Dynamically create an iframe and attach onload eve

2019-03-18 16:31发布

I have created a iframe dynamicaly 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://myurl.com');
body.appendChild(frame);
frame.onload = function(){
    alert('hi'); // here i want to read the content in the frame.
}

3条回答
做个烂人
2楼-- · 2019-03-18 16:49

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);
查看更多
不美不萌又怎样
3楼-- · 2019-03-18 17:03

I doubt you can attach an onload event to an iframe. It will not work on all browsers. You can on the other hand check if the iframe was loaded by:

window.onload=function()
{
var iframe=document.getElementById('myframe');
if(iframe) 
    alert('The iframe has just been loaded.');
}

Or use AJAX to load the content in your container. With AJAX you can set a proper load-complete event.

查看更多
干净又极端
4楼-- · 2019-03-18 17:09

I just tried this and it worked in Chrome:

var iframe = document.createElement('iframe');
// append iframe to DOM however you like then:
iframe.contentWindow.parent.location.href // properly gives parent window's href.

W3school says contentWindow is supported in all major browsers.

查看更多
登录 后发表回答