Cordova/PhoneGap Facebook Integration without Plugin

04/08/2014 update: pushed version 0.2 with a couple of bug fixes.

Many consumer apps provide a Facebook Login option, as well as other Facebook integration features such as posting to your feed, getting your list of friends, etc.

Cordova has a Facebook Plugin that makes that integration easy. Internally, the plugin uses both the Native and the JavaScript implementations of the Facebook SDK, and historically, it has sometimes been hard for the plugin to keep up with new versions of these SDKs, as well as new versions of Cordova.

In a recent Cordova project, I integrated with Facebook without using the Facebook Plugin, and in fact without using the Facebook SDK at all. I implemented a traditional OAuth workflow to log in (as described here), and made direct HTTP requests to Graph API endpoints to retrieve and post data.

I encapsulated that logic in a micro library that I called OpenFB, and decided to share it in this article. Here are a few code examples…

Login using Facebook:

openFB.login(scope, successHandler, errorHandler);

Get the user’s list of friends:

openFB.api({path: '/me/friends', success: successHandler, error: errorHandler});

Post on the user’s feed:

openFB.api(
    {
        method: 'POST',
        path: '/me/feed',
        params: {
            message: 'Testing the Facebook Graph API'
        },
        success: successHandler,
        error: errorHandler
    });

The approach used in OpenFB (plain OAuth + direct requests to Graph API endpoints) is simple and lightweight, but it is definitely not perfect.

Pros:

  • No plugin dependency and no uncertainties when new versions of Cordova or the Facebook SDK are released.
  • Works for all platforms, including platforms for which a version of the plugin doesn’t exist.
  • Works for both browser-based apps and Cordova apps.

Cons:

  • Not full-fledged, less out-of-the box features.
  • Integration not as tight. For example, no native dialogs, etc.

Browser and Cordova Apps

The library works for both browser-based apps and Cordova/PhoneGap apps. When running in a browser, the OAuth URL redirection workflow happens in a popup window. When running in Cordova, it happens inside an “In-App Browser”.

Try it here

You can try the sample app here (My sample Facebook app is called Sociogram). This application is intentionally simplistic to keep the code readable and focused on the Facebook integration. The same app works inside Cordova.

openfb

Source Code

OpenFB is available in this repository on GitHub.

Getting Started

To run the sample on your own system:

  1. Create a Facebook app here: https://developers.facebook.com/apps. In the advanced settings, make sure you declare a “Valid OAuth redirect URI”. For example, if during development you access your application from http://localhost/openfb/index.html, you must declare http://localhost/openfb/oauthcallback.html as a valid redirect URI. Also add https://www.facebook.com/connect/login_success.html as a Valid OAuth redirect URI for access from Cordova.
  2. Copy the Facebook App Id and paste it as the first argument of the openFB.init() method invocation in index.html.
  3. Load index.html, from a location that matches the redirect URI you defined above. For example: http://localhost/openfb/index.html

Summary

No rocket science here. The Facebook Plugin is still the best technical solution because it provides a tighter integration with Facebook (using native dialogs, etc). However, if you are looking for a lightweight and easy-to-set-up solution with no dependencies, or if you are targeting mobile platforms for which an implementation of the plugin is not available, you may find this library useful as well. I’d love to hear your feedback, and learn how you are integrating with Facebook.


  • Pingback: Cordova/PhoneGap Facebook Integration without Plugin | SDK News()

  • Anonymous

    Great stuff Christophe, I was just looking for this exact solution.
    However I can’t seem to get this working for my Cordova app, the login works, then I see facebook redirecting to a facebook URL with an access token in the URI, but the window doesn´t close and the callback on openFB.login is never invoked (neither the success or error callback).
    When I isolate the code from my cordova project and run it in my browser it works fine… what am I missing / doing wrong? Thanks in advance!

    • Hi,
      For Cordova you have to add <script src=’cordova.js’></script> in index.html. I checked in a new version of index.html where it’s there by default. I also just checked in a fix for Cordova detection when running in the emulator.

      Also make sure you add the inappbrowser core plugin:
      cordova plugins add org.apache.cordova.inappbrowser

      Let me know if this works for you.

      Thanks,
      Christophe

      • Anonymous

        Thanks Christophe, I was missing the inappbrowser plugin (perhaps you can update the readme in your git repo to include this instruction).
        Works on my mobile device now, next step is to get it running in a ripple emulator, any thoughts on that? ;) Would it be possible at all?

        • Anonymous

          Would love to see how you got it working on mobile. Even after adding the plugin, the login window doesnt seem to go away. Seems like I have tried everything.

      • Sam

        openFB is working fine in my browser but in mobile app its showing me this message –
        Success
        SECURITY WARNING: Please treat the URL above as you would your password and do not share it with anyone.
        Give me a proper solution.

        Thanks in advance

        • Andy

          Hi Christophe,
          Thank you so much for your library! But I’m also experiencing that issue. I just got stuck on that “success security warning” page and can’t get back to my app from it.
          We would really appreciate your help on this problem.

          • Andy

            I made it work finally.
            After digging around I found out that I was missing this line in config.xml file:

            (don’t forget to add xmlns:gap=”http://phonegap.com/ns/1.0″ namespace as well)

            Hope this will help someone too.

          • Andy

            Oh, I just noticed that this line has been stripped out from my comment, so I’ll paste it without opening and closing brackets:

            gap:plugin name=”org.apache.cordova.inappbrowser”

            (it must be a self-closing XML tag)

        • Miguel

          I have the same problem, any ideas?
          thank you

        • Miguel

          I have the same problem:

          “SECURITY WARNING: Please treat the URL above as you would your password and do not share it with anyone.”

          any ideas?
          thank you

          • Miguel

            Solution
            install cordova plugin org.apache.cordova.inappbrowser.
            In cordova 3.5:
            cordova plugin add org.apache.cordova.inappbrowser

            And facebbok, , app, avanced, Valid OAuth redirect URIs: https://www.facebook.com/connect/login_success.html

            And openfb.js: oauthRedirectURL = ‘https://www.facebook.com/connect/login_success.html’,

            Regards

      • priyanka

        hello
        i am also facing same problem cordova app is working properly in browser but not in mobile app it showing me a success security message….would you please help us

        Regards

        • Skyview

          Hi piyanka,
          I have the same problem, did you found a solution yet?

      • A.S.Karthick

        hi,I used this openFB for my ios app.It works well for the first time login my application via facebook login.when i logout my app then i tried to login my app via facebook, it did not worked. First time, the variable runningInCordova is true when i logout my app that variable runningInCordova is false. How can i fixed that please help me……..

        • Try this: !/^(http(s)?:\/\/)/g.test(window.document.URL); to detect environment.

    • Nitin

      hi,

      i am develop one application. that application using facebook with login using your tutorial.

      but application redirect callback url http://localhost:8888/menooz/asset/www/addmenu.html

      that was error application can`t connect to server.

      plz help us. thanks

  • Pingback: Tutorial: Integrate Facebook without Plugins (PhoneGap)()

  • Solidux

    Thanks for sharing.
    I have a question, you can share images with your method?
    Regards

    • sondes

      Hello I’m developping a cordova application on which I have to share links with photo on facebook, is it possible to share image and url using this share button?

  • Doron

    Hi
    I’m trying to implement this with my ionic cordova app.
    I want to do it a little differently because i need to “login” button to be in an inner state rather in the main state.
    Any way i get the “login” to connect, but the oauth window does not close and i get this error:
    TypeError: injector is undefined
    injector.invoke(function (OpenFB) {

    and the access token is not saved anywere so i cannot access the graph api.
    any chance you can help?

  • Kelvin Jones

    When trying to run this in ios device i get error when click login to facebook

    index.html
    OpenFB login failed

    any ideas?

  • Is there any particular reason why i am unable to post to facebook. I am able to login and retrieve info (i.e. Name) but if i add a message and try to share. i receive the error:

    (#200) The user hasn't authorized the application to perform this action

    Have you come across this before?

    Thanks for sharing btw :)

    • Change “openFB.login(’email’,” to “openFB.login(’email,publish_actions’,”.
      You can add additional permissions if you want.

      https://developers.facebook.com/docs/facebook-login/permissions/

      • Thamizharasan

        Hi Jonnas, I used publish_actions but it’s the permission is asked only for public profile. what should i do..?

    • zua

      Hi Simon,

      try change your permission to this

      }, {scope: ‘read_stream,email,publish_actions,publish_stream’});

      delete this app from Facebook first and test again.

  • Great job Christophe. However, I have some doubts, the access token retrieved from the oauth method that you used, is it a short-term access token or a long-term access token?

  • Praful

    I am getting blank facebook page as my redirect url is like “file:///”.
    whats the issue?

    • zua

      Hi Praful,

      Open “openfb.js” and change baseURL to link where you place oauthcallback.html and logoutcallback.html.

      example: baseURL = ‘http://example.com/’,
      oauthRedirectURL = baseURL+’oauthcallback.html’,
      logoutRedirectURL = baseURL+’logoutcallback.html’,

  • Vipul

    Nice stuff. (Y). Could you please provide the code to get feeds from profile ?

  • Henry

    Hi Chris. This is suer helpful and way easier to use than the phonegap Facebook plugin. I was wondering how would I go about getting the permission to get more data from the users? I tried adding it in openfb.js under scope but that didn’t work. I also tried openFB.login(“email, id, gender”) but that didn’t work either. Thanks!

  • Sasha

    Hello, i’m having a problem with facebook configuration because when i try to login my user the page says: “The given url is not allowed by the application configuration…”
    Its about 5 days that i try to make it work any help would be appriciated.

  • sayang

    emm i wonder could you come out with tutorial facebook with plugin….having a lot problem using phonegap 3.4 with facebook plugin….other resources over the internet almost rubbish….

  • Sasha

    After almost 3 days i can say that this worked for me, thank you very much for sharing.

    • Brandon

      Sasha what did you do? We are having the same issues? Given URL not allowed by configuration.

    • nawaz

      Hi Sasha, would u please tell what did u do for that.. i’m confused that what will be the canvas url if app is on device.. My inappbrowser working fine. i’m getting the above error. would u please explain? Thanks in advance :)

      • Nawaz

        Hi Guys now it is working for me.. i m doing a phonegap app for windows phone 8 . So for fb login i’m using openFb. I’ve seen questions above that people are facing problems using this then people posting that it worked but no one posted how they do. I’ve faced the same problem now i got the solution. These are the steps i followed when i run the cordova “app” on windows phone 8.

        First u need to install inapp browser plugin on root folder.

        1. I’ve added openfb.js in my js folder
        2. on loading i called openFB.init(“app_id_from_facebook_app_page”);
        3. on button click i called openFb.login();

        Fb app Settings :

        1. in basic tab :
        canvasURL : http://localhost/www/ //(it has worked in device)
        secureCanvasURL : https://localhost/www/

        2. No need to give app domains . it will take defaults
        3. Dont give valid OAUTH redirect URIs in advanced tab. keep it blank
        4. don’t change anything in openFB.js

        That’s it
        Now the inapp browser opens with fb login page.

        Happy Coding :)

        Thanks :)

  • Alfredo

    Hello Christophe,

    Implemented this in a Cordova/Phonegap App but All I get is the same as the first comment in this article. App goes to the login dialog, logs in then just a blank screen with the little blue button of the inappbrowser view. No callbacks fired.

    Browser version does nothing. FB settings appear to be ok. I’m testing using PhoneGap Developer App on iOS.

    Your help will be appreciated.

  • Thibka

    Hey,

    Thanks for your solution, it looks great. However, even though the login() method returns a success message, I can’t get the getInfo() method to work.
    Regardless if I try with your example app or with mine, the getInfo() method returns the following error :
    “Invalid OAuth access token”
    I have to admit I’m not quite comfortable with the facebook API, but I can’t figure out what I’m doing wrong… Do you have any idea ?
    Thanks a lot for you help,

    Thibka

    • Thibka

      My bad, I just figured out what was wrong : I didn’t understand that I had to login() first to have access to the getInfo() method.
      Also, you should specify in your doc that the cordova.inappbrowser must be installed, as I only realized that after reading the comments.
      Anyway, thanks a LOT for your solution. :)

    • I pushed a fix for a bug where the login window was not closing when the token was received too fast: In that case, the inappbrowser was still opening (with an animation), which caused an exception when trying to close it. Should be fixed now. Let me know if it doesn’t work for you.

  • Chanti

    Hi,

    I able to run this is Browser.

    I am facing problem while running in Device.
    What should be the OAuth Redirect URL that need to be set in Facebook Application.
    I tried adding localhost/oauthcallback.html but it cant be located as it is running in device.

    • Brandon

      Same problem

    • Chanti

      Got it! We need to add inappbrowser plugin to the cordova project.
      Thanks.

      • Brandon

        Thanks Chanti….I did that as someone else mentioned that. But how did this affect your FB Settings. Meaning when I run localhost/openfb/www/index.html it works from my local dev box and my FB settings show localhost/openfb/www/oauthcallback.html. However when running in emulator or device it does not work.

        • When running in Cordova, the default OAuth redirect URI is: https://www.facebook.com/connect/login_success.html. So make sure you add that in your app configuration on Facebook (Settings > Advanced > Valid OAuth redirect URIs).

          When running in the browser, the default oauthcallcack url is now: origin (protocol://server:port) + /oauthcallback.html’. So if you run your app from http://localhost:3000, make sure you add http://localhost:3000/oauthcallback.html as a Valid OAuth redirect URI in you Facebook App config (Settings > Advanced > Valid OAuth redirect URIs) and that the oauthcallback.html is indeed reachable at that location.

          if you run your app from http://myserver, make sure you add http://myserver/oauthcallback.html as a Valid OAuth redirect URI in you Facebook App config (Settings > Advanced > Valid OAuth redirect URIs) and that the oauthcallback.html is indeed reachable at that location.

      • Pratyancha

        Where we have to add that inappbrowser plugin???

        • Dwy Saputro

          so, what the default canvas URL for phonegap-app should i register in facebook?
          thank you

      • nawaz

        Hi Chanti, would u please explain the settings in facebook app page.. I’m facing the same issue. that there’ll be localhost in device right? so what will be the canvas url.. In my case my app returning when i call window.location, is “x-wmapp0:www/index.html”. So for this what will be the canvas url and what will be the path for oauthcallback.html?

        Thanks in advance :)

  • Icaro

    Is Therer no way to open a dialogue within the phonegap with facebook login screen?

  • Abd

    Hi,
    Thanks for your amazing work It really helped me a lot.
    I have a question, by using this method what type of platform I should add to my Facebook app in the Settings section? do I need to generate hash for Android by using this method also?
    Any help will be appreciated.

  • Chanti

    Hi,

    It is clear that facebook token we get when we run from browser is Short live token.

    What kind of access token that I get if I run from real mobile device?

    One thing that is surprising me is, my app received an access token which is being used since 4 days and working fine.

    Any idea?

    • Akash

      Hi Chanti,

      Similar to Brandon, would you know the URI you used to make this work? I tried localhost/assets/www/oauthcallback.html and a few others, none working. Shows a blank screen on the Android.
      Thanks

      • Tolotra

        Hi,
        In device it doesn’t work because ‘readydevice isn’t fired’, the solution is to add in your index.html. Don’t change anything in openFb.js and just call the openFb.init(‘YOUR_APP_ID’) with no other parameters. After 2 days of coffee i was able to get it work.

        @Christophe Nice job!

        • Tolotra

          oups seems like it doesn’t my call script, as i said you should include cordova.js script in your index.

  • Soroush

    How does this work for Cordova apps? the callbacksuccess for login will never be fired since the users get stuck in success page.

    • See my answers above. Make sure you download the latest version and that your Valid OAuth redirect URIs are configured.

      • Heber

        I am using version 0.3 in Android and the method openFB.init still doesn’t redirect my URI.
        My URI is “file:///android_asset/www/index.html” Thanks.

    • Brandon Hines

      Soroush,

      Did you look at my github for the Sociogram app?

  • WilsonLeal

    Very good!!
    Thanks a lot.

  • Vaibhav Narula

    Hi Chris,

    Amazing Post as usual.

    There is one question . How can we pull other data about the user using your library.?

    • vaibhav

      hey, did u got any solution to fetch other data from facebook….i require email id, profile pic and friend list.

      thanks

  • Jayaprakash

    HI,

    This script was amazing and works perfect. But one thing is users can’t logout completely from facebook.

    • Shadi

      did you find a solution for this issue, I face the same???

  • Abd

    do I need to generate hash for Android to submit the facebook app even if i’m using this method also?
    if yes can you help me how to generate this hash?

  • This is a vital topic ‘Cordova/PhoneGap Facebook Integration without Plugin | Christophe Coenraets’. Diamonds and Facebook Login option give us a blinding glimpse of the innovations that are coming our way—and that they are helping to create.

  • One who can remember the sills and one who is an expert, or at least your
    thoughts can certainly stimulate anxiety, and your ability to sleep and function well.
    Another aspect of counseling, and school psychologists.

    Of course, therre is often a complaint of individuals seeking counselling.
    If one has ever google quest looked into a pair of shoes can be seen on Thursday.

  • Pingback: Checklist for setting Facebook Connect for PhoneGap | TienLe's Blog()

  • Shrikant Havale

    Excellent solution, for integrating facebook into applications. Only concern is about logout, doesn’t completely logout from application, I read several threads on stackoverflow about deleting cookies, clearing sessions, using facebook, logout.php , but no luck yet. Did anybody got solution for implementing logout

    • Mustafa

      Same issue here!

    • A.S.Karthick

      Hi,

      Did you try this code, its working for me…..

      function logout(callback) {
      var logoutWindow,
      token = tokenStore[‘fbtoken’];
      tokenStore.removeItem(‘fbtoken’);
      if (token) {
      logoutRedirectURL=”******your domain url**********”;
      var url=FB_LOGOUT_URL + ‘?access_token=’ + token + ‘&next=’ + logoutRedirectURL;
      $.ajax({

      type : ‘POST’, url : url,
      success : function(responseText){
      //alert(“Testing”);

      },error: function(e){
      //alert(“error”);
      setTimeout(function(){ },5000);
      console.log(” “+e);
      }
      });

      }

      Thanks,
      karthick

    • Fernando

      Add into loginWindowExit function in openfb.js the next sentences:

      loginWindow = window.open(‘http://m.facebook.com/logout.php?confirm=1&next=https://www.facebook.com/connect/login_success.html&access_token=’+tokenStore[‘fbtoken’], ‘_blank’, ‘location=no’, ‘clearcache=yes’, ‘clearsessioncache=yes’);
      loginWindow.close();

      You must to do a facebook logout on the same instance of the inappbrowser window, these lines should be close completily the facebook session. Sorry for my english, I speak spanish.

  • Keylies

    Hello Christophe,

    Very nice plugin. It works well with browser and on my mobile.

    I only got an error when I try to use it with local ripple : http://www.raymondcamden.com/index.cfm/2013/11/5/Ripple-is-Reborn

    It’s the only way to test lastest cordova/phonegap lib on a browser, but I get a white screen with InappBrowser issue. It seems Ripple doesn’t support InappBrowser.

    If this variable : window.tinyHippos is true, it uses Ripple. But is there a way to bypass the error, I don’t see how…

  • Rajesh

    It’s not running sir. while i am running the file on my emulator its loading only. nothing came sir. can you please help me.?

  • Very nice work, Christophe. I’ve got it functioning perfectly in the browser, but I can’t get by the file:/// protocol problem in iOS or Android. The index.html file is loaded with file:/// instead of on http://localhost, and Facebook doesn’t allow file:/// protocol redirect URL’s. Have you gotten this working in the iOS emulator?

    Thanks!

    • Ale

      same issue here.. any ideas?

    • Dirk Postma

      +1 What to do about this?

  • Rahul Mandhani

    Hey,
    How to use this approach for phonegap android application… I try to implement it but stuck on what url to provide in apps settings

    Can any one help??

  • Hi there,

    In my case fails,

    I am using phonegap 3.4 and the facebook login page is opened in a popup and as the callback uri is a file://authcallback.html then facebook wont print the login form, just a white screen. (If I, manually use the callback uri is setted in my app settings then it works )

    Any thoughts?

    Thanks!

  • Tejas

    Hi,

    How to use “Like Page” functionality from phonegap application using this openFB api’s.

    Any idea?

    Thanks!

  • Pratyancha

    When I press the login button on the android facebook page opens and after I login, the success page does not close. Getting ‘Success Warning Message’. Ahere we have to add that “inappbrowser plugin” ? In index.html file??? Please its urgent.

  • Dave

    Great “plugin”. But what if we wanted to get the profile picture URL?

    See: https://developers.facebook.com/docs/graph-api/reference/v2.0/user/picture

    I am doing this, but it doesn’t return any data.

    openFB.api({
    path: ‘/me/picture’,
    params: {
    redirect: ‘0’,
    height: ‘200’,
    width: ‘200’,
    type: ‘normal’
    },
    success: function(data) {
    console.log(JSON.stringify(data));
    document.getElementById(“userName”).innerHTML = ”;
    },
    error: errorHandler});

    Thannk you.

    • Ritij

      Yaa I m also Facing the dame problem…Can anyone provide the code to get the profile image through open fb librabry

      • Ritij

        its urgents..guys…any idea

        • Ale

          Profile picture is avaible on this url:
          ‘https://graph.facebook.com//picture?type=large’

          • Ale

            you need to add user_id after .com/

    • Yogesh

      Did find a solution for this

  • Mohini

    Hello all,
    Can anyone suggest me how can I set cookie TRUE in openFB.login function.?

  • Pingback: Facebook mobile login: come integrarlo in un’applicazione HTML5 | upCreative()

  • scibilo

    hi,
    great post!
    You can store the login/signup information in a mysql database?
    It’s necessary to send push notifications.

    Thanks in advance.

    Regards

  • Very nice blog post. I absolutely love this website. Keep it up!

  • Kia

    On va te dire que ce n’est guère absurde !

  • Ezam

    hello. i had a problem when use the users likes limit. when i put the limit to 100 then i got error message. ‘An active access token must be used to query information about the current user’ . So any solution regarding on this? please help me buddies.

  • ernesto

    Hi, I’m trying to use it inside an appgyver project.
    Login seems to work and the FB windows is properly closed, but after the alert “Facebook login succeeded” in the login callback is fired the iOS simulator crashes.
    Any Idea?

    Thanks in advance

  • Thamizharasan

    Hi Christophe Coenraets thanks for your great work.

    I’m having a issue to post photos in user feed. I cant get the extended permission (publish_actions) during login. What should i do to post the photo on user feed. Please kindly help me to resolve this issue…!

  • Developer

    Very nice work. But while i tried your sample the share is not working. And also i cant get extended permissions through login. Please help me in solving this issue.

  • Akash

    Hii when i change the app id and press the login button it just display me a blank screen. Please help

  • Hitest

    Thanks Christophem, for this great solution.
    but i am getting message like “Given URL is not allowed by the application configuration…”

    did i do something wrong ?

    my file structure is as follow

    newapp\www\index.html
    newapp\www\oauthcallback.html
    newapp\www\openfb.js

    so oauthentication url should be like following ??
    http://localhost/oauthcallback.html

    Thank You :)

  • Norwill

    Great post,

    Only two questions.

    1. Is this compatible with the new version of facebook sdk (2.0) ?
    2. This open the facebook application if i have installed ?

    Thanks.

  • Je vois immédiatement que vous maîtrisez superbement bien le sujet

  • What is the truth, and how Inhabitat editor Jill’s solar-powered
    backpack has been a big week in general for green transportation announcements, as
    several supercharged electric vehicles hit the streets will be a big challenge.
    Today, the top players in the auto industry of the world is the introduction of Asian car manufacturers in the engines of their latest models, while
    keeping the excellent quality of their car battery bracket engine performance.
    If youu are car battery bracket an grown up with a vehicle that
    has a price that justifies its mileage.

  • 2014 new china cheap jerseys store, all jerseys for both man and woman, 100% quality guarantee, fast and free delivery.

  • the Clippers jersey for mens kids and womens sale

  • Pingback: PhoneGap Facebook Plugin – maintenance update | Shazron's Cordova (aka PhoneGap) Blog()

  • For everyone having trouble with the redirect_uri: If you are using this script within Cordova, the redirect URI should not be set. The script then uses https://www.facebook.com/connect/login_success.html as a redirect_uri, reads the value from that window and then closes the window automatically.

  • Nets jerseys cheap Review China

  • Best Place To Buy wholesale jerseys Panthers cheap

  • Buy wholesale Sabres cheap jerseys For Kids And Women

  • Shop for cheap authentic jerseys free shipping and get our ultra fast 7-day shipping standard and 365 day returns on any size order only at our cheap authentic jerseys free shipping online shop.

  • zua

    Thanks very easy but share not working!

  • sonu

    i am also facing same problem cordova app is working properly in browser but not in mobile app it showing white screen when click login. i am also set https://www.facebook.com/connect/login_success.html in aout .would you please help us

    • zua

      Hi Sonu,

      Try this

      Open “openfb.js” and change baseURL to link where you place oauthcallback.html and logoutcallback.html.

      example: baseURL = ‘http://example.com/’,
      oauthRedirectURL = baseURL+’oauthcallback.html’,
      logoutRedirectURL = baseURL+’logoutcallback.html’,

      • sonu

        this is my openfb.js code

        baseURL = location.protocol + ‘//’ + location.hostname + (location.port ? ‘:’ + location.port : ”) + context,

        oauthRedirectURL = baseURL + ‘/www/oauthcallback.html’,

        logoutRedirectURL = baseURL + ‘/www/logoutcallback.html’,
        this is showing in console
        “file:///android_asset/www/logoutcallback.html”, source: file:///android_asset/www/openfb.js (39)
        and problem is same.

        • zua

          Change to that i provide above.
          Delete
          baseURL = location.protocol + ‘//’ + location.hostname + (location.port ? ‘:’ + location.port : ”) + context,

          and direct change to

          example: baseURL = ‘http://example.com/’, //where you place this 2 html file
          oauthRedirectURL = baseURL+’oauthcallback.html’,
          logoutRedirectURL = baseURL+’logoutcallback.html’,

        • zua

          Facebook now need approval to get user feed and post to wall. So at developer.facebook.com we can send at “Status & Review” at the bottom have “Start a Submission” and I take few days for Facebook approval.

          For now only admin can share to wall. Other user cannot.

      • Mustafa

        It works fine for me, Thanks :)

  • Attractive section of content. I just stumbled upon your weeb site and in accession apital to assert that I afquire in fact enjoyed account your blog posts.
    Anyway I will be subscribing to your augment
    and even I achievement you access consistently rapidly.

  • Pingback: Cordova Facebook Login – User Information()

  • vaibhav verma

    everything is working fine , user can login to my app but how to logout from facebook if another user wants to user different login ID on same device. ?? please help

  • frz

    the main point of the cordova facebook plugin is that it uses the facebook app to log you in and degrades gracefully, your code moves the focus to another browser window which defeats the purpose.
    You should look at using display type ‘touch’ at least so the focus remains in the same window view.

  • Yes, work 100% thanks for the article!

  • any chance you can answer this, a lot of folk would appreciate it https://github.com/ccoenraets/OpenFB

  • any chance you can answer this, a lot of folk would appreciate it http://stackoverflow.com/questions/25369607/phonegap-and-facebook-idiots-guide

  • Hello Christophe,

    thank you for your awesome work.
    The plugin worked like a charm.

    I’ve added a pull request on github,
    looking forward for your answer.

    Best greets
    David

  • Harika Bir site, Mükemmel paylaşımlar Admin ellerin dert görmesin

  • Hello Christophe,
    very nice your article and your library help me very well.
    I try the script, work perfectly on browser but with cordova i got the warning “The redirect URL must be absolute”.
    You have any idea?
    thank you very much.

    • sadiveor

      Hello i got the same problem did you found a solution ?

      Thank you very much

      • Peter

        Me too guys having the same issue, any ideas please? Tks

  • Bhagyashree

    Very Nice Plugin !!

  • Robson Braga

    Awesome addon! Works like a charm. Thanks a lot!

  • Miguel

    Hello,
    How to logout and login diferent user.
    Regards

  • ABDows

    Not working on windows phone. Including your exemple.
    get error : Can’t reliably guess the Oauth redirect URI.Please specify it explicity in openFB.init()

  • Hello all,

    Anyone got solution for not getting the Success or done window closed.

    I am facing this problem for iphone though it’s working well for android.

    Please do the needful.

  • Dor

    How do I use this library to open facebook apprequests dialog?

  • Great Job! I am going to try that now!

  • Alberto

    I’m still receiving the “SECURITY WARNING: Please treat the URL above as you would your password and do not share it with anyone.”. Those solutions about setting the https://www.facebook.com/connect/login_success.html didn’t worked for me.

    Any ideas?

    Thanks in advance

    • Alberto

      I realized that loginWindow_loadStartHandler(event) is not firing. Im working with android, cordova, inappplugin and launching it in a device. Any ideas? please help me

      • Franco

        I have the same issue…
        I’m working on it, to see why the even it not being fired, without luck.

        Any thoughts?

        • Franco

          OK, as we all know it was my bad…
          I found the issue:
          – First I was redirecting to the default, and as it wasn’t on the same domain, I wasn’t able to get the event listeners to work.
          – I used the re-directs provided with the library at init, redirecting to: oauthcallback.html
          – And after fixing and issue with Angujar JS and the routing mechanism I was able to make it work.

          Thanks!

  • This plugin works really good. Thank you for your work and this amazing website here!

  • Great Tutorial! I am building a PhoneGap app. What URL should I use for the Valid OAuth redirect URI?

    I guesse there is no http://localhost/openfb/index.html and I don’t know what adress my app will have.

  • Rodrigo

    Hello,

    My app is running in phonegap, but got error: “URI must be absolut”

    The var oauthRedirectURL is set as ‘file:///android.asset/outhcallback.html’.

    How can i fix this error?

    My source is in github – https://github.com/rlacerda83/Teste-Face

    Thks!

    • Peter

      Hi Rodrigo, did you figure this out?! Thanks.

  • Just wanted to say thanks for putting this together and open-sourcing it. I was able to use it pretty easily in an angular/cordova project I’m building. Very cool deal to not have to use the facebook plugin and have to debug in the emulators. Cheers,

  • Pingback: Sociogram: A Pattern Software demonstrating AngularJS/Ionic and Fb Integration | PakUltimate()

  • Anand

    The code works fine in mobile browser as well as system browser. But Inside the app after fb login credentials are entered, gives a white screen and in my console the following errors comes up. Can you please solve this?

    Uncaught TypeError: Cannot call method ‘oauthCallback’ of undefined at http://mysite.in/feroz/OpenFB-master/oauthcallback.html?#access_token=GTSD23&expires_in=516:4

  • harley

    hey dude why don’t you rewrite the article with a step by step tutorial with pictures ?
    it is hard to follow and we must struggle with the comments to get something working properly.

    thank you for sharing by the way.

  • jouni

    Hello

    your logout doesnt work correctely

    il still connect to application(even if token has undeifined value) if i already connected to my facebook page

  • Azura

    Hi, have anyone tested this plugin on IntelXDK?
    I keep getting the “Given URL is not allowed….” error.
    I tried one of the solutions provided by the people here but it still does not work!

  • Thanks for sharing.

    After fb loging I get this error:

    Facebook login succeeded menuCtrl.js:78
    exit and remove listeners openfb.js:115
    Error in error callback: InAppBrowser457255868 = ReferenceError: deferredLogin is not defined

    Anyone seen that before? Nothing in Google!

  • Marcella

    So far this is working great, thank you for this!

    However, I’m running into an issue where the webkit-playsinline setting on my videos in my app no longer work after the loginwindow.close() function is called. It works fine without Facebook login but the minute I leave the app using openFb and come back it’s broken (videos are playing in native fullscreen player). Any thoughts?

    Thanks!

    • Marcella

      Nevermind, I edited your window.open function call to include ‘allowinlinemediaplayback=YES’ in the options parameter.

  • Usman

    Hello,
    first of all, Thanks a lot for this superb tutorial.

    I have a question about Facebook APP

    how did you configure your Facebook APP (Sociogram) to get information?? i have created my Facebook APP but after login it goes to success page and give an error..

    Thanks,

    • Azura

      Make sure you have InApp Browser as a plugin, have the oauthcallback in the root directory

      • Usman

        Thanks for the reply.. i was talking about something else.. but i have resolved that issue…

        anyone fixed the logout issue?

  • thanks for the plugin works great :)

  • Mogens Enevoldsen

    After facebook login I get the following error:
    ReferenceError: Can’t find variable: deferredLogin

  • Agustin

    For all of those receiving a “Success” white screen… my problem was that I was using Ionic Framework and apparently the lines

    document.addEventListener(“deviceready”, function () {
    runningInCordova = true;
    }, false);

    were never triggered. My hardcoded solution was to set by default the deviceready variable to true. I imagine there must be a nicer solution but I don t have time for it….

    Regards!

  • Raja Husnan

    thanks its work, thanks for OpenFB is a micro-library that lets you integrate your JavaScript application with Facebook

    i implemented in my android apps,… thats work!!!!
    for based what i implemented:
    1.in facebook developer Valid OAuth redirect URIs just fill =https://www.facebook.com/connect/login_success.html

    2.dont forget to add plugin for inappbrowser if u use this OpenFB for apps android(“in my case”)

    3.just use default openfb.js no need to change any script..

    4.dont forget the openFB.init({appId: ‘xxx’});

    NB: just try login() and getinfo() its work!!!

    thanks for sharing this………… in open source!!!!

  • Rob

    After being plagued by this issue for a couple of days, I found a solution to my “Given URL is not allowed….” error: remove all platforms from your Facebook app configuration.

    What do you enter for your site URL? Nothing, because when you create a new Facebook app that component is not added. If it is there, Facebook will enforce that requests come from the specified URL.

    Thanks for the library Christophe!

    I hope this saves someone else some time…

  • Still getting that

    Success
    SECURITY WARNING: Please treat the URL above as you would your password and do not share it with anyone.

    How come?

  • @all

    to close the inappbrowser – “ref.close();”

    implement something like this

    var ref = window.open(‘http://apache.org’, ‘_blank’, ‘location=yes’);
    // close InAppBrowser after 5 seconds

    setTimeout(function() {

    ref.close();

    }, 5000);

    • Yoni

      Can you be more specific?

      The line in openfb.js is:
      loginWindow = window.open(FB_LOGIN_URL + ‘?client_id=’ + fbAppId + ‘&redirect_uri=’ + oauthRedirectURL +
      ‘&response_type=token&scope=’ + scope, ‘_blank’, ‘location=no’);

      where oauthRedirectURL is the facebook success page.
      How can I identify that the success page was called and close the page (to get back to the app)?

      It is very frustrating that I’m getting the “Success” message but can’t get back to the app.

      I think it will also be a good idea to collect the 2-3 problems that are discussed here and add them to the post as update, it will save new-comers a lot of time.

  • @all

    to close the inappbrowser – “ref.close();”
    reference – http://docs.phonegap.com/en/edge/cordova_inappbrowser_inappbrowser.md.html#close
    implement something like this

    var ref = window.open(‘http://apache.org’, ‘_blank’, ‘location=yes’);
    // close InAppBrowser after 5 seconds

    setTimeout(function() {

    ref.close();

    }, 5000);

  • Alberto

    Hi, I already make it work but I see that this code is for friends list
    openFB.api({path: ‘/me/friends’, success: successHandler, error: errorHandler});

    But how can i display them or share something with a friend

    Thanks

  • sayak

    hi, login and get info working well. but when i post something it appeared on my own timeline on facebook but noone can’t view it though it shared publicly. what are the permissions required in facebook app setting? does anybody know what is the problem??

    thanks

  • Everythings Works Perfect!
    Thanks You!

  • oby

    i need a solution… i integrate your plugin with ionic && cordova for multi devices app ;-)

    first : thank a lot for plugin.. it’s work a charm with ionic serve and good auth option in fb app settings..

    BUT : with ionic run android (key hash android generated and integrated) not functionnaly !!!

    error is :

    the redirect uri url must be absolute
    or error connection refused (tested with wifi with good ip auth for fb app)..

    i’ve no solution… i test param app ionic with $httpProvider.defaults.useXDomain = true;
    or others… ned help for only connect facebook (my server api work fine)

    thanx..

  • Gaston

    Hi cristopher, i need to show wall posts from facebook page. Only show. Can i do that?

  • Chaitanya Khurana

    Thanks for sharing such a beautiful code! It works like charm. The only issue is that the console displays an error message:

    “deferredlogin is not defined”

  • Meganathan

    Hi,

    This is Meganathan. When i test this script in web, its working fine. But if i test in phonegap/ios returns the below error:

    SECURITY WARNING: Please treat the URL above as you would your password and do not share it with anyone. See the Facebook Help Center for more information.

    Anyone, please help me.

    Thanks and Regards,
    Meganathan P

  • anonymous

    This may sound like an stupid question sorry, when creating the facebook app, I get different choices, iOS, Android, Website, what do I choose? thanks a lot.

  • sonya

    quick question, i can login well in ionic and post to the wall also, the only problem I am having is the logout feature.

    Logout

    .controller…

    $scope.fbLogout = function () {
    openFB.logout(
    function () {
    alert(‘Logout successful’);
    },
    errorHandler);
    function errorHandler(error) {
    alert(error.message);
    }
    }

    when I click on Logout I go redirected to my FB main page (wall) for a second and then back to my app page. the second time I click on logout, i will see the logout successful alert on my app page and that’s all. I am still however logged into FB. What I don’t have anymore is the token. So basically the logout erase the token BUT still keeps me logged into FB. I saw that in the openFB.js there is a line that says:

    * Logout from Facebook, and remove the token.
    * IMPORTANT: For the Facebook logout to work, the logoutRedirectURL must be on the domain specified in “Site URL” in your Facebook App Settings

    The problem here is that I did not add any platform to be used because I am running the app in ionic framework and I do not need an specific platform. Therefore, I don’t have a Site URL to fill in. Besides, if I would for example add a WEBSITE Platform and then see a Site URL field, I wouldn’t be able to add a URL because I don’t have any.

    Anyone have any thoughts on this? thanks a lot, GREAT CODE, two thumbs up!

  • HeartyBank

    For anybody who still have problems related to “Redirect_uri URL must be absolute on Cordova. I just solved it successfully and tested many times until i’m sure how to solve it. Here are what you need to do to make it works. (on Android only!)

    1. in the tag, arrange the script tags like this

    No matters how many js files you want to add. Just list 3 above files as first set.

    2. Make sure you installed in app browser plugin properly.

    3. You don’t need to change anything in openfb.js file.

    4. And you also don’t need to specify Redirect URL in FB’s App Setting page. Just leave it blank.

    5. Use the sample code you download from OpenFB’s github (latest version). It works perfectly.

    6. In the FB’s App Setting Page… I set these things as “yes” , you can try set these same as me. maybe it can work even thought you don’t do the same.

    Advanced Tab
    – Native or desktop app
    – Is your App Secret embedded
    – Client OAuth Login
    – Embedded browser OAuth Login

    Basic Tab
    – Add Android Platform with Single Sign on
    – Add Website URL

    After doing all above things, I make it works without any problems. Just try do the same things as mine. Hopefully this will help everybody. Cheers!

  • ashdiuhasiurgais

    people having trouble with white or blank screen is because they copied and pasted the code but haven’t declared the variable errorHandler

  • Hi there, there is a way to redirect to another page when the login is complete? mi client needs only validate the account of the user and after that just send it to the main page of the site…..

  • Hi there… there is a way to redirect to a page in the same site when user has done login? i need to know if that is possible using this plugin

  • junaidy

    how to solve this:
    alert (#200) requires extended permission: read_stream
    after login in sociogram

  • raza2022

    first time used in my app and working superb. Thanks Man
    more one thing, is similar module for google+ sign in

    • Niketa

      Did you find anything for Google + ?

  • Sir,

    Let me know, How can i come back to my app index page after login success?. Right now this goes to /login-success.php . PLZ help me

  • Martin

    Hello Coen,

    I’m using the above script and it is working great! One thing that is not working, is when i log out and want to login again. Nothing is happening when i click my login button.

    Have you got any idea what could be wrong?

    Regards,
    Martin

  • Hi Christophe

    This is the best solution I’ve come across so far. Thanks for putting your time and sharing with the community.

    I have done exactly as you have stated in the readme and everything worked.

    If anyone is struggling with this, I can help out as I have it working in Cordova (using Telerik AppBuilder and Cordova 3.x)

    Thanks

  • thank you so much awesome work. It really helped me more than expected.!! Thank you!!!!!!

  • necoide

    Excellent work!

  • Franck

    when i try to log in with my browser i get this message

    can’t reliably infer the OAuth redirect URI.please specify it explicitly in OpenFB.init()

  • nettii

    Hi, I have a problem after succes login. I can see a screen that show this:

    SECURITY WARNING: Please treat the URL above as you would your password and do not share it with anyone.

    and can’t get back to my app from it.

    anyone help me please?

    Thanks in advance

  • Great work !!

    Thanks you.

  • Hi,

    I’m also facing a same problem after successful login and showing the screen containing following message.

    SECURITY WARNING: Please treat the URL above as you would your password and do not share it with anyone.

    No unable to go back to my app from it.

    I show many of them having same issue, can anyone let me know how to resolve it?

    Thanks!

  • Pingback: Can Facebook JS SDK work with Phonegap / Cordova? | Some Cordova Questions and Answers()

  • Vijaya

    Followed all the steps for fb logn but unable to login using mobile device. It throws error : not logged in, Try logging in.

    I am unable to run this in my browser to check if it works too

  • chris

    Hi, is the FB plugin work with Cordava version 3.5.1 above, I understand that it can’t ? Anyone can help as my application was build under the old pre 3.5.1 version which has vulnerabilities

  • Avi

    Thank you very much.
    Helped me a lot.

  • I am working in development. I don’t have any hosted website url.
    I am creating a phonegap application where login with facebook to be used.
    So what should be my oauth success uri URL?

  • Pingback: Mobile Web Weekly No.2 | ENUE Blog()

  • hello coenraets, i have an problem while calling the logout function in ionic. it opens the home.php window when i called. i think the facebook api are not understanding the url those are created inside the window.open function inside the open.js file. can you help me to get rid from it.?

  • Hi iam using this its working but iam stucking at getting frinedslist
    i tried this openFB.api({path: ‘/me/friends’, success: successHandler, error: errorHandler});

    it showing response as empty {“data”:[]}

    how to solve this

  • Hi how to get friends list?

    iam triend your code but getting empty data

  • aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

  • Tolik

    Hi
    It looks like there an error when I try to test your login app from the link you gave in the tutorial I redirect to Facebook login page log in and than nothing happened I stay at Facebook login page and I see a clear white page

    I’m using my smartphone by the way any idea?

  • quality, reliable, cost-effectiveness and the associated jobs are done imalattan.rofesyonek team.http://jonsunsport.com/futbol-takim-formalari.html

  • Fabrics we use in our form; The first-class micro-interlock; flex-fit, anti-bacterial, it has a thermo-balance, and immediately drying. This gives you the freedom to move your soccer jerseys of the match; It is designed stylish enough to be worn on a daily basis. Our models are produced in two types as my special jerseys and other digital printed.
      His highest production of our company, we use the sport socks products: cotton, cotton, polyester, nylon and lycra. It includes anti-bacterial.

  • oho oho very nice to blog admin baba en

  • hoojianliang

    HI, I am developing mobile apps. Since mobile have facebook app and broswer, I would like to ask is this API are able to connect to my fb account from facebook apps but not from the broswer?

  • idan

    Hello ,
    I’m having cordova app that works on android with openFb ,yesterday I deployed this app to iPhonea 4s , the openFb works and facebook login appears but redirect me to “Success” … “Security warning ….” page instead to my app (as in the android).

    any idea what is the problem ?

    • itsme me

      hii did u solved this problem? im also getting same problem android working fine but iphone getting problem same as like u

  • This is an awesome tutorial so far I have seen on this topic. Great Job!

    I would love to have something similar for paypal integration for phonegap build too. I have literally tried everything but I am unable to integrate paypal with my phonegap+jquerymobile app.

    Thank You.

  • Ole

    Hi

    I have successfully used OpenFB in my Phonegap app, but after upgrading to iOS 9.2.1, I only got an empty window with black bar in the buttom, where I can click on “Done”.

    Log says:
    webView:didFailLoadWithError – 102: Frame load interrupted

    I’m I the only one seeing this problem? I got an iPad with iOS 9.2 where it works like charm.

    Any help appreciated.

    Thanks

    Ole

  • Ankit

    This facebook integration is taking local regional langualge, how will i set it default to english.

  • John Troxel

    We are using a very similar approach. Only Facebook is so far rejecting our app in the review: “Your app cannot embed the Facebook Login dialog inside a custom web view. Utilize our native Facebook Login SDK, so that users do not need to login twice.” We’re trying to get to the bottom of what they mean.

    Has anyone else gone through the approval process with a no-plugin approach?

    – John

  • Niketa

    Hi,

    Do you know any such package which can give similar functionality for Google +

  • Hitesh Maniya

    Hi
    I have check in website and it’s working but when i check with cordova app it’s giving error “Domain of this url is not allowed in your app domains

  • Rig Nortana

    Phonegap ios /android:
    when i try to click on login button its display this error :
    Can’t Load URL: The domain of this URL isn’t included in the app’s domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.

  • Quintin De Bruyn

    I cannot thank you enough, been sitting on this for 3 days, any other method failed. This one is great !!!! A quick question, I’m using this on Phonegap . how can I prevent user having to enter credentials manually when logging in, can’t I just have the details pulled from the native facebook app ?

css.php