Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create an iframe and attach onload event to it

I have created a iframe dynamically and added a src attribute to it. Then I have appended this iframe to body of the page. Know I want to attach an onload event to iframe to read the iframe content. Can somebody suggest how do I do that?

frame = document.createElement('iframe');
frame.setAttribute('src','http://example.com');
body.appendChild(frame);
frame.onload = function(){
    alert('hi'); // here I want to read the content in the frame.
}
like image 940
sushil bharwani Avatar asked May 31 '11 06:05

sushil bharwani


2 Answers

You can add a load event listener to the iframe's contentWindow, which is just like any other Window.

Here's an example:

      iframe = document.createElement('iframe')
      iframe.setAttribute('src', 'https://example.com/')

      document.getElementsByTagName('body')[0].appendChild(iframe)
      const onLoaded = function() {
        console.log('iframe loaded');
      }
      if (iframe.contentWindow.document.readyState === 'complete') {
        console.log('already loaded')
        onLoaded()
      } else {
        iframe.contentWindow.addEventListener('load', onLoaded)
      }
like image 199
Tyler Rick Avatar answered Sep 23 '22 17:09

Tyler Rick


Some browsers do have the onload event for an iframe, first you should try to attach it before setting the iframe's src attribute.

I'd avoid using it altogether since in certain browsers it might not fire under certain conditions (e.g. the target was in cache in IE).

You could user a timer to check if the frame's contentWindow's readystate is complete

var inter = window.setInterval(function() {
    if (frame.contentWindow.document.readyState === "complete") {
      window.clearInterval(inter);
      // grab the content of the iframe here
    }
}, 100);
like image 34
Asaf Avatar answered Sep 23 '22 17:09

Asaf