简体   繁体   中英

How to check user already logged in facebook?

I am using facebook javascript SDK to integrate login with facebook in my app. I have 2 JS files in my app.

  1. FacebookLogin.js
  2. content.js

Now i am loading FacebookLogin.js in content.js. Further I have below code in my FacebookLogin.js

var userID;
window.fbAsyncInit = function() {
    //SDK loaded, initialize it
    FB.init({
        appId      : 'MY_APP_ID',
        xfbml      : true,
        version    : 'v2.2'
    });

    //check user session and refresh it
    FB.getLoginStatus(function(response) {
        if (response.status === 'connected') {
            //user is authorized
            userID = response.authResponse.userID;
        } else {
            document.getElementById('status').innerHTML = 'Please log into Facebook.';
        }
    });
};

Now I want to use that userID variable in my content.js file. So that i can check if user is already logged in, like below

if(userID === undefined && userID === null)
    {
        showSocialLoginPopup(); 
        return false;
    }

here showSocialLoginPopup() displays a popup with different login options like facebook, Twitter, etc. Now if the user is already logged in then i dont want to display that popup.

This is mostly a question about scope.

All of your .js files will be loaded into the same DOM, and therefore can access variables and functions and such across files.

One option is to make userID a global variable :

1) make sure that your content.js is loaded AFTER your FacebookLogin.js
2) declare your variable userID outside of any functions or objects

this will allow you to access userID anywhere in your javascript

Here is a small tutorial on variable scope in javascript:
http://www.w3schools.com/js/js_scope.asp

Edit: Another potential problem could be timing.

The FB.getLoginStatus() is an asynchronous call, and will take some time complete, the userID does not get set until after that call is finished.

If your function from content.js is not behind some kind of event or timeout then it may well be executing before the FB call finishes which means userID would be undefined still.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM