• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

I Like Kill Nerds

The blog of Australian Front End / Aurelia Javascript Developer & brewing aficionado Dwayne Charrington // Aurelia.io Core Team member.

  • Home
  • Aurelia 2
  • Aurelia 1
  • About
  • Aurelia 2 Consulting/Freelance Work

How To Create An Iframe and Populate It With Dynamic HTML In Javascript

Javascript · August 25, 2020

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.

Dwayne

Leave a Reply Cancel reply

0 Comments
Inline Feedbacks
View all comments

Primary Sidebar

Popular

  • The Quad Cortex Desktop Editor is Finally Announced
  • Thoughts on the Flipper Zero
  • NBN Box Installed Inside of Garage, Where Do You Put The Modem?
  • How To Install Eufy Security Cameras Without Drilling or Using Screws
  • Smoke Detector Randomly Goes Off Early Hours of The Morning

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz