[英]How can I get Iframe event before load?
在我的站点中,我在 iframeB 中使用 iframeA,并且当 iframeA 更改其内容时,我必须设置 src。 我只能使用 onload 事件设置它,但是在加载站点时会调用它。 我正在寻找一些事件或触发器,它可以帮助我在开始加载之前检测位置/src 更改。 我不想在 src 设置之前等待整个页面加载。 我无法直接访问 iframeA(只是下面的脚本)
一些代码:
var myframe = document.getElementById('frameB').contentWindow.document.getElementById('frameA');
myframe.onload=function (funcname) {...};
检查这个主旨还是我的回答这个问题。 那里的代码正是这样做的:
function iframeURLChange(iframe, callback) {
var unloadHandler = function () {
// Timeout needed because the URL changes immediately after
// the `unload` event is dispatched.
setTimeout(function () {
callback(iframe.contentWindow.location.href);
}, 0);
};
function attachUnload() {
// Remove the unloadHandler in case it was already attached.
// Otherwise, the change will be dispatched twice.
iframe.contentWindow.removeEventListener("unload", unloadHandler);
iframe.contentWindow.addEventListener("unload", unloadHandler);
}
iframe.addEventListener("load", attachUnload);
attachUnload();
}
它利用unload
事件。 每当卸载页面时,预计会开始加载新页面。 但是,如果您侦听该事件,您将获得当前 URL,而不是新 URL。 通过添加 0 毫秒延迟的超时,然后检查 URL,您将获得新的 iframe URL。
但是,每次加载新页面时都会删除unload
侦听器,因此必须在每次load
重新添加。
不过,该函数会处理所有这些。 要使用它,您只需执行以下操作:
iframeURLChange(document.getElementById("myframe"), function (url) {
console.log("URL changed:", url);
});
您还可以尝试采用检测 iframe 何时离开当前位置的方法。 这在某些情况下可能很有用。 为此,请将以下代码放入 iFarme 源中。
$(window).on('beforeunload', function () {
alert('加载前...');
});
什么会改变 iframe 的来源? 如果您有权访问该代码,那么您就可以执行onload
函数中的任何操作。
如果链接的target
属性设置为 iframe 并且源正在更改,那么您可以劫持链接点击:
$('a[target="frameB"]').bind('click', function () {
//run your onload code here, it will run as the iframe is downloading the new content
});
另外,顺便提一下,您可以像这样在 jQuery 中为load
事件绑定一个事件处理程序:
$('#frameB').bind('load', function () {
//run onload code here
});
站点 -> 框架 B -> 框架 A
$("#frameB").contents().find("#frameA").bind('load', function () {
//load code here
});
这将选择#frameB
元素(即在当前顶级 DOM 中),获取其内容,找到#frameA
元素,然后为load
事件绑定事件处理程序。
请注意,此代码必须在#frameB
加载并已存在于其DOM 中的#frameA
元素之后运行。 像这样的事情可能是个好主意:
$('#frameB').bind('load', function () {
$(this).contents().find('#frameA').bind('load', function () {
//run load code here
});
});
#frameB
元素中的链接:
$('#frameB').contents().find('a[target="frameA"]').bind('click', function () {
/*run your code here*/
});
这将在#frameB
元素中找到其target
属性设置为frameA
任何链接,并添加一个click
事件处理程序。
同样,这仅在#frameB
iframe 元素已加载(或至少进入document.ready
事件)时才有效,因此您可以选择它的元素。
我认为将带有适当事件处理程序的内联onload
属性添加到iframe
标记将解决您的问题。
function onIframeLoad(){
//Write your code here
}
标记更改
<iframe src='..' onload='onIframeLoad()' />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.