FB.logout() called without an access token

To logout from the application which uses facebook graph API, use this JavaScript on the logout page just after the <form> tag:

window.onload=function()
{
    // initialize the library with your Facebook API key
    FB.init({ apiKey: 'b65c1efa72f570xxxxxxxxxxxxxxxxx' });

    //Fetch the status so that we can log out.
    //You must have the login status before you can logout,
    //and if you authenticated via oAuth (server side), this is necessary.
    //If you logged in via the JavaScript SDK, you can simply call FB.logout()
    //once the login status is fetched, call handleSessionResponse
    FB.getLoginStatus(handleSessionResponse);
}

//handle a session response from any of the auth related calls
function handleSessionResponse(response) {
    //if we dont have a session (which means the user has been logged out, redirect the user)
    if (!response.session) {
        window.location = "/mysite/Login.aspx";
        return;
    }

    //if we do have a non-null response.session, call FB.logout(),
    //the JS method will log the user out of Facebook and remove any authorization cookies
    FB.logout(handleSessionResponse);
}

The code works and is live on my site.


I went for the less trivial solution:

    function facebookLogout(){
        FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                FB.logout(function(response) {
                    // this part just clears the $_SESSION var
                    // replace with your own code
                    $.post("/logout").done(function() {
                        $('#status').html('<p>Logged out.</p>');
                    });
                });
            }
        });
    }

Figured it out after so many tries.

Generally response.authResponse.accessToken contains token. So, its error about the accessToken not being there.

Think logically, where does that response come from in your code? Out of nowhere.

So, we need to get that response object from a function and get this working. I don't know how it worked for others, but this worked for me.

Just replace the code with this

function logout(){
  FB.getLoginStatus(function(response) {
    FB.logout(function(response){
      console.log("Logged Out!");
      window.location = "/";
    });
  });
}

What we do here is, get the login status if the user is logged in and get the corresponding response in return, which contains all the necessary tokens and data. Once this is fetched, the token is used to log out the user.


I've tried something like this:

function fbLogout(){
    if(typeof FB.logout == 'function'){
        if (FB.getAuthResponse()) {
         FB.logout(function(response) { window.location.href = PROJECT_PATH + '/index/logout'; }); 
         return;
        }  
    };

    window.location.href = PROJECT_PATH + '/index/logout'; 
    return;  
}