乐闻世界logo
搜索文章和话题

How to detect when an iframe starts to load new url?

2个答案

1
2

When detecting when an iframe begins loading a new URL, JavaScript event listeners are commonly used. Here are some methods to monitor when an iframe starts loading a new URL:

Method 1: Using the onload Event

To detect when the iframe begins loading a new URL, you can listen for the onload event. However, it only informs us when the iframe has finished loading and does not directly indicate the start time. Nevertheless, we can initialize certain operations before setting the new src attribute to simulate detecting the start of loading:

javascript
var iframe = document.getElementById('myIframe'); // Function executed when the iframe begins loading a new URL function onIframeStartLoad() { console.log('Starting to load a new URL...'); } // Function executed when the iframe has completed loading a new URL function onIframeLoad() { console.log('New URL loaded successfully'); } // Listen for the `onload` event on the iframe iframe.onload = onIframeLoad; // Change the iframe's `src` attribute to start loading a new URL iframe.src = 'https://example.com'; // Before setting `src`, we can trigger the start of loading detection onIframeStartLoad(); // Manually invoke the start detection function

Method 2: Using addEventListener Method

We can use addEventListener to attach a load event listener to the iframe, which is better suited for modern browsers and dynamic event management:

javascript
var iframe = document.getElementById('myIframe'); iframe.addEventListener('load', function() { console.log('New URL loaded successfully'); }); // Before changing the iframe's `src` attribute, we can perform certain operations console.log('Starting to load a new URL...'); iframe.src = 'https://example.com';

Method 3: Using MutationObserver

If you want to detect when the src attribute of the iframe is changed (not necessarily when loading completes), you can use MutationObserver. This allows you to monitor DOM changes, such as attribute modifications:

javascript
var iframe = document.getElementById('myIframe'); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { if (mutation.type === 'attributes' && mutation.attributeName === 'src') { console.log('iframe src attribute changed, new URL is starting to load'); } }); }); observer.observe(iframe, { attributes: true // Configure the observer to watch for attribute changes }); // Change the iframe's `src` attribute iframe.src = 'https://example.com';

Method 4: Using beforeunload Event

In specific cases where you want to detect when the iframe begins loading a new page as the original page is about to unload, you can use the beforeunload event:

javascript
var iframe = document.getElementById('myIframe'); iframe.contentWindow.onbeforeunload = function() { console.log('iframe is about to start loading a new page'); }; // Change the iframe's `src` attribute iframe.src = 'https://example.com';

Note that this method may be subject to cross-origin policy restrictions because it requires accessing the contentWindow object of the iframe.

In summary, typically, we can detect when an iframe begins loading a new URL by listening for the load event or using MutationObserver. Performing necessary operations before setting the new src attribute helps identify the start of loading. In practical applications, the choice of method depends on specific requirements and scenarios.

2024年6月29日 12:07 回复

I've devised the following solution – it's the only viable approach given that we control both the iframe content and the host window content.

Within the iframe, we add the following script to the page footer (since all pages share the same template, this constitutes a single-file change).

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

In the host window, we add this script to monitor the iframe status.

javascript
function init_content_monitor() { var content = jQuery('.iframe'); // When the user navigates away from the currently displayed iframe page, display an animation var content_start_loading = function() { alert('NOW: show the animation'); } // When the iframe finishes 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 the same domain as the 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); }
2024年6月29日 12:07 回复

你的答案