Example 1 — Safe Stream into an Iframe
Write markup into an iframe document, then close the stream.
const iframe = document.getElementById("preview");
const doc = iframe.contentDocument;
doc.open();
doc.write("<p>Hello world!</p>");
doc.write("<p>I am a fish</p>");
doc.close();
console.log(doc.querySelectorAll("p").length); // 2 How It Works
- Sandbox. Use
contentDocumentso the host page is never cleared. - Open.
open()starts a fresh document stream. - Write. Each string is parsed as HTML into that stream.
- Close.
close()finishes parsing so the iframe shows the result.

