capricorn86 / happy-dom

A JavaScript implementation of a web browser without its graphical user interface
MIT License
3.41k stars 207 forks source link

DOMParser.parseFromString TypeError: undefined is not an object (evaluating 'new window.HTMLDocument') #1562

Open bitofbreeze opened 1 month ago

bitofbreeze commented 1 month ago

Describe the bug Using bun, I get the following error when trying to use DOMParser.parseFromString:

84 |      */
85 |     #createDocument(mimeType) {
86 |         const window = this[PropertySymbol.window];
87 |         switch (mimeType) {
88 |             case 'text/html':
89 |                 return new window.HTMLDocument();
                                ^
TypeError: undefined is not an object (evaluating 'new window.HTMLDocument')
      at #createDocument (/node_modules/happy-dom/lib/dom-parser/DOMParser.js:89:28)
      at parseFromString (/node_modules/happy-dom/lib/dom-parser/DOMParser.js:22:34)

Bun v1.1.30 (macOS arm64)

To Reproduce Steps to reproduce the behavior: Run a script with bun that does something like:

import { DOMParser } from "happy-dom";

const parser = new DOMParser();
    const page = parser.parseFromString(
        `
<!DOCTYPE html>
<html>
  <body>
    <div>hi</div>
  </body>
</html>
`,
        "text/html",
    );

Expected behavior A successfully parsed document

Screenshots

Device:

Additional context Add any other context about the problem here.

OlaviSau commented 4 weeks ago

I found another bug related to this feature (lmk if I should report as a different issue) - it seems like this string <body><x></x>Example Text will not detect body as the root, although it should - this will break HappyDOM for use in frameworks like Angular. (new window.DOMParser()).parseFromString("<body><x></x>Example Text", "text/html").body.innerHTML Chrome: <x></x>Example Text HappyDOM: <body><x></x>Example Text</body>. Looks like the cause is in: https://github.com/capricorn86/happy-dom/blob/afd256b2e4f0260adb22432c1a354f558cda6623/packages/happy-dom/src/dom-parser/DOMParser.ts#L44 tagName BODY should match as well in order to correctly detect documentTypeNode. It somewhat seems like it's the intent of the next check to catch this case, but I am not sure why that is not working or if the intent is different. node[PropertySymbol.nodeType] === NodeTypeEnum.documentTypeNode @capricorn86