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>
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With