最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I detect when source of iframe is changed? - Stack Overflow

programmeradmin1浏览0评论

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', function(){ alert('src 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', function(){ alert('src is changed')});
Share Improve this question edited Jul 2, 2010 at 3:05 Gert Grenander 17.1k6 gold badges41 silver badges43 bronze badges asked Jul 2, 2010 at 2:47 Oguz BilgicOguz Bilgic 3,4807 gold badges38 silver badges60 bronze badges 3
  • Is the iframe pointing at the same domain, or another one? – Nick Craver Commented Jul 2, 2010 at 2:49
  • same domain but , maybe another subdomain. – Oguz Bilgic Commented Jul 2, 2010 at 2:53
  • The problem with most solutions as far as I can tell is that the "onload" event is triggered when the iframe loads, not when you navigate to another page inside the iframe. And similarly, as far as I can tell, the "src" property does not change either when you navigate inside the iframe. It stays on the original "src". So solutions tracking this property will not work. – Mig Commented Aug 23, 2024 at 9:24
Add a comment  | 

2 Answers 2

Reset to default 13

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)

  1. 暂无评论