我正在写一个基于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';
}

我不确定这个例子如何适用于旧的Web浏览器,但我使用这个IE, Firefox和Chrome没有问题:

var iFrameDetection = (window === window.parent) ? false : true;

下面是@magnoz的回答的代码实现。

constructor() {
    let windowLen = window.frames.length;
    let parentLen = parent.frames.length;

    if (windowLen == 0 && parentLen >= 1) {
        this.isInIframe = true
        console.log('Is in Iframe!')
    } else {
        console.log('Is in main window!')
    }
}

在每一页写这个javascript

if (self == top)
  { window.location = "Home.aspx"; }

然后它会自动重定向到主页。

如果你想知道用户是否通过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/