简体   繁体   English

使用InAppBrowser进行Phonegap Facebook登录

[英]Phonegap Facebook Login with InAppBrowser

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. 我最近一直在寻找一个好的全球解决方案来进行Facebook登录,也许还有其他登录...经过2天的研究,我设法通过Phonegap上的InAppBrowser使它运行。

I started testing with android version 2.3 > and here is my solution: 我开始使用Android 2.3版进行测试,这是我的解决方案:

Use openFB: repository 使用openFB: 存储库

OpenFB uses inappbrowser. OpenFB使用inappbrowser。

What the script actually does: 脚本实际上是做什么的:

  1. Opens new child window with facebook login and sets the redirect URL 使用Facebook登录信息打开新的子窗口并设置重定向URL
  2. Once the user was redirected to the redirect.html it checks if the login was successfull or not. 将用户重定向到redirect.html后,它将检查登录是否成功。 In the case it was successfull it gets the requested parameters from the facebook api object and appends them to the setVars.html URL. 如果成功,它将从facebook api对象获取请求的参数,并将其附加到setVars.html URL。 Successfull or not, it will then redirect to setVars.html 成功与否,它将重定向到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 现在,我们在login.html中打开的子窗口上的loadstop事件将触发,因为刚停在的URL是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 现在,它从url中提取所需的参数-在我的示例中是电子邮件,id和名称,并将它们写入login.html

1: Create an facebook app, add your domains and make it public 1:创建一个Facebook应用,添加您的域并将其公开

2: create 3 files - login.html,redirect.html,setVars.html 2:创建3个文件-login.html,redirect.html,setVars.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: 将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 的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. 不要忘记在需要的地方添加jquery,cordova.js,index.js,并用您的APP_ID和DOMAINNAME替换所有占位符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM