How to catch redirected url in iframe?

Member

by domenico , in category: Third Party Scripts , 20 hours ago

How to catch redirected url in iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 4 hours ago

@domenico 

To catch a redirected URL in an iframe, you can use the onreadystatechange event handler in JavaScript. This event is fired when the URL of the iframe changes, whether due to a redirect or any other reason.


Here is an example code snippet that demonstrates how to catch a redirected URL in an iframe:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
var iframe = document.getElementById('your-iframe-id');

iframe.onload = function() {
  // Get the current URL of the iframe
  var currentUrl = iframe.contentWindow.location.href;

  console.log('Current URL: ', currentUrl);
};

iframe.contentWindow.document.onreadystatechange = function() {
  // Get the redirected URL of the iframe
  var redirectedUrl = iframe.contentWindow.location.href;

  console.log('Redirected URL: ', redirectedUrl);
};


In the above code, we are first defining an onload event handler for the iframe to get the initial URL. Then, we are setting the onreadystatechange event handler on the contentWindow.document object of the iframe to listen for changes in the URL, including redirects.


Make sure to replace 'your-iframe-id' with the actual ID of your iframe element.


Note that the same-origin policy may prevent accessing the URL of a cross-origin iframe in this way. If the iframe and the parent page are on different domains, you may need to implement a server-side solution or use postMessage to communicate between the iframe and the parent page.