FB.Event.subscribe & FB.Event.unsubscribe
用來listen相關facebook事件,當特定事件出現時就執行callback functionFB.Event.subscribe(event, callback function)讓我們來看一段程式碼:
FB.Event.subscribe('auth.sessionChange', function(response) { if (response.session) { alert(response.authResponse.accessToken); //使用者登入,資料寫入cookies裡 } else { alert("Ohoh"); //使用者登出,cookies被清掉 } });
除了範例中所提到的,我們還能訂閱以下的事件:
- auth.login - fired when the auth status changes to connected
- auth.logout - fired when your app notices that there is no longer a valid user
- auth.authResponseChange - fired when the authResponse changes
- auth.statusChange - fired when the status changes (see FB.getLoginStatus for additional information on what this means)
而傳給callback function的參數"response"長得像這樣:
{ status: "", /* Current status of the session */ authResponse: { /* Information about the current session */ userID: "" /* String representing the current user's ID */ signedRequest: "", /* String with the current signedRequest */ expiresIn: "", /* UNIX time when the session expires */ accessToken: "", /* Access token of the user */ } }
而至於unsubscribe的部分則是subscribe的相反,就是取消listen特定事件,可以自己試試看。
FB.login
顧名思義,就是以facebook登入所在網站。前提是你必須先用FB.init設定了SDK環境、設定appId。FB.login(callback function, permissions scope)來,讓我們再
FB.login(function(response) { if (response.authResponse) { console.log('Welcome! Fetching your information.... '); FB.api('/me', function(response) { console.log('Good to see you, ' + response.name + '.'); }); } else { console.log('User cancelled login or did not fully authorize.'); } }, {scope: 'user_about_me,email,user_likes'});這邊要注意的是第二個參數是一個object,只有一組key:value,key一定是"scope",value是一連串以permission組成的String,中間以逗號分開。
scope中所指定的就是要從使用者那拿到的授權,要看詳細清單可以看facebook的官方文件。
FB.getLoginStatus
基本上在一個facebook應用中我們需要判斷使用者是以下三個狀態中的哪一種:- 使用者登入了facebook也授權給你的應用程式 (connected)
- 使用者登入了facebook但還沒授權給你的應用程式 (not_authorized)
- 根本沒登入 (unknown)
這時我們就可以使用FB.getLoginStatus來搞清楚使用者的狀態
FB.getLoginStatus(callback function, force)force是一個boolean,會強制reload使用者的登入狀態(預設為false)
我們再來偷一段程式碼來搞清楚他的用法:
FB.getLoginStatus(function(response) { if (response.status === 'connected') { // the user is logged in and has authenticated your // app, and response.authResponse supplies // the user's ID, a valid access token, a signed // request, and the time the access token // and signed request each expire var uid = response.authResponse.userID; var accessToken = response.authResponse.accessToken; } else if (response.status === 'not_authorized') { // the user is logged in to Facebook, // but has not authenticated your app } else { // the user isn't logged in to Facebook. } });
response object:
{ status: 'connected', authResponse: { accessToken: '...', expiresIn:'...', signedRequest:'...', userID:'...' } }
最近剛好需要學習 Facebook API,搜尋到了這一篇系列文章,我覺得寫的很棒,謝謝你,學習了 XD
回覆刪除不會,平常也常常爬到你的文章,只是都默默潛水 XD
刪除