我正在写一个基于iframe的facebook应用程序。现在我想使用相同的html页面来渲染正常的网站以及facebook内的画布页面。我想知道我是否可以确定页面是否已经在iframe内加载或直接在浏览器中加载?


当前回答

我不确定这个例子如何适用于旧的Web浏览器,但我使用这个IE, Firefox和Chrome没有问题:

var iFrameDetection = (window === window.parent) ? false : true;

其他回答

这是一段古老的代码,我用过几次:

if (parent.location.href == self.location.href) {
    window.location.href = 'https://www.facebook.com/pagename?v=app_1357902468';
}

当在与父元素相同的iframe中,window. frameelement方法返回嵌入窗口的元素(例如iframe或object)。否则,如果在顶级上下文中浏览,或者如果父帧和子帧有不同的起源,它将求值为null。

window.frameElement
  ? 'embedded in iframe or object'
  : 'not embedded or cross-origin'

这是一个在所有现代浏览器中都具有基本支持的HTML标准。

我以前经常检查窗户。父键对我有用,但最近window是一个循环对象,总是有父键,不管有没有iframe。

正如评论所言,很难与窗口相比。父母工作。不确定这是否会工作,如果iframe是完全相同的网页作为父母。

window === window.parent;

下面是@magnoz的回答的代码实现。

constructor() {
    let windowLen = window.frames.length;
    let parentLen = parent.frames.length;

    if (windowLen == 0 && parentLen >= 1) {
        this.isInIframe = true
        console.log('Is in Iframe!')
    } else {
        console.log('Is in main window!')
    }
}
if ( window !== window.parent ) 
{
      // The page is in an iframe   
} 
else 
{     
      // The page is not in an iframe   
}