Git Product home page Git Product logo

openfb's Introduction

OpenFB

OpenFB is a Micro-Library for Facebook integration in JavaScript apps running in the browser and in Cordova.

OpenFB has no dependency: You don't need the Facebook plugin when running in Cordova. You also don't need the Facebook SDK.

OpenFB allows you to login to Facebook and execute any Facebook Graph API request.

Here are a few code examples...

Login using Facebook:

openFB.login(callback, {scope: 'email,read_stream,publish_actions'});

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 Facebook 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".

Getting Started

Creating a Facebook application

  1. Login to Facebook

  2. Access https://developers.facebook.com/apps, and click Add New App

  3. Select www as the platform

  4. Type a unique name for your app and click Create New Facebook App ID

  5. Specify a Category, and click Create App ID

  6. Click My Apps in the menu and select the app you just created

  7. Click Settings in the left navigation

  8. Click the Advanced Tab

  9. In the OAuth Settings section, add the following URLs in the Valid OAuth redirect URIs field:

  10. Click Save Changes

Running the Sample in the Browser

  1. Copy the Facebook App ID for the app you just created and paste it as the first argument of the openFB.init() method invocation in index.html.
  2. Load index.html, from a location that matches the redirect URI you defined above. For example: http://localhost:8100

Running the Sample in Cordova

  1. Create a Cordova project

    cordova create sample com.openfb.sample sample
    
  2. Add the InAppBrowser Plugin

    cd sample
    cordova plugins add org.apache.cordova.inappbrowser
    
  3. Delete the contents of the www directory

  4. Copy index.html and openfb.js from the OpenFB project to the www directory of your Cordova project

    Make sure your index.html includes <script src="cordova.js"></script>. cordova.js does not need to (and shouldn't be) present in your www folder: it is automatically injected by the cordova build process.

  5. Make sure you are in your Cordova project's root directory, add a platform, and build the project. For example:

    cordova platform add ios
    cordova build ios
    
  6. Run the project on device or in the emulator

AngularJS Wrapper

If you are using AngularJS, you can use ngOpenFB which provides a wrapper around the OpenFB library and allows you to use OpenFB "the Angular way":

  • As an Angular service instead of a global object
  • Using promises instead of callbacks

indexng.html provides an AngularJS sample.

Check out the Ionic Tutorial for a complete example.

Summary

The Facebook Plugin is still the best technical solution to integrate your Cordova app with Facebook because it provides a tighter integration (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.

openfb's People

Contributors

000panther avatar ccoenraets avatar ratt avatar superandrew avatar vielhuber avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

openfb's Issues

Web Login doesnt get any auth token or response from facebook

Hi Sir,
i am using OpenFB library to login in facebook from an ionic mobile app and also mobile website.
when i login using mobile app it works perfect.
but when i login from mobile website it doenst go in .then function

OpenFB.login('email,read_stream,publish_stream').then(
function () {
alert('logged in facebook'); //this doesnt work
},
function () {
alert('OpenFB login failed');
});

Thanks and Regards,
Supreet Sethi

deferredLogin not defined

deferredLogin is in loginWindow_exitHandler() which is undefined and prevents window.open to be called twice.

How to remove session from app

Hi,
I have used your code and it's working fine. but when i logout from my app and again login it's not asking for userid and password. It's show successfull login message and redirect to next screen.
Could you, let me know how to remove access_token from session?

Thanks,

Bower support

This is awesome, thanks for this. Can you add support for Bower?

LIKE button

Any chance for an API for Like?

The HTML "Like" button doesn't play well in Cordova.

Phonegap: Login problem

Hi! I have a problem with login and i am not able to resolve it. I have followed every step and i have inserted "https://www.facebook.com/connect/login_success.html"; after insert user data on Facebook Login, appears an error and, after click on "OK" button, the phone shows a white page with "success" label and "SECURITY WARNING: Please treat the URL above as you would your password".

Login Problem

i had this white page/screen with success text and some security warning. How to remove it and back to the main page?

Posting Photos using openFB,api

Hi,

How can i get publish_actions (extended permissions) in openFB api. While trying your sample app (http://coenraets.org/apps/openfb/index.html) the share is also not working.
test 1

I tested in cordova too but it's also showing the similar error for share...!

test 2

My application needs to post photos in users wall. How can i do it. Please kindly help me to resolve this issue..!

Login not working with Windows Phone 8 and Cordova

When the app tries to login, the appInView shows me that I'm entering a non-secure site, and asks me to continue. I agree, but the alert appears again.

The official FB plugin for Phonegap is not available on WP, and the JS Facebook API seems to not work neither, and this is the only module I've got that seems to work.

Security Warning, not redirecting...

Hi, I know many people had already posted this issue, and I tried those solutions.
It worked very well on browser and emulate. but it stocked me for days that I can't use it on my ios device.
still seeing this after login and not redirecting to any page.. : (

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

my Valid OAuth redirect URIs are as instruction
(http://localhost:8100/oauthcallback.html,https://www.facebook.com/connect/login_success.html)

, and my plugins version as below.

0.11.0 "Facebook Connect"
1.0.0 "InAppBrowser"
1.0.0 "Whitelist"

I saw someone end up with order problem, so add it here if necessary.

<script src="lib/ionic/js/ionic.bundle.js"></script> <script src="lib/ngCordova/dist/ng-cordova.js"></script> <script src="cordova.js"></script> <script src="js/openfb.js"></script> <script src="js/ngopenfb.js"></script> <script src="js/app.js"></script>

...

and I'm using the "Ionic View App" to test my App. ( Will that be a problem? )

Any advice would be really appreciate, thanks all in advance.

Android not working

connect-error

This happens on both android emulator and on device.

I have http://localhost set as a "Valid OAuth redirect URIs" and I've forced the baseURL in openfb.js to be http://localhost as the file:///android_assets or whatever isn't valid and I cant get anything to work.

This all works fine on desktop. Any help?

Cannot detect device ready. And thus runningInCordova does not get set.

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

This did not work in my cordova app. I had to manually set
openFB.runningInCordova = true;

I think the reason is I imported OpenFB.js in the header instead of end of the body and I probably need to first listen to document ready and then add the listener to device ready.

Android not working

This library does not work for Android? When I press the login button on the android facebook page opens and after I login, the success page does not close. Anyone have any idea what it might be? Note: In iOS works perfectly.

Blank Screen

Hi, Iºm having an issue I´m not quite sure how to solve it. First. I´m creating a PhoneGap APP so wich should be my oauth url since the user will have an APP and not a website APP.

After I click login I get a blank screen. No errors just a blank screen ( inApp and Web ). I don't know how to solve this.

Cheers,
DAniel SOusa

Method to refresh token

Hi, in my scenario I need to keep a token valid because I have to send it to the app backend. I am not able to understand how can I make a silent call to facebook to have renewed the user access token withou calling openFB.login() which prompts the user to reenter credentials.

Any idea?

Two enhancements

Hi Conrad,
This is truly an awesome library that is easy to integrate into ionic.

Here are two enhancements I had to make, which you may choose to fold into the library:

  1. set FB API version, as v2.0 does not allow friends etc. and
  2. enable a caching parameter (important, if you e.g. uses the /photo part of opengraph)
// Insert in globals
        // Which version of FP API to use v1.0 or v2.0
            APIversion = "v1.0",

// Change api to use APIversion and to have an optional cache parameter defaulting to false

        function api(obj) {

            var method = obj.method || 'GET',
                params = obj.params || {};
            var cache = (typeof params['cache'] !== 'undefined')?params['cache']:false;

            params['access_token'] = tokenStore['fbtoken'];


            return $http({method: method, cache: cache,
                url: 'https://graph.facebook.com/' + APIversion + obj.path, params: params})
                .error(function(data, status, headers, config) {
                    if (data.error && data.error.type === 'OAuthException') {
                        $rootScope.$emit('OAuthException');
                    }
                });
        }

An enhancement request is for the login function to detect whether or not to show the login screen based on the validity of the stored token - is that possible ?

Best Regards

./psimonsdk

Facebook logout on device not working

I cannot get Facebook logout to work on device properly (it clears session and everything just fine but doesn't actually log the user out of Facebook, eg: so they can log in as a different Facebook user).

Per the note in openfb.js "* IMPORTANT: For the Facebook logout to work, the logoutRedirectURL must be on the domain specified in "Site URL" in your Facebook App Settings", I have my Facebook domain settings points to the proper localhost so that logout works correct when testing locally, but I don't know how to handle this on my device.

When I try to view what the baseURL would be on device I just get "file:///private", which Facebook won't accept as a valid site URL for me to test with.

How can I perform a successful Facebook logout from device?

The redirect_uri URL must be absolute

Hello,
I am getting a facebook popup with the error : "The redirect_uri URL must be absolute" when testing my app on desktop. It works just fine when testing on mobile.
Here is the the request string it produces on desktop:
https://www.facebook.com/dialog/oauth?client_id=MY_APP_ID&redirect_uri=file:///D:/oauthcallback.html&response_type=token&scope=email,public_profile

redirect_uri seems to be incorrect but the error remains even if I modify it to contain the correct path

Thanks,
Max

Done window on Login to Facebook

Hello all,

When I click on Login to facebook button, I get the done window in my ios as well as android device.
this window does not close automatically.

Please do the needful.

How to correctly return the user to a new state in the Emulator?

I'm trying to use OpenFB in my Ionic app, and in the browser it now works fine with the following login controller:

 .controller('LoginCtrl', function($scope, $state){
        $scope.fbLogin = function(){
            openFB.login(
                function(response){
                    if (response.status == 'connected'){
                        console.log('Facebook login succeeded. YEAH!!!');
                        $state.go('tab.chats');
                    } else {
                        console.log('The FB login failed.');
                    }
                },
                {scope: 'email, publish_actions'}
            );
        }
    })

The problem is that when I try this in the emulator, I get redirected to the FB view and I can login, but after that view I get a screen giving me a safety warning which says (translated from Dutch) something like this:

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.

I don't get this warning in the browser though. Does anybody know why this is and how I can solve it? All tips are welcome!

After Login

Hi

It was works fine before and now its not working . Still I got this error " sorry this feature isn't available right now an error occurred while processing this request.please try again later "

I using cordova 3.4

please help me

What is the license of this library?

Hi,

I found no license information in this repo. I would like to change this into an Instagram library for Cordova but without knowing which license this has, I don't want to start.

Can you clarify the license?

New problem after adding clearcache=yes

I had that problem which the app would not logout. I followed the instructions to add " clearcache=yes" to the end of ther URL, described here (#10). It worked (IN PART). It's already logging out when I click the button to do so, but the problem is that it's also logging out when it's not supposed to. It should keep me logged in if I kill the app and reopen it but the app is asking for my FB credentials again. (I'm not explicitly clicking the logout button)
How can this be fixed?? Thanks.

Not able to logout

I'm having troubles with logging out using openFB. Facebook does not redirect to my logoutcallback, but to https://www.facebook.com/home.php. Accoording to the information I read, this may be caused either by

  1. incorrect token,
  2. incorrect next

When logging out in Cordova, the "next" parameter in de logout url is set to "file:///var/logoutcallback.html". When I add this URL to the "Valid OAuth redirect URIs" in the Facebook app settings, but Facebook complains that it is not a valid URL. And, if I open "file:///var/logoutcallback.html" in InAppBrowser manually, it can't find the file.

When I set it to "logoutcallback.html", without file:/// it does open in InAppBrowser. I also could add it to the "Valid OAuth redirect URIs". But still, logout doesn't work. Facebook does not redirect to my logoutcallback, but to https://www.facebook.com/home.php. And logout didn't work.

Is logging out currently not working in openFB.js? Or what am I doing wrong?

Window not closing at first login

I'm using openfb.js in my Steroids Appgyver project. On iOS it's working fine, but on Android I'm running into a small issue.
When I'm testing the app for the first time and I click on the FB login button it takes me to the login form. Then when I enter my email and password I see my callback page. The window is not closing however.

When I boot the app a second time and I click on the login button I don't need to fill in the form again, the app goes to the callback page and the window closes correctly.

Any ideas on how to fix that the window also closes correctly on the first run?

Security warning

I can get this working in the browser but I keep getting a Security warning in my phonegap app?

I'm sure if I am setting my Facebook app up correctly.

Any help would be must appreciated :)

Logout Problem

Hello,
I use cordova/phonegap, when I logout from facebook, token becomes null, there is no problem here. However, It doesnt ask me facebook password or email when I click the login button again.
So It doesnt allow me login different users.
I think I can logout from app but cannot logout from inapp browser.
How can I solve this problem?

Can't find variable: deferredLogin

Hi, I am using openfb with bower in ionic. I don't understand why I have this error.

5     332137   log      exit and remove listeners
6     332137   log      Error in Success callbackId: InAppBrowser1724574440 : ReferenceError: Can't find variable: deferredLogin

it seems to be a common problem:
https://github.com/ccoenraets/OpenFB/issues?utf8=%E2%9C%93&q=deferredLogin+

I've applied the fix

117 if (loginCallback && !loginProcessed) loginCallback({status: 'user_cancelled'});

from this pullRequest:
https://github.com/soloidx/OpenFB/commit/a4ea90d644fcdc290ed082e9a6c58302168fbe1d
But I'd like to have the correct file pushed with bower instead of manually patching OpenFB. Is there anyone who can accept the pull request?

oauthRedirectURL is not correct with folders two levels deep

When running the script locally with two folder levels e.g.
http://localhost:8888/example-app/www/

The callback url comes out as:
http://localhost:8888/example-app/oauthcallback.html
http://localhost:8888/example-app/logoutcallback.html

This should actually be:
http://localhost:8888/example-app/www/oauthcallback.html
http://localhost:8888/example-app/www/logoutcallback.html

I fixed by changing line 20 from:
context = window.location.pathname.substring(0, window.location.pathname.indexOf("/",2))

to:
context = window.location.pathname.substring(0, window.location.pathname.lastIndexOf("/"))

Problem after login

Hi! I use Intel XDK to develop an hybrid app. When i build the apk, i have noticed that, after login (and getting token) every next request returns error, without specific problem message.

openFB.logout doesnt work on android device

Hello everybody.
I am facing the following problem when I test logout functionality on android device - it logs me in instantly using data from previous session when I am trying to logout and then log in using another profile. It works just fine when I debug it in desktop browser but fails on mobiles. I suspect it doesnt clear all fb cookies and other stuff loaded at the first login.
Any advice will be highly appreciated,
Max

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.