admin管理员组

文章数量:1330604

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...

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...

Share Improve this question asked Sep 14, 2010 at 16:03 DavidDavid 14k16 gold badges46 silver badges51 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 5

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 pare 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.

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:

  • http://jsbin./uzucu4/2

I'm relatively sure you cannot see when that happens.

本文标签: javascriptHow to run a function when iframe src changesStack Overflow