admin管理员组

文章数量:1332345

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 = "";
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=""></iframe>

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.";
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."></iframe>
Share Improve this question asked Feb 21, 2012 at 4:55 user198989user198989 4,66320 gold badges68 silver badges95 bronze badges 1
  • 4 stackoverflow./questions/2429045/… – Alex Commented Feb 21, 2012 at 4:58
Add a ment  | 

1 Answer 1

Reset to default 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.";
            $("#iframeContentPanel").load(function () {
                if (intialFrameSrc != $("#iframeContentPanel").attr('src')) {
                    alert("the iframe has changed.");
                }
            });

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

    </script>
        <iframe id="iframeContentPanel" name="iframeContentPanel" src="http://www.twiij." width="500"  frameborder="0" height="500" scrolling="no"></iframe>
<input type="button" id="btnChangeUrl" value="Change Url"/>

本文标签: javascriptAlert when iframe url changedStack Overflow