jQuery 检测 iframe 何时开始加载新 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17315013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:48:40  来源:igfitidea点击:

Detect when an iframe starts to load new URL

javascriptjqueryeventsiframe

提问by Philipp

How can I detect that an iframe on my page startsto load a new page?

如何检测页面上的 iframe开始加载新页面?

Our situation is:

我们的情况是:

  • When iFrame content starts to change we need to display a "loading" animation and hide the search-box.
  • I know how to handle the "iframe has finished to load" event (to hide the animation) but not how to catch the initial "starting to change" event...
  • 当 iFrame 内容开始改变时,我们需要显示“加载”动画并隐藏搜索框。
  • 我知道如何处理“iframe 已完成加载”事件(以隐藏动画),但不知道如何捕获初始的“开始更改”事件...

Note: I can attach jquery "click" hook to the links on the menu, which will work. However, inside the iframe content there are many cross-reference links, and the "change" event also applies for them! So we need to catch event when user clicks on a link inside the iframeor when the iframe src is changed via javascript- because we also want to show the loading-animation and hide the search-box.

注意:我可以将 jquery "click" 挂钩附加到菜单上的链接,这将起作用。但是,iframe 内容内部有很多交叉引用链接,“change”事件也适用于它们!因此,当用户单击 iframe 内的链接通过 javascript 更改 iframe src时,我们需要捕获事件- 因为我们还想显示加载动画并隐藏搜索框。

采纳答案by Bruce

I found a better solution if iframe and the container page is same origin, don't have to put extra code into the inner page:

如果 iframe 和容器页面是同源的,我找到了一个更好的解决方案,不必将额外的代码放入内页:

<iframe src="same-origin.com" onload="content_finished_loading(this)"></iframe>
<script>
    var indicator = document.querySelector('.loading-indicator');
    var content_start_loading = function() {
        indicator.style.display = 'block';
    };

    var content_finished_loading = function(iframe) {
        indicator.style.display = 'none';
        // inject the start loading handler when content finished loading
        iframe.contentWindow.onunload = content_start_loading;
    };
</script>

回答by Philipp

I came up with following solution - which is only possible because we control the content of the iframe content and the host-window

我想出了以下解决方案 - 这只是因为我们控制 iframe 内容和主机窗口的内容

Inside the iframe we add following script to the page footer (all pages use the same template, so this is a change to a single file)

在 iframe 中,我们将以下脚本添加到页脚(所有页面使用相同的模板,因此这是对单个文件的更改)

<script>
window.onunload = function() {
    // Notify top window of the unload event
    window.top.postMessage('iframe_change', '*');
};
</script>

Inside the host-window we add this script to monitor the iframe state

在主机窗口中,我们添加此脚本来监视 iframe 状态

function init_content_monitor() {
    var content = jQuery('.iframe');

    // The user did navigate away from the currently displayed iframe page. Show an animation
    var content_start_loading = function() {
        alert ('NOW: show the animation');
    }

    // the iframe is done loading a new page. Hide the animation again
    var content_finished_loading = function() {
        alert ('DONE: hide the animation');
    }

    // Listen to messages sent from the content iframe
    var receiveMessage = function receiveMessage(e){
        var url = window.location.href,
            url_parts = url.split("/"),
            allowed = url_parts[0] + "//" + url_parts[2];

        // Only react to messages from same domain as current document
        if (e.origin !== allowed) return;
        // Handle the message
        switch (e.data) {
            case 'iframe_change': content_start_loading(); break;
        }
    };
    window.addEventListener("message", receiveMessage, false);

    // This will be triggered when the iframe is completely loaded
    content.on('load', content_finished_loading);
}

回答by T.Todua

There is already a possible solution at: iFrame src change event detection?

已经有一个可能的解决方案:iFrame src change event detection?

However, if you want to manipulate the target page, then it is not needed to touch the iframe-target file content. Just add the correct JS code in parent page and it can access SAME-ORIGIN iframe. I used something like this:

但是,如果您要操作目标页面,则不需要触摸 iframe-target 文件内容。只需在父页面中添加正确的 JS 代码,它就可以访问 SAME-ORIGIN iframe。我使用了这样的东西:

<iframe id="xyz" ....>
.....
<script>
var iframeElement = document.getElementById("xyz");
var iframe_El = iframeElement.contentDocument || iframeElement.contentWindow.document;
// manipulate iframe_El wih "on complete" events and like that.
....
</script>

more at: https://jsfiddle.net/Lnb1stc8/

更多信息:https: //jsfiddle.net/Lnb1stc8/

回答by user6242961

When you are creating the iframe dynamically, include the ONLOAD event like so...

当您动态创建 iframe 时,请像这样包含 ONLOAD 事件...

F=document.createElement('iframe');
F.onload=function(){
    UpdateDetails(
        this.contentWindow.document.title,
        this.contentWindow.location
    );
};
F.src='some url';
document.getElementById('Some_Container').appendChild(F);

The onload event will now constantly update the global variables below via the function below, as the user surfs the net:

当用户上网时,onload 事件现在将通过下面的函数不断更新下面的全局变量:

var The_Latest_Title='';
var The_Latest_URL='';
function UpdateDetails(Title,URL){
    The_Latest_Title=Title;
    The_Latest_URL=URL;
}