Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling an IFRAME with dynamic content from JavaScript

I have an IFRAME that should be filled with content from JavaScript. Had the content be on the server all I had to do is:

    function onIFrameFill() {
         myIframe.location.href = "HelloWorld.html";
     }

But the content I have is a HTML page generated on the client and represented as a string (I have not much influence on it). How can I populate the content of the my iframe programatically?

like image 942
user256890 Avatar asked Apr 19 '10 08:04

user256890


People also ask

Does iframe work if javascript is disabled?

If a user has javascript disabled, iframes will work. An iframe tag has attributes “height” and “width,” which allows the designer great latitude with dimensions and format like 300×250 , 728×90 depending on the Ad size. Iframe tag can appear anywhere on the page and several iframes can be added if wished to.

Can you put javascript in an iframe?

Either your src-url will be used or your code between the iframe-tags will be used; never both. This means that there is no way to "embed a javascript into an iframe". The only way to get your script in there would be to add it to the source page that you're loading into the iframe.

What is iframe Srcdoc?

The srcdoc attribute specifies the HTML content of the page to show in the inline frame. Tip: This attribute is expected to be used together with the sandbox and seamless attributes. If a browser supports the srcdoc attribute, it will override the content specified in the src attribute (if present).

Can you modify an iframe?

To alter an iframe element within a variation, click the element in the Visual Editor. When the element is selected, a menu will appear that shows the actions you can take. Edit Element... > Edit iFrame: You can modify the iframe source ( src ) attribute when using Optimizely as an AB testing tool.


2 Answers

I think you're looking for something like:

var iframeDoc = myIframe.contentWindow.document;
iframeDoc.open();
iframeDoc.write('hello world');
iframeDoc.close();
like image 82
Jeffery To Avatar answered Sep 21 '22 20:09

Jeffery To


Tried setting .innerHTML but that does not work. Solution by Jeffery To works. Just want to add that myIframe.contentWindow might not work in old browsers (read IE old versions) so you can do

var iFrameWindow = myIframe.contentWindow || myIframe.documentWindow;
var iFrameDoc = iFrameWindow.document;

then use the document open(), write() & close() as above.

like image 41
Agraj Avatar answered Sep 21 '22 20:09

Agraj