javascript - How to run a function when iframe src changes? - Stack Overflow

How can i run a function when the src of an iframe is changed? The iframe displays a site that is not o

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742269663a4412459.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信