我正在写一个基于iframe的facebook应用程序。现在我想使用相同的html页面来渲染正常的网站以及facebook内的画布页面。我想知道我是否可以确定页面是否已经在iframe内加载或直接在浏览器中加载?
当前回答
我用这个:
var isIframe = (self.frameElement && (self.frameElement+"").indexOf("HTMLIFrameElement") > -1);
其他回答
这对我来说是最简单的解决方案。
<p id="demofsdfsdfs"></p>
<script>
if(window.self !== window.top) {
//run this code if in an iframe
document.getElementById("demofsdfsdfs").innerHTML = "in frame";
}else{
//run code if not in an iframe
document.getElementById("demofsdfsdfs").innerHTML = "no frame";
}
</script>
这是一段古老的代码,我用过几次:
if (parent.location.href == self.location.href) {
window.location.href = 'https://www.facebook.com/pagename?v=app_1357902468';
}
由于您是在facebook应用程序的上下文中请求,您可能想要考虑在初始请求发出时在服务器上检测这一点。如果从iframe调用,Facebook将传递一堆查询字符串数据,包括fb_sig_user键。
因为你可能需要在你的应用程序中检查和使用这些数据,所以使用它来确定要渲染的适当上下文。
下面是@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!')
}
}
当在与父元素相同的iframe中,window. frameelement方法返回嵌入窗口的元素(例如iframe或object)。否则,如果在顶级上下文中浏览,或者如果父帧和子帧有不同的起源,它将求值为null。
window.frameElement
? 'embedded in iframe or object'
: 'not embedded or cross-origin'
这是一个在所有现代浏览器中都具有基本支持的HTML标准。