Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set HTML content into an iframe

I have a HTML string

<html>   <body>Hello world</body> </html>  

and I want to set it to an iframe with JavaScript. I am trying to set the HTML like this:

contentWindow.document.body.innerHTML 

or

contentDocument.body.innerHTML 

or

document.body.innerHTML 

but IE gives "Access is denied." or "Object does not support this property or method." or "Invalid final element to the action." errors.

Here is my full code:

<!DOCTYPE html> <html>   <head>     <script type="text/javascript" src="jquery_1.7.0.min.js"/>     <script type="text/javascript">       $(document).ready(function(){         var htmlString = "<html><body>Hello world</body></html>";         var myIFrame = document.getElementById('iframe1');         // open needed line commentary         //myIFrame.contentWindow.document.body.innerHTML = htmlString;         //myIFrame.contentDocument.body.innerHTML = htmlString;         //myIFrame.document.body.innerHTML = htmlString;         //myIFrame.contentWindow.document.documentElement.innerHTML = htmlString;       });     </script>   </head>   <body>     <p>This is iframe:       <br>       <iframe id="iframe1">       <p>Your browser does not support iframes.</p>       </iframe>   </body> </html> 
like image 904
SBotirov Avatar asked May 12 '13 06:05

SBotirov


People also ask

How do I add HTML content to an iframe?

Answer: Use the jQuery contents() method You can use the jQuery contents() method in combination with the find() , val() and html() methods to insert text or HTML inside an iframe body.

How do I create an iframe embed code?

To embed an iframe in a content page, select Interactive layout, choose the HTML block and paste the iframe code there. You can adjust the iframe width and height properties. To embed an iframe using the Old (Classic) editor, click on the Embed Media icon and paste the code in the appropriate field.

Can you put a div inside an iframe?

Approach 1: For adding additional div's in an iframe, you need to use a wrapper div, that wraps the contents of your intended div and the iframe into one unit. This way you can display the contents of your div along with the iframe embedding to the document/webpage.

Can you style HTML in iframe?

You will not be able to style the contents of the iframe this way. My suggestion would be to use serverside scripting (PHP, ASP, or a Perl script) or find an online service that will convert a feed to JavaScript code. The only other way to do it would be if you can do a serverside include.


1 Answers

You could use:

document.getElementById('iframe1').contentWindow.document.write("<html><body>Hello world</body></html>"); 

Here's a jsFiddle, which works in all major browsers.

Note that instead of contentDocument.write you should use contentWindow.document.write: this makes it work in IE7 as well.

like image 175
tom-19 Avatar answered Oct 14 '22 18:10

tom-19