CLOSE

   HTML  CSS  JavaScript  
   Technology    Tricks

Adding Iframe to Webpage Dynamically with given HTML Code

           
 OCTOBER 18, 2019   by studytonight

If you want to create an iframe on your webpage dynamically using JavaScript and want to run some HTML code in it, the first solution that will come to your mind would be to save the HTML code in some file and then use that file in the src attribute of the iframe tag to create an iframe and add the HTML code to it.

But how can you do so dynamically, where you do not have any HTML file to show inside the iframe, rather you just have the HTML/CSS code.

Well, if this is the problem you are facing, you are at the right place.

Let's start with a basic solution to this problem. The code below can be used to add simple HTML code, to a dynamically created iframe in your HTML page using JavaScript.

var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
document.body.appendChild(iframe);

But this code will not work for complex HTML code. But one thing is for sure, that we will have to use document.createElement('iframe') to create an iframe dynamically using JavaScript, and we will have to append it to the DOM of our HTML page, for which we can either simply add the iframe to the <body> tag like in the above example, or we can add the iframe inside a particular div tag.

Below is the code, using which we can create an iframe dynamically and then add out HTML code to it.

var iframe = document.createElement('iframe');

// div tag in which iframe will be added should have id attribute with value myDIV
document.getElementById("myDIV").appendChild(iframe);

// provide height and width to it
iframe.setAttribute("style","height:100%;width:100%;");
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(htmlcode);
iframe.contentWindow.document.close();

In the code above, the variable htmlcode will hold the HTML code that you want to run inside the iframe.




Code Explanation:

In the JavaScript code above, we have first used the document.createElement() function to create an iframe element. Then we have used the appendChild() function to append it to some DOM element on our HTML page, in this case a <div> tag with id attribute as myDIV.

Then we opened the iframe, added the HTML code which we want to run inside the iframe using the document.write() function, and then we closed the iframe element.

This technique will be helpful for you if you want to open some user specified code in an iframe dynamically and show output.


SHARE YOUR THOUGHTS WITH US!