javascript iframe url 更改时发出警报
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9372391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Alert when iframe url changed
提问by user198989
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.
此脚本每 2 秒运行一次,并检测 iframe 的 url 是否更改。但我无法让它工作。我想提醒 iframe 的 url 是否更改。例如,如果有人单击链接并转到 iframe 内容上的另一个页面。
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>
回答by Nickz
If you prefer to use JQuery below is the following syntax, instead of using half-jquery and standard javascript.
如果您更喜欢使用下面的 JQuery,请使用以下语法,而不是使用 half-jquery 和标准 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.
虽然我不确定 onload 功能是否适用于 Sarafi。Firfox、IE 和 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"/>