views:

52

answers:

2

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')});
+3  A: 

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.

Daniel Vassallo
but I think `onload` will also trigger when refresh iframe...
Reigel
Yes, it will. Is that a problem?
Daniel Vassallo
yes I guess `How can I detect when ` **source** ` of iframe is changed?`
Reigel
@Reigel: If the iframe is pointing to a page within the same domain, the OP can check `this.contentWindow.location` to see if the iframe is pointing to a new `scr`. If the iframe is refreshed, the `onLoad` will still fire, but `this.contentWindow.location` will be set to the same value as before. This should be very easy to check.
Daniel Vassallo
+1  A: 

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
casablanca
@casablanca: Do you know if this works even when the iframe navigates to a new page from a link within the iframe itself?
Daniel Vassallo
@Daniel Vassallo No it will not because the 'src' won't change.
Thqr
NB:`curSrc != prevSrc` will be true on the first firing as `prevSrc` will be `null` vs the iframe src.
stormdrain
@casablanca, @Ozaki: I think the OP is asking for an event that is fired when a user navigates from within the iframe: `"I want to detect when user clicks a link in iframe"`.
Daniel Vassallo
@stormdrain: Indeed. If that's not needed, just set `prevSrc` to the original source.@Daniel: I guess you're right, which leads to your solution of using `contentWindow.location` instead of `src`.
casablanca
@casablanca: technically this script won't work the way you intended anyway. The attr will always return the same thing (the iframe src) unless the iframe has a script that updates the iframe src attribute.
stormdrain
Yes, I did mention in my previous comment that Daniel's solution is correct.
casablanca