Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

document.write is not working as browsers #1376

Open
aralroca opened this issue Apr 1, 2024 · 0 comments
Open

document.write is not working as browsers #1376

aralroca opened this issue Apr 1, 2024 · 0 comments
Labels
bug Something isn't working high priority

Comments

@aralroca
Copy link
Contributor

aralroca commented Apr 1, 2024

After doing this:

const doc = document.implementation.createHTMLDocument();
doc.open();
doc.write('<html>')
doc.write('<head>')
doc.write('<title>Title</title>')
doc.write('</head>')
doc.write('<body>')
doc.write('<span>Body</span>')
doc.write('</body>')
doc.write('</html>')
doc.close();

console.log(doc.documentElement.outerHTML)

I expect:

<html>
  <head>
    <title>Title</title>
  </head>
  <body>
    <span>Body</span>
  </body>
</html>

(Same behavior in Chrome, Safari and Firefox)

But I'm getting this error:

DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.

I see that is related with this code:

https://github.com/aralroca/happy-dom/blob/d7c7d45b9190663ca545aa6184a28eb812ab46ca/packages/happy-dom/src/nodes/document/Document.ts#L897-L904

Here is creating the body twice, and then in the head is using the body that is not appended. However, changing this:

-documentElement.appendChild(this.createElement('body'));
+documentElement.appendChild(body);

Resolves that it does not crash, but the behavior is different and I don't know how to solve it (please, some help). Now the HTML generated is this one:

<html>
  <head>
  </head>
  <body>
    <head>
    </head>
    <title>Title</title>
    <span>Body</span>
  </body>
</html>

I think this is because of the doc.open() not behaving properly. So we can reproduce the same HTML in browsers removing the doc.open():

const doc = document.implementation.createHTMLDocument();
-doc.open();
doc.write('<html>')
doc.write('<head>')
doc.write('<title>Title</title>')
doc.write('</head>')
doc.write('<body>')
doc.write('<span>Body</span>')
doc.write('</body>')
doc.write('</html>')
-doc.close();

console.log(doc.documentElement.outerHTML)

But this is not what we want. This is necessary to process HTML in streaming in a separate document and to be able to parse the nodes as they come in.

Note

Same error happens with document.write

Any idea how to solve it? Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working high priority
Projects
None yet
Development

No branches or pull requests

2 participants