Detect when an iframe starts to load new URL

前端 未结 4 1946
孤街浪徒
孤街浪徒 2021-01-31 02:07

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

Our situation is:

  • When iFrame content starts to change we need to di
4条回答
  •  灰色年华
    2021-01-31 02:55

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

    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)

    
    

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

    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);
    }
    

提交回复
热议问题