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

时间:2021-03-15 23:51:26

I have an iframe in my HTML, and I want to be notified when it's fully loaded. I have this testcase:

我的HTML中有一个iframe,我希望在它完全加载时收到通知。我有这个测试用例:

<!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. 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).

首先,我单击Add Handlers按钮添加监听器,然后单击iframe内test.htm中的任何链接。我的期望是我得到警报,但没有任何反应。为什么,我该如何解决?我目前正在寻找一个适用于Firefox和IE的解决方案(但在任何一个浏览器中都没有发生)。

1 个解决方案

#1


A workaround would be to include javascript within test.htm

解决方法是在test.htm中包含javascript

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:

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

Note that this only works if both files are on the same domain

请注意,这仅适用于两个文件位于同一域中的情况

#1


A workaround would be to include javascript within test.htm

解决方法是在test.htm中包含javascript

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:

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

Note that this only works if both files are on the same domain

请注意,这仅适用于两个文件位于同一域中的情况