检测iframe何时开始加载新URL

Phi*_*ipp 40 javascript iframe jquery events

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

我们的情况是:

  • 当iFrame内容开始变化时,我们需要显示"加载"动画并隐藏搜索框.
  • 我知道如何处理"iframe已完成加载"事件(隐藏动画)但不知道如何捕获最初的"开始更改"事件...

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

Bru*_*uce 26

我找到了一个更好的解决方案,如果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>
Run Code Online (Sandbox Code Playgroud)


Phi*_*ipp 23

我提出了以下解决方案 - 这是唯一可行的,因为我们控制iframe内容和主机窗口的内容

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

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

在主机窗口内,我们添加此脚本以监控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);
}
Run Code Online (Sandbox Code Playgroud)