我正在写一个基于iframe的facebook应用程序。现在我想使用相同的html页面来渲染正常的网站以及facebook内的画布页面。我想知道我是否可以确定页面是否已经在iframe内加载或直接在浏览器中加载?
当前回答
if ( window !== window.parent )
{
// The page is in an iframe
}
else
{
// The page is not in an iframe
}
其他回答
这是一段古老的代码,我用过几次:
if (parent.location.href == self.location.href) {
window.location.href = 'https://www.facebook.com/pagename?v=app_1357902468';
}
if ( window !== window.parent )
{
// The page is in an iframe
}
else
{
// The page is not in an iframe
}
目前最好的遗留浏览器断帧脚本
其他的解决方法对我都不起作用。这条适用于所有浏览器:
防止点击劫持的一种方法是在每个不应该被框起来的页面中包含一个“打破框架”脚本。下面的方法将防止网页被框架,即使在传统浏览器,不支持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
这对我来说是最简单的解决方案。
<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>
如果你想知道用户是否通过facebook page tab或canvas访问你的应用,请检查Signed Request。如果你没有得到它,可能用户没有从facebook访问。 确保确认signed_request字段结构和字段内容。
使用php-sdk,你可以像这样获得Signed Request:
$signed_request = $facebook->getSignedRequest();
你可以在这里阅读更多关于签名请求的内容:
https://developers.facebook.com/docs/reference/php/facebook-getSignedRequest/
在这里:
https://developers.facebook.com/docs/reference/login/signed-request/