我正在写一个基于iframe的facebook应用程序。现在我想使用相同的html页面来渲染正常的网站以及facebook内的画布页面。我想知道我是否可以确定页面是否已经在iframe内加载或直接在浏览器中加载?
当前回答
这对我来说是最简单的解决方案。
<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>
其他回答
我以前经常检查窗户。父键对我有用,但最近window是一个循环对象,总是有父键,不管有没有iframe。
正如评论所言,很难与窗口相比。父母工作。不确定这是否会工作,如果iframe是完全相同的网页作为父母。
window === window.parent;
使用这个javascript函数作为如何实现这一点的例子。
function isNoIframeOrIframeInMyHost() {
// Validation: it must be loaded as the top page, or if it is loaded in an iframe
// then it must be embedded in my own domain.
// Info: IF top.location.href is not accessible THEN it is embedded in an iframe
// and the domains are different.
var myresult = true;
try {
var tophref = top.location.href;
var tophostname = top.location.hostname.toString();
var myhref = location.href;
if (tophref === myhref) {
myresult = true;
} else if (tophostname !== "www.yourdomain.com") {
myresult = false;
}
} catch (error) {
// error is a permission error that top.location.href is not accessible
// (which means parent domain <> iframe domain)!
myresult = false;
}
return myresult;
}
由于您是在facebook应用程序的上下文中请求,您可能想要考虑在初始请求发出时在服务器上检测这一点。如果从iframe调用,Facebook将传递一堆查询字符串数据,包括fb_sig_user键。
因为你可能需要在你的应用程序中检查和使用这些数据,所以使用它来确定要渲染的适当上下文。
我不确定这个例子如何适用于旧的Web浏览器,但我使用这个IE, Firefox和Chrome没有问题:
var iFrameDetection = (window === window.parent) ? false : true;
我用这个:
var isIframe = (self.frameElement && (self.frameElement+"").indexOf("HTMLIFrameElement") > -1);