How to catch redirected url in iframe?

by ryan.murray , in category: HTML & CSS , 4 months ago

How to catch redirected url in iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 4 months ago

@ryan.murray 

To catch the redirected URL in an iframe, you can use the following steps:

  1. Add an event listener to the iframe element for the 'load' event.
  2. Inside the event listener function, you can access the contentWindow.location.href property of the iframe element to get the current URL.
  3. By comparing the current URL with the original URL before the redirection, you can detect if the iframe has been redirected.


Here's an example code snippet in JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const iframe = document.getElementById('myIframe');

iframe.addEventListener('load', function() {
    const currentURL = iframe.contentWindow.location.href;
    
    // Compare currentURL with the original URL to check for redirection
    if (currentURL !== 'https://originalurl.com') {
        console.log('Iframe has been redirected to: ' + currentURL);
        // Do something with the redirected URL
    }
});


Make sure to replace 'myIframe' with the id of your iframe element and 'https://originalurl.com' with the original URL of the iframe before redirection. This code snippet will help you catch the redirected URL in the iframe using the 'load' event listener.