At work recently, I had a use-case where I needed to show a preview of some HTML dynamically sent from the server inside of an iFrame.
It is quite possible before you found this blog post, you found a solution that looked something like this:
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
This will work for simple HTML and instances where the HTML isn’t overly long. But, if your use-case is like mine, the HTML the server is returning is massive. In my case, I had base64 encoded images making the returned HTML huge.
The above solution will not work for overly large strings. The solution is to create a blob of type text/html
and pass in the HTML. Finally, use createObjectUrl
and pass it to the source of the iFrame.
const iframeContainer = document.querySelector('#container'); const iframe = document.createElement('iframe'); iframe.frameBorder = 'none'; const finalHtml = ` <!DOCTYPE html> <html> <body>${html}</body> </html>`; const blob = new Blob([finalHtml], {type: 'text/html'}); iframe.src = window.URL.createObjectURL(blob); iframeContainer.innerHTML = ''; iframeContainer.appendChild(iframe);
This will work for overly large strings. It will also work for special characters and any weird caveats of the string approach above, which will not always work.