What could be causing this Facebook javascript-sdk login code to repeatedly log in the user automatically?

After pressing the logout button on my site, I am still unable to keep a user logged out. Although they are redirected to the login page, the updateButton function is called again with the same credentials causing them to be logged back in. Despite trying various approaches, the issue persists. It seems that there may be errors in the way I have implemented the updateButton function below, and the FB.logout() method is not working correctly either as indicated by the error message "FB.logout called without an access token" in the console.

$(function(){

    var button;

    window.fbAsyncInit = function(){

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

        function updateButton(response) { // Uncertain about correctness of this function
            console.log("Update Button Fired.");
            console.log(response);

            button  = document.getElementById('fb-auth');

            if(response.status === 'connected') {
                FB.api('/me', function(info) {
                    login(response, info);
                });
            } else {
                FB.login(function(response) {
                    if(response.status === 'not_authorized') {
                        FB.api('/me', function(info) {
                            login(response, info); 
                        });
                    } else {

                    }
                }, {scope: 'email, user_birthday, user_about_me'});
            }
        }  

        FB.getLoginStatus(updateButton);
        FB.Event.subscribe('auth.statusChange', updateButton);

    };

    (function() {
        var e = document.createElement('script');
        e.async = true;
        e.type = 'text/javascript';
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        document.getElementById('fb-root').appendChild(e);
    })();

    function login(response, info){
        console.log('login Showloader called');
        if (response.authResponse) { 
            var accessToken = response.authResponse.accessToken;
            $.post("/web/register/faceBookRegistration", {data: info, accessTokenValue: accessToken}).done(function(data) {
                if(typeof(data) !== undefined) {
                    window.location = "/web/login/loadViewFaceLogin";
                }
            });
        }
    }

    function logout(response){
        FB.logout(function(response){
            console.log("User is now logged out"); 
        });
    }

});

My logout function may also not be functioning correctly:

function logout(response){ 
    FB.logout(function(response){
        console.log("User is now logged out"); 
    });
}

The error "FB.logout called without an access token" appearing in the console may indicate issues with this function. What could be causing this?

Answer №1

I made some modifications to your code while still preserving its core elements:

   // File - fb-init.js

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

    (function(d){
        var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
        if (d.getElementById(id)) {return;}
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        ref.parentNode.insertBefore(js, ref);
    }(document));

-

    // File - main.js

    $('#fb-login').on('click', function() {
        FB.getLoginStatus(function(responseStatus) {
            if (responseStatus.status === 'connected') {
                FB.api('/me', function(responseMe) {
                    if (!responseMe.id) 
                        return false;
                    var accessToken = responseMe.authResponse.accessToken;
                    $.post('/web/register/faceBookRegistration' {
                        data                : responseMe,
                        accessTokenValue    : accessToken
                    }).done(function(data) {
                        if (typeof(data) !== 'undefined')
                            window.location = '/web/login/loadViewFaceLogin';    
                    });   
                });
            }
            else if (responseStatus.status === 'not_authorized') {
                FB.login(function(responseLogin) {
                    FB.api('/me', function(responseMe) {
                    if (!responseMe.id) 
                            return false;
                        var accessToken = responseMe.authResponse.accessToken;
                        $.post('/web/register/faceBookRegistration' {
                            data                : responseMe,
                            accessTokenValue    : accessToken
                        }).done(function(data) {
                            if (typeof(data) !== 'undefined')
                                window.location = '/web/login/loadViewFaceLogin';    
                        });   
                    });
                }, {scope:'email, user_birthday,user_about_me' });    
            }
            else
                return false;
        });    
    });

    $('#fb-logout').on('click', function() {
        FB.logout(function(responseLogout) {

        });    
    });

Answer №2

When the status is set to true, it triggers automatic login for users who are already logged into Facebook when visiting the website.

Answer №3

It's generally not recommended to utilize the FB.logout() function unless you specifically need to log the user out of Facebook, rather than just your website.

The issue with the popup may stem from the FB.getLoginStatus(updateButton) method, which triggers the updateButton() function every time a page loads.

To enhance this, consider utilizing an onclick function instead.

Answer №4

After coming across this article about the issue with FB.logout() being called without an access token, I realized that my logout process was not functioning correctly. Fixing this would bring me a sense of relief.

Below is the code snippet for the logout function that solved my problem:

function logout(response){

if(!response.authResponse){
window.location = "/web/login/";
return;
}

FB.logout(function(response){
FB.Auth.setAuthResponse(null,'unknown');  
logout(response);
});
}

The article mentioned the importance of continuously sending logout requests until it is fully processed by Facebook. I implemented a recursive call to achieve this, and the solution worked when the confirmation came through.

Being new to this, I would appreciate any suggestions on how to improve the current hack.

A special thanks to 'ZeNy' as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing jQuery to toggle between adding and removing CSS classes for element identification

Below is a JavaScript/jQuery function that I have: function hideShowHiddens(action){ $('.hidden_col').each(function(){ if(action == 'show'){ this.removeClass("hidden"); }else{ ...

Obtain data from an ajax request to be included in the form submission

Seeking assistance with my code to retrieve the selected value from ajax_details.php for submission in the form action process_details.php. Here is the code snippet: injury_details.php <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jqu ...

Issue with React.js: The formData is empty when trying to add a value from a file using material-ui-dropzone

I am currently working on integrating an upload feature using a library named material-ui-dropzone Although I believe the file upload process is functioning correctly, I encounter an issue with axios where the formData appears empty even prior to sending ...

Incorporate an external library

I am currently facing a challenge in my angular2 project where I need to import a 3rd party library. Here are the steps I have taken so far: ng new myproject npm install --save createjs-easeljs npm install @types/easeljs However, I am stuck at this poin ...

Encountering a Next.js prerendering issue when using getStaticPaths

I am currently developing a Next.js application. Here is the structure of my files: cpanearme -components -listitem.js -pages -home -index.js -firm -[id].js Below is the code for a list item that redirects to the dynamic rout ...

The useEffect function is not being executed

Seeking assistance from anyone willing to help. Thank you in advance. While working on a project, I encountered an issue. My useEffect function is not being called as expected. Despite trying different dependencies, I have been unable to resolve the issue ...

What is preventing me from receiving the value from the Ajax call?

I have developed an Ajax function that looks like this: function searchPlanAjax(url){ jQuery('#loader').css('display','block'); var plan = jQuery('.rad').val(); var site = url+"fbilling_det ...

Is there a way to execute a JavaScript function by clicking on an anchor tag?

Many websites, such as StackOverflow, have attempted to address this particular issue. However, the explanations provided are complex and difficult for me to grasp. I am looking for someone who can help identify my mistakes and explain the solution in simp ...

Revisiting Async Await: A guide to implementing callbacks

I have the following code snippet: const myImage = document.querySelector('img'); const myRequest = new Request('flowers.jpg'); fetch(myRequest).then((response) => { console.log(response.type); // returns basic by default respo ...

I keep trying to retrieve a specific property from an object, but every time I do, it returns as undefined

I'm currently employing Javascript within a React component. My goal is to retrieve a specific property from an object. If I log this object out to the console as shown below: console.log("Engine: ", this.Engine); The output looks like th ...

Tips for utilizing [(ngModel)] with an object that is empty, null, or undefined in Angular 4

When trying to assign [(ngModel)] inside my .html code to an empty (null or undefined) object, I encountered the error message _co.object is null. There are two scenarios: one where the object has a value and one where it does not. The ngModel works fine i ...

The V-model seems to be failing to bind to the DOM element

I'm encountering an issue with the code I've written. The v-model is not binding the data in the DOM, even though the axios I'm using is returning values. Here is the code snippet: <template> <v-container fluid> <v-layo ...

Does the presence of XHR calls with application/json as the 'type' indicate that the application is using AJAX technology?

Forgive my lack of knowledge on this topic as I am still in the process of learning. I am exploring the possibility of implementing a solution on my website where I can embed a JavaScript code that will make API calls to display images. I am curious to kno ...

Oops! The type '{}' is lacking the properties listed below

interface Human { firstName: string; lastName: string; } let human1: Human = {}; human1.firstName = "John" human1.lastName = "Doe" Upon declaring human1, an error pops up: Type '{}' is missing the following properties from type Human ...

Arranged list becomes depleted (Although Lodash's groupBy function still functions properly)

Check out the sample plunker here Initially, I am grouping a collection by a specific key, which in this case is yob (year of birth). I have two approaches: I can create a custom function to group the collection, allowing for custom logic to be impleme ...

How do I determine which radio button is currently selected within my Angular2 application?

In my HTML, I have the following radio buttons: <div class="col-lg-4" id="radioButtons"> <form action=""> <fieldset id="capacity"> <legend>capacity</legend> <label for="input-ao">< ...

The Facebook SDK's function appears to be triggering twice

I am currently in the process of integrating a Facebook login button into my website and have made progress, but I have encountered a problem. The Facebook SDK JavaScript code that I am using is as follows: function statusChangeCallback(response) { ...

Using Javascript/HTML to enable file uploads in Rails

I'm currently facing an issue with uploading and parsing a file in Rails, as well as displaying the file content in a sortable table. I followed a tutorial on to get started. This is what my index.html.erb View file looks like: <%= form_tag impo ...

incorporating a previous and forward button to navigate through the enlarged picture

I am currently in the process of developing an image thumbnail slider where clicking on a thumbnail will open a pop-up box with a larger image. It is essential for me to incorporate next and previous buttons for navigating through the larger images. The f ...

Error in D3: stream_layers function is not defined

Utilizing nvd3.js to construct a basic stacked bar chart as detailed here I inserted the code provided in the link into an Angular directive like this: app.directive('stackBar', function() { return { restrict: 'A', ...