Pmi*_*lan 2 javascript jquery events jquery-events
在我的站点中,我在 iframeB 中使用 iframeA,并且当 iframeA 更改其内容时,我必须设置 src。我只能使用 onload 事件设置它,但是在加载站点时会调用它。我正在寻找一些事件或触发器,它可以帮助我在开始加载之前检测位置/src 更改。我不想在 src 设置之前等待整个页面加载。我无法直接访问 iframeA(只是下面的脚本)
一些代码:
var myframe = document.getElementById('frameB').contentWindow.document.getElementById('frameA');
myframe.onload=function (funcname) {...};
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)
它利用unload事件。每当卸载页面时,预计会开始加载新页面。但是,如果您侦听该事件,您将获得当前 URL,而不是新 URL。通过添加 0 毫秒延迟的超时,然后检查 URL,您将获得新的 iframe URL。
但是,unload每次加载新页面时都会删除该侦听器,因此必须在每个load.
不过,该函数会处理所有这些。要使用它,您只需执行以下操作:
iframeURLChange(document.getElementById("myframe"), function (url) {
console.log("URL changed:", url);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22891 次 |
| 最近记录: |