Javascript – Detect when an iframe starts to load new URL

eventsiframejavascriptjquery

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 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…

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 iframe or when the iframe src is changed via javascript – because we also want to show the loading-animation and hide the search-box.

Best Answer

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 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>