Chrome Violation when using document.write with generated iFrame source - alternative?

447 Views Asked by At

I understand using document.write is discouraged for various reasons, however I'm using it to inject programmatically html generated into an iframe widget.

var iframe = document.createElement('iframe')
document.body.appendChild(iframe)
iframe.contentWindow.document.open()
iframe.contentWindow.document.write(generateHtml())
iframe.contentWindow.document.close()

This method works perfectly for my use case, however Chrome warns against document.write as you'd expect: [Violation] Avoid using document.write().

Is it possible to suppress or satisfy the warning or do I have to live with it?

I believe it's the best method to inject html to an iframe, considering other ways that I have tried:

  • Setting the src directly with data:text/html; ... - limitations around length
  • Setting srcdoc with html - This is my fall back, but browser support could be an issue
  • Encode html using btoa base64 and set src directly with data:text/html;base64,... - This didn't encode properly and yielded Invalid regular expression: Range out of order in character class

Appreciate any tips!

1

There are 1 best solutions below

4
syduki On BEST ANSWER

One more method is to create a document from html with DOMParser, then patch the iframe document with that:

const html = `
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>Hello</title>
        </head>
        <body>World!</body>
    </html>
`;
const iframe = document.createElement('iframe');
iframe.addEventListener('load', () => {
    const docOld = iframe.contentWindow.document;
    const docNew = new DOMParser().parseFromString(html, 'text/html');
    docOld.insertBefore(docNew.doctype, docOld.firstChild);
    docOld.replaceChild(docNew.documentElement, docOld.documentElement);
});
document.body.appendChild(iframe);