我认为前进的最佳方式是简单地使用一个变量来查看一旦 facebook 初始化就获取用户的登录状态,并使用它来设置一个布尔变量来确定是立即登录还是共享。
那么让我们一步一步来看看这个:
登录变量
首先,我们要声明 bool,以便我们可以访问它并将其默认设置为 false。你可能想把它放在头脑中的某个地方。
var loggedIn = false;
原始 Facebook 初始化模板
接下来,让我们看一下基本的 Facebook 初始化模板(如果您使用不同的东西,请告诉我):
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : 'YOUR_APP_ID', // App ID from the app dashboard
channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel file for x-domain comms
status : true, // Check Facebook Login status
xfbml : true // Look for social plugins on the page
});
// Additional initialization code such as adding Event Listeners goes here
};
// Load the SDK asynchronously
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
添加 FB.getLoginStatus()
在以下行之后:
// Additional initialization code such as adding Event Listeners goes here
我们将要使用以下函数检查用户的登录状态:
// See if the User is logged in
FB.getLoginStatus(function(response) {
if (response.status === 'connected')
{
// Mark the user as logged in
loggedIn = true;
}
});
分享前先测试登录
我不知道您在 facebook 上分享的代码是什么样的,但我们假设您将它放入一个名为fbShare()
. 我们现在可以做的是将 onclick 函数分配tryShare()
给您的 Share Button,并使用类似于以下逻辑的方式定义该函数:
function tryShare()
{
if (loggedIn)
{
//User is already logged in and authorized
fbShare();
}
else
{
// Pop open the FB Login dialog
FB.login(function(response) {
if (response.authResponse) {
// Successful login/auth
fbShare();
}
else
{
// Your user didn't want to log in to fb
}
});
}
}
概括
因此,您的代码最终应如下所示:
<head>
...
<script ... >
...
function fbShare()
{
// Your sharing code goes here
}
var loggedIn = false;
function tryShare()
{
// tryShare() function immediately above this..
}
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : 'YOUR_APP_ID', // App ID from the app dashboard
channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel file for x-domain comms
status : true, // Check Facebook Login status
xfbml : true // Look for social plugins on the page
});
// Additional initialization code such as adding Event Listeners goes here
// See if the User is logged in
FB.getLoginStatus(function(response) {
if (response.status === 'connected')
{
// Mark the user as logged in
loggedIn = true;
}
});
};
// Load the SDK asynchronously
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
...
<button onclick="tryShare()">Share on Facebook</button>
除此之外,大部分代码tryShare()
都是直接从Facebook JavaScript SDK Reference复制而来的。让我知道这一切是否有意义:)