Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind Facebook onlogin event to customized button?

I know how to use custom button as Facebook login.

Now I'd like to bind onlogin event to customized button, but I don't know how to do.

Original code

<fb:login-button scope="public_profile,email" onlogin="afterLogin();">
</fb:login-button>

<script>
    /* Assume that Facebook SDK loaded asyncronously and initilized */

    function afterLogin() {
        // Do stuff
    }
</script>

My code

<button id="cusomized-button" onclick="fbLogin();" onlogin="afterLogin();">
    Customized button
</button>

<script>
    /* Assume that Facebook SDK loaded asynchronously and initialized */

    // Show facebook login modal
    function fbLogin() {
        FB.login(function() {}, {
            scope: 'email,public_profile'
        });
    };

    function afterLogin() {
        // Do stuff
    }
</script>
like image 967
Chemical Programmer Avatar asked Jan 30 '26 12:01

Chemical Programmer


1 Answers

Assuming you use version 2.4 of the Graph API, you are able to subscribe to an event called auth.login which is fired whenever the login status changes.

So, if you want to react to when the user logs in, you can do this and your function named afterLogin would be called once the user logs in to your app:

FB.Event.subscribe('auth.login', afterLogin);

Do note that Facebook recommends everyone to listen to auth.statusChange instead, otherwise your application will not know if the user has logged out or deauthorized the application, which would invalidate the token.

Here's an example using auth.statusChange, the response argument passed to the function contains a response object which is detailed here:

FB.Event.subscribe('auth.statusChange', function(response) {
    if(response.status === 'connected') {
    // `connected` means that the user is logged in and that your app is authorized to do requests on the behalf of the user
    afterLogin();
    } else if(response.status === 'not_authorized') {
    // The user is logged in on Facebook, but has not authorized your app
    } else {
    // The user is not logged in on Facebook
    }

});

As an alternative, the first argument to FB.login is a function which is called after the user returns from Facebook, so you could do something like this:

FB.login(function(response) {
    if (response.authResponse) {
        afterLogin();
    } else {
        // The user cancelled the login or did not authorize your app
    }
}, {
    scope: 'email,public_profile'
});
like image 109
ToJa92 Avatar answered Feb 01 '26 21:02

ToJa92



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!