我正在写一个基于iframe的facebook应用程序。现在我想使用相同的html页面来渲染正常的网站以及facebook内的画布页面。我想知道我是否可以确定页面是否已经在iframe内加载或直接在浏览器中加载?
当前回答
在每一页写这个javascript
if (self == top)
{ window.location = "Home.aspx"; }
然后它会自动重定向到主页。
其他回答
当在与父元素相同的iframe中,window. frameelement方法返回嵌入窗口的元素(例如iframe或object)。否则,如果在顶级上下文中浏览,或者如果父帧和子帧有不同的起源,它将求值为null。
window.frameElement
? 'embedded in iframe or object'
: 'not embedded or cross-origin'
这是一个在所有现代浏览器中都具有基本支持的HTML标准。
我不确定这个例子如何适用于旧的Web浏览器,但我使用这个IE, Firefox和Chrome没有问题:
var iFrameDetection = (window === window.parent) ? false : true;
目前最好的遗留浏览器断帧脚本
其他的解决方法对我都不起作用。这条适用于所有浏览器:
防止点击劫持的一种方法是在每个不应该被框起来的页面中包含一个“打破框架”脚本。下面的方法将防止网页被框架,即使在传统浏览器,不支持X-Frame-Options-Header。
在文档HEAD元素中,添加以下内容:
<style id="antiClickjack">body{display:none !important;}</style>
首先对style元素本身应用一个ID:
<script type="text/javascript">
if (self === top) {
var antiClickjack = document.getElementById("antiClickjack");
antiClickjack.parentNode.removeChild(antiClickjack);
} else {
top.location = self.location;
}
</script>
这样,所有内容都可以在文档HEAD中,并且在API中只需要一个方法/taglib。
参考:https://www.codemagi.com/blog/post/194
由于您是在facebook应用程序的上下文中请求,您可能想要考虑在初始请求发出时在服务器上检测这一点。如果从iframe调用,Facebook将传递一堆查询字符串数据,包括fb_sig_user键。
因为你可能需要在你的应用程序中检查和使用这些数据,所以使用它来确定要渲染的适当上下文。
function amiLoadedInIFrame() {
try {
// Introduce a new propery in window.top
window.top.dummyAttribute = true;
// If window.dummyAttribute is there.. then window and window.top are same intances
return !window.dummyAttribute;
} catch(e) {
// Exception will be raised when the top is in different domain
return true;
}
}