我正在写一个基于iframe的facebook应用程序。现在我想使用相同的html页面来渲染正常的网站以及facebook内的画布页面。我想知道我是否可以确定页面是否已经在iframe内加载或直接在浏览器中加载?
当前回答
浏览器会阻塞对窗口的访问。顶部由于同源政策。IE漏洞也会发生。下面是工作代码:
function inIframe () {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
Top和self都是窗口对象(还有父窗口),所以你会看到你的窗口是否是顶部窗口。
其他回答
如果你想知道用户是否通过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/
这是一段古老的代码,我用过几次:
if (parent.location.href == self.location.href) {
window.location.href = 'https://www.facebook.com/pagename?v=app_1357902468';
}
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;
}
}
当在与父元素相同的iframe中,window. frameelement方法返回嵌入窗口的元素(例如iframe或object)。否则,如果在顶级上下文中浏览,或者如果父帧和子帧有不同的起源,它将求值为null。
window.frameElement
? 'embedded in iframe or object'
: 'not embedded or cross-origin'
这是一个在所有现代浏览器中都具有基本支持的HTML标准。
在Firefox 6.0扩展(Addon-SDK 1.0)的内容脚本中,接受的答案对我来说不起作用:Firefox在每个:顶级窗口和所有iframe中执行内容脚本。
在内容脚本中,我得到以下结果:
(window !== window.top) : false
(window.self !== window.top) : true
这个输出的奇怪之处在于,无论代码是在iframe中运行还是在顶级窗口中运行,它总是相同的。
另一方面,谷歌Chrome似乎只在顶级窗口内执行我的内容脚本一次,所以上面不会工作。
在两种浏览器的内容脚本中,最终为我工作的是:
console.log(window.frames.length + ':' + parent.frames.length);
如果没有iframe,则打印0:0,在包含一个框架的顶级窗口中打印1:1,在文档的唯一iframe中打印0:1。
这允许我的扩展在两个浏览器中确定是否存在任何iframes,此外,在Firefox中,如果它是在iframes之一中运行。