检查Google Chrome中页面是否在Iframe中

7

我已经尝试了许多window属性,来确定一个iframe页面是否能够知道它自己被嵌入到了一个iframe中。我尝试过以下属性:

if(top.location!= self.location) //doesn't work in Google Chrome
   alert("I am in an iframe!")

以下内容在所有浏览器上都可以运行,但在Chrome上不起作用。我正在为Firefox和Chrome编写用户脚本,但是Chrome真的不太好处理。有没有办法判断Chrome是否能检测到它所在的页面在iframe中?


http://jsfiddle.net/hpVec/ 在Chrome中似乎运行良好。 - Peter Olson
1
var in_iframe = (window.location != window.parent.location); 在框架中 = (窗口位置 != 父窗口位置); - Silver Moon
2个回答

15

我认为这适用于框架,我假设它也适用于 iFrame。

if (top === self) { 
  // no frame
} else { 
  //frame 
}

0

window.frameElement 在即使是最古老的浏览器中也得到支持。它可以识别当前窗口嵌入的 iframe、embed 或 object。

if(!!window.frameElement){
  //code to be executed if we are in an iframe
} 

更多内容请点击此处。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接