Facebook API - 用户登录后运行javascript

时间:2011-05-31 11:02:10

标签: javascript facebook api

我得到的那一刻:

<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>    
<script>
  window.fbAsyncInit = function() {
    FB.init({ appId:'188492754501683', cookie:true, status:true, xfbml:true }); 
  };
</script> 
<fb:login-button perms="email">
  login with Facebook
</fb:login-button>    

我想运行一些代码来提取电子邮件,并说:

FB.api('/me', function(res) { if (res != null) { alert(res.email); } } );

当我在FB.init()的调用下添加它时,它在加载窗口时立即运行,这是可以理解的但不是我想要的。

我希望代码在用户点击“使用Facebook登录”按钮后运行,然后成功登录等等。

任何人都可以指出我正确的方向,我搜索谷歌但似乎无法找到任何东西:/

先谢谢,汤姆。

1 个答案:

答案 0 :(得分:3)

你可以使用这个事件:

<!DOCTYPE html>
<html  xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
    <title>Facebook Test</title>
</head>
<body>
        <div id="fb-root"></div>        
        <script>
window.fbAsyncInit = function() {
    FB.init({appId: 'YOUR_APP_ID', status: true, cookie: true, xfbml: true});
    FB.Event.subscribe('auth.login', function(response) {
        // user logedin
    });
};
        (function() {
            var e = document.createElement('script');
            e.type = 'text/javascript';
            e.src = document.location.protocol +
                '//connect.facebook.net/en_US/all.js';
            e.async = true;
            document.getElementById('fb-root').appendChild(e);
        }());

</script>

        <fb:login-button perms="email">
            Login with Facebook
        </fb:login-button>        
</body>
</html>

请参阅http://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/了解您可以订阅的更多活动。

使用完整示例更新