我正在写一个基于iframe的facebook应用程序。现在我想使用相同的html页面来渲染正常的网站以及facebook内的画布页面。我想知道我是否可以确定页面是否已经在iframe内加载或直接在浏览器中加载?
当前回答
在每一页写这个javascript
if (self == top)
{ window.location = "Home.aspx"; }
然后它会自动重定向到主页。
其他回答
浏览器会阻塞对窗口的访问。顶部由于同源政策。IE漏洞也会发生。下面是工作代码:
function inIframe () {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
Top和self都是窗口对象(还有父窗口),所以你会看到你的窗口是否是顶部窗口。
在每一页写这个javascript
if (self == top)
{ window.location = "Home.aspx"; }
然后它会自动重定向到主页。
if (window.frames.length != parent.frames.length) { page loaded in iframe }
但只有当iframe的数量在你的页面和页面谁加载你在iframe不同。使没有iframe在你的页面有100%的保证这段代码的结果
如果你想知道用户是否通过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/
使用这个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;
}