2

This script runs every 2 seconds and detect if the url of the iframe is changed. But I can't get it to work. I want to alert if the url of the iframe is changed. For example if someone clicks a link and go another page on the iframed content.

var prevSrc = "http://www.bodrumlife.com";
function check() {
var curSrc = $('#iframe').attr('src');
  if (curSrc != prevSrc) {
   alert("hobaa");
   prevSrc = curSrc;
   }
}

window.setInterval(check, 2000); // 2 seconds


<iframe id="iframe" name="iframe" src="http://www.bodrumlife.com"></iframe>
user198989
  • 4,574
  • 19
  • 66
  • 95

1 Answers1

4

If you prefer to use JQuery below is the following syntax, instead of using half-jquery and standard javascript.

$(function(){
    $('#iframeId').load(function() {
        alert("the iframe has changed.");
    });
});

Although I'm not sure if the onload function works in Sarafi. It's supported by Firfox, IE and Chrome.

EDIT:

extended example

    <script type="text/javascript">
        $(function () {
            var intialFrameSrc = "http://www.twiij.com";
            $("#iframeContentPanel").load(function () {
                if (intialFrameSrc != $("#iframeContentPanel").attr('src')) {
                    alert("the iframe has changed.");
                }
            });

            $("#btnChangeUrl").click(function () {
                $("#iframeContentPanel").attr("src", "http://m.smh.com.au/");
            });
        });

    </script>
        <iframe id="iframeContentPanel" name="iframeContentPanel" src="http://www.twiij.com" width="500"  frameborder="0" height="500" scrolling="no"></iframe>
<input type="button" id="btnChangeUrl" value="Change Url"/>
Nickz
  • 1,880
  • 17
  • 35
  • 1
    Thanks, it works. But it fires when iframe's first load also. How to prevent it from firing at first load ? – user198989 Feb 21 '12 at 05:31
  • 2
    Create a bool var on first load set false, if loadedCheck is false, then set to true and wrap your alert if loadedCheck. Or if you have default URL then check if url is default then do nothing. – Nickz Feb 21 '12 at 05:39
  • Thanks. Also, is it possible to make an event when iframe is loading (not when loaded) ? – user198989 Feb 22 '12 at 15:23
  • There's one problem with this script. If you navigate to an invalid URL in Firefox or Safari the load event won't be triggered. – mgamer Jul 11 '13 at 20:28