我正在写一个基于iframe的facebook应用程序。现在我想使用相同的html页面来渲染正常的网站以及facebook内的画布页面。我想知道我是否可以确定页面是否已经在iframe内加载或直接在浏览器中加载?


当前回答

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;
    }
}

其他回答

浏览器会阻塞对窗口的访问。顶部由于同源政策。IE漏洞也会发生。下面是工作代码:

function inIframe () {
    try {
        return window.self !== window.top;
    } catch (e) {
        return true;
    }
}

Top和self都是窗口对象(还有父窗口),所以你会看到你的窗口是否是顶部窗口。

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/

这对我来说是最简单的解决方案。

    <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>
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;
    }
}