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 yieldedInvalid regular expression: Range out of order in character class
Appreciate any tips!
One more method is to create a
documentfromhtmlwith DOMParser, then patch theiframedocument with that: