简体   繁体   English

iframe加载的事件处理程序未触发

[英]Event handler for iframe loaded not firing

I have an iframe in my HTML, and I want to be notified when it's fully loaded. 我的HTML中有一个iframe,要在其完全加载时得到通知。 I have this testcase: 我有这个测试用例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Test</title>

<script language="javascript" type="text/javascript">
function addListener(el, type, func, capture) {
    if (el.addEventListener){
        el.addEventListener(type, func, capture); 
    } else if (el.attachEvent){
        el.attachEvent('on'+type, func);
    }
}
function addhandlers(frame) {
    addListener(frame, "load", function(e) { onDomLoaded(e); }, true);
}
function onDomLoaded(e) {
    alert("loaded");
}
</script>

</head>
<body>
<form action="#">
<input type="button" value="Add handlers" onclick="addhandlers(window.frames[0]);" />
</form>

<iframe id="frm" height="300" src="test.htm" width="700"></iframe>

</body>
</html>

The test.htm file is just a standard html file with a few regular links to places. test.htm文件只是一个标准的html文件,带有一些指向场所的常规链接。

First I click the Add Handlers button to add the listeners, then I click any link in test.htm inside the iframe. 首先,我单击“添加处理程序”按钮以​​添加侦听器,然后单击iframe中test.htm中的任何链接。 My expectation is that I get an alert, but nothing happens. 我的期望是我会收到警报,但是什么也没发生。 Why, and how do I solve it? 为什么,如何解决? I'm currently looking for a solution that works in firefox and IE (but nothing happens in either browser). 我目前正在寻找在Firefox和IE中都可以使用的解决方案(但是在任何一种浏览器中都没有任何反应)。

A workaround would be to include javascript within test.htm 一种解决方法是将JavaScript包含在test.htm中

test.htm: test.htm:

function addListener(el, type, func, capture) {
    if (el.addEventListener){
            el.addEventListener(type, func, capture); 
    } else if (el.attachEvent){
            el.attachEvent('on'+type, func);
    }
}
function addhandlers(frame) {
        addListener(frame, "load", function(e) { onDomLoaded(e); }, true);
}

function onDomLoaded(e) {  
   window.parent.iframeLoaded()
}

parentpage.htm: parentpage.htm:

function iframeLoaded() {
    alert('loaded');
}

Note that this only works if both files are on the same domain 请注意,这仅在两个文件都在同一域中时才有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM