auth.statusChange doesn't fire during FB.init if the user isn't logged in to facebook

放肆的年华 提交于 2019-12-03 01:56:21

My best solution for this was to set status to 'false' in the fb.init options, then to explicitly call getloginstatus separately.

IF get loginstatus came back as unknown (i.e. logged out), I subscribed to the status change event, as well as doing the usual of displaying the login button. Then when the user logs in, status change fires as expected.

A better solution that theoretically should save you a roundtrips is as follows (coffeescript, but easily translatable to javascript):

FB.init
  appId: appId
  channelUrl: channelUrl
  status: true     # Check Facebook Login status on init
  cookies: true
  xfbml: false

FB.getLoginStatus (response) =>
  @parseResponse(response)
  FB.Event.subscribe 'auth.statusChange', @parseResponse
  FB.Event.subscribe 'auth.authResponseChange', @parseResponse

We're still using a manual getLoginStatus to fire when the user is unknown, but this time we still use 'status: true' so that the login status is already cached when getLoginStatus is called. By subscribing to the relevant events only after getLoginStatus has fired, we make sure the handling method parseResponse is only called once on load.

You can check the response you get back after you pass a true parameter in the getLoginStatus:

window.fbAsyncInit = function() {
    FB.init({
        appId  : '',
        status : true,
        cookie : true,
        xfbml  : true,
    });

    FB.getLoginStatus( function(response) {
        //console.log(response);
        if (response.status === 'connected') {
            var accessToken = response.authResponse.accessToken;
            alert(accessToken);
        } else if (response.status === 'not_authorized') {
            //login function
        } else {
            //login function
        }
    }, true);

    FB.Event.subscribe('auth.authResponseChange', function(response) {
        //console.log('The status of the session changed to: '+response.status);
        window.location.reload();
    });
};

If you set the status to true, the FB.getLoginStatus response object will be cached by the SDK and subsequent calls to FB.getLoginStatus will return data from this cached response.

To get around this, you have to call FB.getLoginStatus with the second parameter set to true to force a roundtrip to Facebook - effectively refreshing the cache of the response object.

FB Docs: https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!