Alert when iframe url changed

懵懂的女人 提交于 2019-12-12 21:00:03

问题


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>

回答1:


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"/>


来源:https://stackoverflow.com/questions/9372391/alert-when-iframe-url-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!