Get user login status on Facebook by real time

2020-07-28 11:42发布

问题:

This question is related to another question of mine: How to know if a user log out of Facebook, FB.Event.Subscribe not work

In that question, I tried to get a call back event when the users log out of Facebook. But since it has no appropriate answer yet, I must try another way. I try polling to get the login status of a user by javascript, like this:

        function checkLogin()
        {
            alert("in");
            FB.getLoginStatus(function(response) {
              if (response.status == "connected") {
                // logged in and connected user, someone you know
                alert("ok - 5 seconds has passed");
              } else {
                // no user session available, someone you dont know
                alert("not ok");
              }
            });
            t=checkLogin("timedCount()",5000);
        }

The problem with this is that: the function only returns the correct result the first time it gets called. After that, it seems the result is cached, and I continously received "connected" in response, although the user silently logged out by another tab in browser.

This is not good, because at that time Facebook pop out a dialog which ask the user to login. But if the user cancel it, he still can work with my application (caused his session with my application server is not expired yet!).

In the document, FB dev says that:

When you invoke FB.getLoginStatus, an HTTP request may be made to www.facebook.com to check the current status of the user. However, if FB.getLoginStatus has already been called during this browser session, and a session has been persisted within a cookie, an HTTP request to facebook.com may not be needed

So I think this effect caused by the cached. I wonder why Facebook do it that way.

Does anyone know a work around for this issue?

Thanks for any help,

Hoang Long

回答1:

It took me a long time enough, eventually, until one of my co-workers solved the problem.

The solution is that we need to call FB.init() again, with cookie:false before calling getLoginStatus. This will remove the cookie and get new information.

FB.init({ 
        appId:'${appId}', 
            cookie: false, 
        status: true, 
        xfbml: true 
    });

FB.getLoginStatus(function (response) {
        if (response.session) {
                alert("here");
        }
});