Cordova plugin that handles Facebook integration for mobile (iOS and Android) apps.
Project uses mobile native platform FacebookSDK for iOS and Android to utilize basic operations for a mobile app that uses Cordova.
We also provide TypeScript source and type definition files together with the JavaScript for the client side with this plugin.
Sample app is built and tested with Cordova 3.6.3 (Android and iOS) and we only support Cordova version > 3.0.
We currently tested FacebookSDK for following platforms and versions:
Download the latest FacebookSDK, and follow the getting started guideline.
The guideline is well documented and people at Facebook may change stuff in the future, so we stick to that instead of fancy cordova plugin hacks (well, cordova people also modify plugin flow too).
Unlike iOS, Android getting started guideline is pretty long and scary. For Android we rely on Android Simple Facebook by Roman Kushnarenko, many thanks for that project. We distribute the compiled version (2.2) of the library with the plugin, so you don't have to worry about anything.
Here is what to do for Android before installing our plugin.
-
Clone Facebook SDK 3.18.0 or download it. Then, import the project to your workspace.
-
Add reference from your project to
FacebookSDK
project.
To add this plugin just type:
cordova plugin add https://github.com/ccsoft/cordova-facebook
To remove this plugin type:
cordova plugin remove com.ccsoft.plugin.CordovaFacebook
Replace the openURL method in your AppDelegate.m (if already exists, add it otherwise) with the following code block
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation
{
if (!url) {
return NO;
}
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
url, @"url", sourceApplication, @"sourceApplication", @"NO", @"success", nil];
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"CordovaPluginOpenURLNotification" object:self userInfo:dict]];
NSString* success = [dict objectForKey:@"success"];
if([success isEqualToString:@"NO"]) {
// calls into javascript global function 'handleOpenURL'
NSString* jsString = [NSString stringWithFormat:@"handleOpenURL(\"%@\");", url];
[self.viewController.webView stringByEvaluatingJavaScriptFromString:jsString];
// all plugins will get the notification, and their handlers will be called
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]];
return YES;
}
return ![success isEqualToString:@"NO"];
}
Then, in your js file (probably in index.js)
// Get a reference to the plugin first
var plugin = new CC.CordovaFacebook();
The plugin has the following methods:
Initializes the plugin. Must be called before calling any other function.
####parameters
appId: string: Your FB app id.
appName: string: Your FB app name.
appPermissions: array: Your FB app permissions as an array of strings.
successCallback: function: If not already logged in, we return an empty string. If already logged in to FB we return JSONObject for "accessToken", "expirationDate" and "permissions". Expiration date is a timestamp value. Permissions are retruned as JSONArray.
failureCallback: function: Called with failure reason string.
####example
plugin.init('YOUR_FB_APP_ID', 'YOUR_FB_APP_NAME',
['public_profile', 'email', 'publish_actions'],
function(response) {
if(response) {
console.log("Access token is: " + response.accessToken);
console.log("Expires: " + response.expirationDate);
console.log("Permissions are: " + response.permissions);
}
}), failureCallback);
####parameters
successCallback: function: Called with a JSONObject for "accessToken", "expirationDate" and "permissions". Expiration date is a timestamp value. Permissions are retruned as JSONArray.
failureCallback: function: Called with failure reason string.
####example
plugin.login(function(response) {
console.log("Access token is: " + response.accessToken);
console.log("Expires: " + response.expirationDate);
console.log("Permissions are: " + response.permissions);
}), failureCallback);
####parameters
successCallback: function: Called with no params.
####example
plugin.logout(successCallback);
Retrieves user info. See FBGraphUser documentation for successCallback parameter in iOS. See the example below for Android. (They must be equiavelent, let us know if there are differences.)
####parameters
successCallback: function: Called with user info data
failureCallback: function: Called with failure reason string.
####example
plugin.info(function(data) {
console.log("User Id: " + data.id);
console.log("Name: " + data.name);
console.log("Email: " + data.email); // if asked for it in permissions
console.log("First Name: " + data.first_name);
console.log("Last Name: " + data.last_name);
console.log("Link: " + data.link);
console.log("Locale: " + data.locale);
},
function(err) {console.log(err););
- iOS: share call tries to open share dialog via official Facebook app. If Facebook app is not installed on device, we fallback to feed call.
- Android: share behaves exactly the same as feed.
####parameters
name: string
url: string
logoUrl: string
caption: string
description: string
successCallback: function: post_id (on iOS, if Facebook app is installed and used for share, pass no parameters to callback on success)
failureCallback: function: Called with failure reason string.
####example
plugin.share('Name', 'http://www.example.com', 'http://www.example.com/test.png',
'Test caption', 'Test description.', successCallback, failureCallback);
feed call requires an active session. Shows facebook web dialog as a popup on iOS and uses open graph on Android. On Android, we will support dialog whem Simple Facebook library supports it.
####parameters
name: string
url: string
logoUrl: string
caption: string
description: string
successCallback: function: post_id (on iOS, if Facebook app is installed and used for share, pass no parameters to callback on success)
failureCallback: function: Called with failure reason string.
####example
plugin.feed('Name', 'http://www.example.com', 'http://www.example.com/test.png',
'Test caption', 'Test description.', successCallback, failureCallback);
invite call requires an active session. Shows facebook invite dialog and returns the invitation response.
####parameters
message: string: Mesage to be shown with the invitation (to friend).
title: string: Title to be shown with the invitation (to friend).
successCallback: function: Returns invitation id and the fb id of people the invitation has been sent.
failureCallback: function: Called with failure reason string.
####example
plugin.invite('Invitation message better be inviting', 'Invitation Title', successCallback, failureCallback);
For implementation details:
When sending requests to friends in Facebook, you are also responsible to delete these requests, once the invitee responds. The procedure is explained in Facebook SDK documentation here.
####parameters
request: string: Request to delete, note that it should be of the form: "requestid_fbuserid", you MUST concatenate these two manually on your js side!
successCallback: function: returns nothing.
failureCallback: function: Called with failure reason string.
####example
plugin.deleteRequest(requestId + '_' + fbuserId, successCallback, failureCallback);
For implementation details:
- Facebook documentation on deleting requests here
- Facebook documentation on requests with Graph API here (scroll to deleting)
- See Android (Simple Facebook) implementation details here
Post score for the user. Note that your app should be classified as a game in Facebook app settings.
####parameters
score: number: integer score value.
successCallback: function: returns nothing.
failureCallback: function: Called with failure reason string.
####example
plugin.postScore(score, successCallback, failureCallback);
For implementation details:
- Facebook documentation on Scores API here
Gets the score for the user and his/her friends. Note that your app should be classified as a game in Facebook app settings.
####parameters
scores: []: json array of scores, each object in array contains score and user as follows:
score: number; // best score of that user
user.id: string; // user id
user.name: string; // user name
successCallback: function: returns nothing.
failureCallback: function: Called with failure reason string.
####example
plugin.getScores(function(resp) {
for (var i = 0; i < resp.length; i++) {
console.log("Score Order: " + i);
console.log("User Id: " + resp[i].user.id);
console.log("User Name: " + resp[i].user.name);
console.log("Score: " + resp[i].score);
}
}, failureCallback);
For implementation details:
- Facebook documentation on Scores API here
Makes a call to graph API using FB SDK.
####parameters
node: string: The graph path
params: JSON Object; // params to be passed, eg: to get the name of a friend {"fields": "name"}
method: string; // one of "GET", "POST", "DELETE"
successCallback: function: returns result if any.
failureCallback: function: Called with failure reason string.
####example
plugin.graphCall("me", {"fields": "name,id"}, "GET", function(resp) {
console.log("My name is: " + resp.name + " and id is: " + resp.id);
}
}, failureCallback);
For implementation details:
- Facebook documentation on Scores API here
We have a sample cordova app to test the plugin that you can find here. Please note that the link takes you to a dedicated branch named facebook, please use that branch to test this plugin. We use separate branches for each plugin we implement.
Once you download/clone and run the app, you are going to be using a sample Facebook app in sandbox. You can change your app settings (in index.html), you can also test the features with the following Facebook tester user credentials:
Pass: 123456
- Why do we implement another plugin since there is already an official phonegap-facebook-plugin?
- As of today (16.01.2014), official cordova facebook plugin project on GitHub has 985 stars (including mine), 118 watchers, 218 open issues, 29 pull requests and 5 branches.
- Last commit as of today to master branch was 3 months ago, we don't have time to wait for fixes and new updates.
- Official plugin tries to retain the same interface for the Facebook JavaScript SDK, which we believe an unnecessary burden.
- We have some live apps that uses the official plugin, and we are scared to update our app to new Cordova version, scared to break things in Facebook side.
- Well, it was not that hard to do it, so we did it.