Assuming I have no control over the content in the iframe, is there any way that I can detect a src change in it via the parent page? Some sort of onload maybe?
My last resort is to do a 1 second interval test if the iframe src is the same as it was before, but doing this hacky solution would suck.
I'm using the jQuery library if it helps.
Answer based on JQuery < 3
As mentioned by subharb, as from JQuery 3.0 this needs to be changed to:
https://jquery.com/upgrade-guide/3.0/#breaking-change-load-unload-and-error-removed
If you have no control over the page and wish to watch for some kind of change then the modern method is to use
MutationObserver
An example of its use, watching for the
src
attribute to change of aniframe
Output after 3 seconds
On jsFiddle
Posted answer here as original question was closed as a duplicate of this one.
Since version 3.0 of Jquery you might get an error
Which can be easily fix by doing
The iframe always keeps the parent page, you should use this to detect in which page you are in the iframe:
Html code:
Js:
Here is the method which is used in Commerce SagePay and in Commerce Paypoint Drupal modules which basically compares
document.location.href
with the old value by first loading its own iframe, then external one.So basically the idea is to load the blank page as a placeholder with its own JS code and hidden form. Then parent JS code will submit that hidden form where its
#action
points to the external iframe. Once the redirect/submit happens, the JS code which still running on that page can track yourdocument.location.href
value changes.Here is example JS used in iframe:
And here is JS used in parent page:
Then in temporary blank landing page you need to include the form which will redirect to the external page.
You may want to use the
onLoad
event, as in the following example:The alert will pop-up whenever the location within the iframe changes. It works in all modern browsers, but may not work in some very older browsers like IE5 and early Opera. (Source)
If the iframe is showing a page within the same domain of the parent, you would be able to access the location with
contentWindow.location
, as in the following example: