Skip to content

Commit

Permalink
capricorn86#759@patch: Spurious HTML comments in embedded scripts.
Browse files Browse the repository at this point in the history
  • Loading branch information
fcapolini committed Feb 16, 2023
1 parent 2b8de28 commit 1d669da
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
1 change: 1 addition & 0 deletions packages/happy-dom/src/config/PlainTextElements.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default ['style', 'script'];
10 changes: 9 additions & 1 deletion packages/happy-dom/src/xml-parser/XMLParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import INode from '../nodes/node/INode';
import IElement from '../nodes/element/IElement';
import HTMLLinkElement from '../nodes/html-link-element/HTMLLinkElement';
import IDocumentFragment from '../nodes/document-fragment/IDocumentFragment';
import PlainTextElements from '../config/PlainTextElements';

const MARKUP_REGEXP = /<(\/?)([a-z][-.0-9_a-z]*)\s*([^<>]*?)(\/?)>/gi;
const COMMENT_REGEXP = /<!--(.*?)-->|<([!?])([^>]*)>/gi;
Expand Down Expand Up @@ -51,7 +52,14 @@ export default class XMLParser {

if (parent && match.index !== lastTextIndex) {
const text = data.substring(lastTextIndex, match.index);
this.appendTextAndCommentNodes(document, parent, text);
if (
parent.nodeType === Node.ELEMENT_NODE &&
PlainTextElements.includes((<IElement>parent).tagName.toLowerCase())
) {
parent.appendChild(document.createTextNode(text));
} else {
this.appendTextAndCommentNodes(document, parent, text);
}
}

if (isStartTag) {
Expand Down
32 changes: 31 additions & 1 deletion packages/happy-dom/test/dom-parser/DOMParser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,14 @@ describe('DOMParser', () => {
let window;

beforeEach(() => {
window = new Window();
window = new Window({
settings: {
disableJavaScriptFileLoading: true,
disableJavaScriptEvaluation: true,
disableCSSFileLoading: true,
enableFileSystemHttpRequests: false
}
});
domParser = new window.DOMParser();
});

Expand Down Expand Up @@ -55,5 +62,28 @@ describe('DOMParser', () => {
`.replace(/[\s]/gm, '')
);
});

it('Correctly parses JS script w/ `<!` in it', () => {
const newDocument = domParser.parseFromString(
`<html>
<body>
<script>
var test = {className:"meta",begin:/<![a-z]/,end:/>/,contains:[t,i,l,c]};
</script>
</body>
</html>`,
'text/html'
);
// Spurious comment `<!--[a-z]/,end:/-->` should be solved
expect(new XMLSerializer().serializeToString(newDocument).replace(/\s{1,}/, ' ')).toBe(
`<html>
<body>
<script>
var test = {className:"meta",begin:/<![a-z]/,end:/>/,contains:[t,i,l,c]};
</script>
</body>
</html>`.replace(/\s{1,}/, ' ')
);
});
});
});

0 comments on commit 1d669da

Please sign in to comment.