且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将Facebook onlogin事件绑定到自定义按钮?

更新时间:2023-10-07 07:54:46

假设您使用的是Graph API 2.4版,则可以订阅名为

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.

因此,如果您想对用户登录时做出反应,可以执行此操作,一旦用户登录到您的应用程序,就会调用名为afterLogin的函数:

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);

请注意,Facebook建议每个人都改为收听auth.statusChange,否则您的应用程序将不知道用户是否已注销或取消了对应用程序的授权,这会使令牌无效.

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.

这里是使用auth.statusChange的示例,传递给函数的response参数包含响应对象

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
    }

});

作为替代方案,FB.login的第一个参数是一个函数,该函数在用户从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'
});