Reputation: 13999
How can i run a function when the src
of an iframe is changed? The iframe displays a site that is not on my server... When the user clicks on or presses a button inside the iframe, i'd like to perform a function to test whether the src
has changed...
Upvotes: 2
Views: 6527
Reputation: 8169
Let's replace the onload
function with ours. Don't forget to also call their onload
function
function letswatch() {
var myIframe = document.getElementById("myIframe");
var oldonload = myIframe.onload;
if (typeof myIframe.onload != 'function') {
myIframe.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
Our function:
function func() {
alert("changed");
}
Please watch a working example at:
Upvotes: 1
Reputation: 19241
You have no access to the button inside the iframe if it's on a different domain so you can't use the "click" event. The only solution is to use the "load" event on the iframe:
<iframe src=".." onLoad="alert('new page loaded');"></iframe>
The load event will be triggered immediately when the page in the iframe has been loaded and then again when the other page (after changing the src) has been loaded. Then you can compare the first src (store it in a variable at the begin) with the current one and if they are different it means that the src has been changed.
Upvotes: 5