开发者

How can I detect when source of iframe is changed?

I want to detect when user clicks a link in iframe and changes the source of iframe, because I want to resize it. Also I use jQuery. What is the best way to detect this?

Actually I need something like this (this example is in jQuery, it does not work, I imagined this)

$('#iframe').live('load', func开发者_运维知识库tion(){ alert('src is changed')});


You may want to use the onLoad event, as in the following example:

<iframe src="/test.html" onLoad="alert(this.contentWindow.location);"></iframe>

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)

Note that you will not be able to access the contentWindow.location if the iframe is in a different domain or sub-domain, but the onLoad event will still fire.


This isn't an exactly clean solution, but it will work: you can create a timer that periodically checks if the iframe source has changed.

var prevSrc = '';
function check() {
  var curSrc = $('#iframe').attr('src');
  if (curSrc != prevSrc) {
    // source has changed; do something
    prevSrc = curSrc;
  }
}

window.setInterval(check, 1000); // 1 sec - this can be anything you want
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜