繁体   English   中英

如何在加载前获取 Iframe 事件?

[英]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.

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