如何将Facebook onlogin事件绑定到自定义按钮? [英] How to bind Facebook onlogin event to customized button?
问题描述
我知道如何在Facebook登录中使用自定义按钮.
I know how to use custom button as Facebook login.
现在我想将onlogin
事件绑定到自定义按钮,但是我不知道该怎么做.
Now I'd like to bind onlogin
event to customized button, but I don't know how to do.
原始代码
<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>
我的代码
<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>
推荐答案
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'
});
这篇关于如何将Facebook onlogin事件绑定到自定义按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!