Apidcloud

Working javascript example - facebook sdk 4.0

Nov 23rd, 2014
193
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <button id="loginBtn">Facebook Login</button>
  2. <div id="response"></div>
  3.  
  4. <script>
  5.     function getUserData() {
  6.     FB.api('/PAGE-ID/posts', function(response) {
  7.         console.log(response.data);
  8.        console.log(response.data.length)
  9.        for (var i=0, l=response.data.length; i<l; i++) {
  10.           var post = response.data[i];
  11.           console.log(post)
  12.           if (post.message) {
  13.              console.log('Message: ' + post.message);
  14.           } else if (post.attachment && post.attachment.name) {
  15.              console.log('Attachment: ' + post.attachment.name);
  16.           }
  17.        }
  18.     });
  19. }
  20.  
  21. window.fbAsyncInit = function() {
  22.     //SDK loaded, initialize it
  23.     FB.init({
  24.         appId      : 'APP-ID',
  25.         xfbml      : true,
  26.         version    : 'v2.2'
  27.     });
  28.  
  29.     //check user session and refresh it
  30.     FB.getLoginStatus(function(response) {
  31.         if (response.status === 'connected') {
  32.             //user is authorized
  33.             document.getElementById('loginBtn').style.display = 'none';
  34.             getUserData();
  35.         } else {
  36.             //user is not authorized
  37.         }
  38.     });
  39. };
  40.  
  41. //load the JavaScript SDK
  42. (function(d, s, id){
  43.     var js, fjs = d.getElementsByTagName(s)[0];
  44.     if (d.getElementById(id)) {return;}
  45.     js = d.createElement(s); js.id = id;
  46.     js.src = "//connect.facebook.net/en_US/sdk.js";
  47.     fjs.parentNode.insertBefore(js, fjs);
  48. }(document, 'script', 'facebook-jssdk'));
  49.  
  50. //add event listener to login button
  51. document.getElementById('loginBtn').addEventListener('click', function() {
  52.     //do the login
  53.     FB.login(function(response) {
  54.         if (response.authResponse) {
  55.             //user just authorized your app
  56.             document.getElementById('loginBtn').style.display = 'none';
  57.             getUserData();
  58.         }
  59.     }, {scope: 'read_stream', return_scopes: true} // depending on the information we want to retrieve, we might need to set permissions
  60.  );
  61. }, false);
  62.    
  63. </script>
RAW Paste Data