Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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', function(){ alert('src is changed')});
like image 404
Oguz Bilgic Avatar asked Jul 02 '10 02:07

Oguz Bilgic


2 Answers

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.

like image 81
Daniel Vassallo Avatar answered Sep 23 '22 15:09

Daniel Vassallo


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
like image 43
casablanca Avatar answered Sep 23 '22 15:09

casablanca