动态创建iframe并将onload事件附加到它 [英] Dynamically create an iframe and attach onload event to it
问题描述
我已经创建了一个iframe dynamicaly并为其添加了一个src属性。然后我将这个iframe附加到页面的正文。知道我想将一个onload事件附加到iframe以读取iframe内容。有人可以建议我怎么做。
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.
}
推荐答案
有些浏览器确实有onload iframe的事件,首先应该在设置iframe的src属性之前尝试附加它。
Some browsers do have the onload event for an iframe, first you should try to attach it before setting the iframe's src attribute.
我完全避免使用它,因为在某些浏览器中它可能不会在某些条件下触发(例如目标在IE中的缓存中)。
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).
您可以使用计时器来检查框架的contentWindow的readystate是否完整
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);
这篇关于动态创建iframe并将onload事件附加到它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!