Question

I've have recently searched for a good global solution to do a facebook login and maybe others... After 2 days of research i managed to get it working via the InAppBrowser off Phonegap.

I started testing with android version 2.3 > and here is my solution:

Was it helpful?

Solution 2

What the script actually does:

  1. Opens new child window with facebook login and sets the redirect URL
  2. Once the user was redirected to the redirect.html it checks if the login was successfull or not. In the case it was successfull it gets the requested parameters from the facebook api object and appends them to the setVars.html URL. Successfull or not, it will then redirect to setVars.html
  3. Now the loadstop event on our opened childwindow in login.html will trigger because the url - it just stoped at - is setVars.html
  4. Now it extracts the needed parameters from the url - in my case the email,id and name and writes them to the login.html

1: Create an facebook app, add your domains and make it public

2: create 3 files - login.html,redirect.html,setVars.html

setVars.html:

<!DOCTYPE html>

    <title>SetVars</title>

    <style type='text/css'>
        /* Styles specific to this particular page */
    </style>

</head>

<body>
</body>

redirect.html:

<div id="fb-root"></div>
<script type="text/javascript" charset="utf-8">

            window.fbAsyncInit = function() {
                          FB.init({
                            appId      : YOUR_ID,
                            status     : true, // check login status
                            cookie     : true, // enable cookies to allow the server to access the session
                            xfbml      : true  // parse XFBML
                          });


                          function getJsonFromUrl(urlString) {
                              var parameterQuery = urlString.split("?");
                              var data = parameterQuery[1].split("&");
                              var result = {};
                              for(var i=0; i<data.length; i++) {
                                var item = data[i].split("=");
                                result[item[0]] = decodeURIComponent(item[1]);
                              }
                              return result;
                            }

                          var fbDataArray = getJsonFromUrl(document.URL);   

                          //If user cancels the permission page
                          if (typeof  fbDataArray['error'] !== "undefined") {
                            location = "http://YOUR_DOMAIN/setVars.html?name=" + response.name + "&email=" + response.email + "&id=" + response.id;
                          }

                          FB.Event.subscribe('auth.authResponseChange', function(response) {

                            // Here we specify what we do with the response anytime this event occurs. 
                            if (response.status === 'connected') {
                              // The response object is returned with a status field that lets the app know the current
                              // login status of the person. In this case, we're handling the situation where they 
                              // have logged in to the app.
                              getFBdata();
                            } else if (response.status === 'not_authorized') {
                              // In this case, the person is logged into Facebook, but not into the app
                              //FB.login();
                              location = "http://YOUR_DOMAIN/setVars.html?name=" + response.name + "&email=" + response.email + "&id=" + response.id;
                            } else {
                              // In this case, the person is not logged into Facebook,
                              //FB.login();
                              location = "http://YOUR_DOMAIN/setVars.html?name=" + response.name + "&email=" + response.email + "&id=" + response.id;
                            }
                          });



              };

              // Load the SDK asynchronously
              (function(d){
               var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
               if (d.getElementById(id)) {return;}
               js = d.createElement('script'); js.id = id; js.async = true;
               js.src = "https://connect.facebook.net/en_US/all.js";
               ref.parentNode.insertBefore(js, ref);
              }(document));



              // Here we run a very simple test of the Graph API after login is successful. 
              // This testAPI() function is only called in those cases. 
              function getFBdata() {

                FB.api('/me', {fields: 'name,email,id'}, function(response) {
                  location = "http://YOUR_DOMAIN/setVars.html?name=" + response.name + "&email=" + response.email + "&id=" + response.id;
                });

              }
    </script>

login.html

<div id="fb-root"></div>

    <div onclick="fbLogin();" style="margin-top: 25px; height: 100px; width: 100%; background-color: blue; color: white; font-size: 40px">Login with Facebook</div>
    <div onclick="location = 'https://www.facebook.com' " style="margin-top: 25px; height: 100px; width: 100%; background-color: blue; color: white; font-size: 40px">Goto Facebook</div>

    <div id="userData"></div>

    <script type="text/javascript" charset="utf-8">


        document.addEventListener("deviceready", function() {



            function getJsonFromUrl(urlString) {
              var parameterQuery = urlString.split("?");
              var data = parameterQuery[1].split("&");
              var result = {};
              for(var i=0; i<data.length; i++) {
                var item = data[i].split("=");
                result[item[0]] = decodeURIComponent(item[1]);
              }
              return result;
            }

            fbLogin = function () {
                var ref = window.open('https://www.facebook.com/dialog/oauth?scope=email&client_id=YOUR_APP_ID&redirect_uri=http://YOUR_DOMAIN/redirect.html', '_blank', 'location=no');

                 ref.addEventListener('loadstop', function(event) { 


                    if(event.url.indexOf("http://YOUR_DOMAIN/setVars.html") != -1) {

                        ref.close();

                        var fbDataArray = getJsonFromUrl(event.url);

                        if (fbDataArray['email'].indexOf('@') != -1) {

                            $('#userData').html('<img style="display:block; height: 150px; width: 150px; margin: 0px auto; margin-top: 50px;" src="https://graph.facebook.com/' + fbDataArray['id'] + '/picture?width=100&height=100" />');
                            $('#userData').append('<div style="text-align:center; height: 50px; width: 300px; margin: 0px auto; font-size: 25px; margin-top: 25px;">' + fbDataArray['email'] + '</div>');
                            $('#userData').append('<div style="text-align:center; height: 50px; width: 300px; margin: 0px auto; font-size: 25px; margin-top: 10px;">' + fbDataArray['name'] + '</div>');
                            $('#userData').append('<div style="color: green; text-align:center; height: 50px; width: 300px; margin: 0px auto; font-size: 25px; margin-top: 10px;">ACCESS GRANTED!</div>');
                        } else {
                            $('#userData').html('<div style="color: red; text-align:center; height: 50px; width: 300px; margin: 0px auto; font-size: 25px; margin-top: 10px;">ACCESS DENIED!</div>');
                        }
                        //alert(fbDataArray['email'] + ' | ' + fbDataArray['name'] + ' | ' + fbDataArray['id']);

                    }


                 });
                 ref.addEventListener('loaderror', function(event) { alert('error: ' + event.message); });

            };




               window.fbAsyncInit = function() {
                FB.init({
                  appId      : YOUR_APP_ID,
                  status     : true,
                  cookie     : true,
                  xfbml      : true
                });

              };

              (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>

Dont forget to add jquery,cordova.js,index.js where its needed and replace all the placeholders with your APP_ID and DOMAINNAME.

OTHER TIPS

Use openFB: repository

OpenFB uses inappbrowser.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top