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')});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With