PhoneGap / Cordova Social Sharing plugin
by @EddyVerbruggen, read my blog about this plugin
Every now and then kind folks ask me how they can give me all their money. So if you want to contribute to my pension fund, then please go ahead :)
For a quick demo app and easy code samples, check out the plugin page at the Verified Plugins Marketplace: http://plugins.telerik.com/plugin/socialsharing |
0. Index
- Description
- Screenshots
- Installation
- Usage on iOS and Android
- Web Share API
- Usage on Windows Phone
- Share-popover on iPad
- Whitelisting on iOS 9
1. Description
This plugin allows you to use the native sharing window of your mobile device.
- Works on Android, version 2.3.3 and higher (probably 2.2 as well).
- Works on iOS6 and up.
- Works on Windows Phone 8 since v4.0 of this plugin (maybe even WP7, but I have no such testdevice).
- Share text, a link, a images (or other files like pdf or ics). Subject is also supported, when the receiving app supports it.
- Supports sharing files from the internet, the local filesystem, or from the www folder.
- You can skip the sharing dialog and directly share to Twitter, Facebook, or other apps.
- Compatible with Cordova Plugman.
- Officially supported by PhoneGap Build.
2. Screenshots
iOS 7 (iPhone)
Sharing options are based on what has been setup in the device settings
iOS 7 (iPad) - a popup like this requires a little more effort
iOS 6 (iPhone)
Android
Windows Phone 8
Cordova ActionSheet plugin)
Alternative ShareSheet (iOS only, using the3. Installation
Automatically (CLI / Plugman)
SocialSharing is compatible with Cordova Plugman, compatible with PhoneGap 3.0 CLI, here's how it works with the CLI:
$ phonegap local plugin add https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin.git
or with Cordova CLI, from npm:
$ cordova plugin add cordova-plugin-x-socialsharing
$ cordova prepare
SocialSharing.js is brought in automatically. There is no need to change or add anything in your html.
Manually
1. Add the following xml to all the config.xml
files you can find:
<!-- for iOS -->
<!-- for Android (you will find one in res/xml) -->
<!-- for Windows Phone -->
For sharing remote images (or other files) on Android, the file needs to be stored locally first, so add this permission to AndroidManifest.xml
:
For iOS, you'll need to add the Social.framework
and MessageUI.framework
to your project. Click your project, Build Phases, Link Binary With Libraries, search for and add Social.framework
and MessageUI.framework
.
2. Grab a copy of SocialSharing.js, add it to your project and reference it in index.html
:
3. Download the source files for iOS and/or Android and copy them to your project.
iOS: Copy SocialSharing.h
and SocialSharing.m
to platforms/ios/<ProjectName>/Plugins
Android: Copy SocialSharing.java
to platforms/android/src/nl/xservices/plugins
(create the folders)
Window Phone: Copy SocialSharing.cs
to platforms/wp8/Plugins/nl.x-services.plugins.socialsharing
(create the folders)
PhoneGap Build
Just add the following xml to your config.xml
to always use the latest version of this plugin (which is published to plugins.cordova.io these days):
or to use an older version, hosted at phonegap build:
SocialSharing.js is brought in automatically. Make sure though you include a reference to cordova.js in your index.html's head:
4. Usage on iOS and Android
You can share text, a subject (in case the user selects the email application), (any type and location of) file (like an image), and a link. However, what exactly gets shared, depends on the application the user chooses to complete the action. A few examples:
- Mail: message, subject, file.
- Twitter: message, image (other filetypes are not supported), link (which is automatically shortened if the Twitter client deems it necessary).
- Google+ / Hangouts (Android only): message, subject, link
- Flickr: message, image (an image is required for this option to show up).
- Facebook Android: sharing a message is not possible. You can share either a link or an image (not both), but a description can not be prefilled. See this Facebook issue which they won't solve. As an alternative you can use
shareViaFacebookWithPasteMessageHint
since plugin version 4.3.4. See below for details. Also note that sharing a URL on a non standard domain (like .fail) may not work on Android. Make sure you test this. You can use a link shortener to workaround this issue. - Facebook iOS: message, image (other filetypes are not supported), link. Beware that since a Fb update in April 2015 sharing a prefilled message is no longer possible when the Fb app is installed (like Android), see #344. Alternative: use
shareViaFacebookWithPasteMessageHint
.
Using the share sheet
Since version 5.1.0 (for iOS and Android) it's recommended to use shareWithOptions
as it's the most feature rich way to share stuff cross-platform.
It will also tell you if sharing to an app completed and which app that was (if that app plays nice, that is).
// this is the complete list of currently supported params you can pass to the plugin (all optional)var options = message: 'share this' // not supported on some apps (Facebook, Instagram) subject: 'the subject' // fi. for email files: '' '' // an array of filenames either locally or remotely url: 'https://www.website.com/foo/#bar?a=b' chooserTitle: 'Pick an app' // Android only, you can override the default share sheet title var { console; // On Android apps mostly return false even while it's true console; // On Android result.app is currently empty. On iOS it's empty when sharing is cancelled (result.completed=false)} var { console;} windowpluginssocialsharing;
share
method as well
You can still use the older Here are some examples you can copy-paste to test the various combinations:
message onlymessage and subjectlink onlymessage and linkimage only// Beware: passing a base64 file as 'data:' is not supported on Android 2.x: https://code.google.com/p/android/issues/detail?id=7901#c43// Hint: when sharing a base64 encoded file on Android you can set the filename by passing it as the subject (second param)base64 image only// Hint: you can share multiple files by using an array as thirds param: ['file 1','file 2', ..], but beware of this Android Kitkat Facebook issue: [#164]message and imagemessage, image and linkmessage, subject, image and link
Example: share a PDF file from the local www folder:
Share PDF
Sharing directly to..
<!-- unlike most apps Twitter doesn't like it when you use an array to pass multiple files as the second param -->message via Twittermsg and link via Twitter
msg via Facebook (with errcallback)
Facebook with prefilled message - as a workaround for this Facebook (Android) bug. BEWARE: it's against Facebooks policy to prefil the message, or even hint the user to prefill a message for them. See this page for details.
- On Android the user will see a Toast message with a message you control (default: "If you like you can paste a message from your clipboard").
- On iOS this function used to behave the same as
shareViaFacebook
, but since 4.3.18 a short message is shown prompting the user to paste a message (like Android). This message is not shown in case the Fb app is not installed since the internal iOS Fb share widget still supports prefilling the message. - iOS9 quirk: if you want to use this method, you need to whitelist
fb://
in your .plist file.
msg via Facebook (with errcallback)
Whitelisting Facebook in your app's .plist:
LSApplicationQueriesSchemes fb
msg via Instagram
Quirks:
- Instagram no longer permits prefilling a message - you can prompt the user to paste the message you've passed to the plugin because we're adding it to the clipboard for you.
iOS Quirks:
- Before trying to invoke
shareViaInstagram
please usecanShareVia('instagram'..
AND whitelist the urlscheme (see below). - Although this plugin follows the Instagram sharing guidelines, the user may not only see Instagram in the share sheet, but also other apps that listen to the "Instagram sharing ID". Just google "com.instagram.exclusivegram" and you see what I mean.
- Note that on iOS when sharing an image and text, only the image is shared - let's hope WhatsApp creates a proper iOS extension to fix this.
- Before using this method you may want to use
canShareVia('whatsapp'..
(see below).
msg via WhatsApp (with errcallback)
Experimental feature: sharing directly to someone
Available in 5.0.8 and up - please let me know if this works for your device! Open an issue if not..
msg via WhatsApp for Addressbook ID 101
For receiver
on iOS pass in the Addressbook ID (or 'abid'). You can find those abid's by using the Cordova Contacts Plugin.
The result in the success callback of the find
function is a JSON array of contact objects, use the 'id' you find in those objects.
Don't pass in an image on iOS because that can't be sent to someone directly unfortunately. Message and URL are fine though.
On Android pass in the phone number of the person you want to send a message to (untested at the moment).
SMS
Note that on Android, SMS via Hangouts may not behave correctly
<!-- Want to share a prefilled SMS text? -->share via SMS<!-- Want to prefill some phonenumbers as well? Pass this instead of null. Important notes: For stable usage of shareViaSMS on Android 4.4 and up you require to add at least one phonenumber! Also, on Android make sure you use v4.0.3 or higher of this plugin, otherwise sharing multiple numbers to non-Samsung devices will fail -->share via SMS<!-- Need a subject and even image sharing? It's only supported on iOS for now and falls back to just message sharing on Android -->share via SMS
Code inspired by the EmailComposer plugin, note that this is not supported on the iOS 8 simulator (an alert will be shown if your try to).
windowpluginssocialsharing;
If Facebook, Twitter, Instagram, WhatsApp, SMS or Email is not available, the errorCallback is called with the text 'not available'.
If you feel lucky, you can even try to start any application with the shareVia
function:
<!-- start facebook on iOS (same as `shareViaFacebook`), if Facebook is not installed, the errorcallback will be invoked with message 'not available' -->message via Facebook<!-- start facebook on Android (same as `shareViaFacebook`), if Facebook is not installed, the errorcallback will be invoked with message 'not available' -->message via Facebook<!-- start twitter on iOS (same as `shareViaTwitter`), if Twitter is not installed, the errorcallback will be invoked with message 'not available' -->message and link via Twitter on iOS<!-- if you share to a non existing/supported app, the errorcallback will be invoked with message 'not available' -->message via Bogus App
What can we pass to the shareVia
function?
- iOS: You are limited to 'com.apple.social.[facebook | twitter | sinaweibo | tencentweibo]'. If an app does not exist, the errorcallback is invoked and iOS shows a popup message asking the user to configure the app.
- Android: Anything that would otherwise appear in the sharing dialoge (in case the
share
function was used. Pass a (part of the) packagename of the app you want to share to. TheshareViaFacebook
function for instance usescom.facebook.katana
as the packagename fragment. Things likeweibo
,pinterest
andcom.google.android.apps.plus
(Google+) should work just fine.
You can even test if a sharing option is available with canShareVia
!
You'll need to pass everything you want to share, because (at least on Android) some apps may only become available when an image is added.
The function will invoke the successCallback when it can be shared to via shareVia
, and the errorCallback if not. As a bonus on Android, the errorCallback contains a JSON Array of available packages you can pass to shareVia.
You can even specify the activity if the app offers multiple sharing ways, passing 'packageName/activityName'. (for example, WeChat, passing 'com.tencent.mm' or 'com.tencent.mm/com.tencent.mm.ui.tools.ShareImgUI' to share to chat, passing 'com.tencent.mm/com.tencent.mm.ui.tools.ShareToTimeLineUI' to share to moments).
is WeChat available on Android?is facebook available on iOS?// this one requires whitelisting of whatsapp:// on iOS9 in your .plist fileis WhatsApp available?is SMS available?is Instagram available?<!-- Email is a different beast, so I added a specific method for it -->is Email available?
Want to share images from a local folder (like an image you just selected from the CameraRoll)?
// use a local image from inside the www folder:windowpluginssocialsharing; // success/error callback params may be added as 5th and 6th param// .. or a local image from anywhere else (if permitted):// local-iOS:windowpluginssocialsharing;// local-iOS-alt:windowpluginssocialsharing;// local-Android:windowpluginssocialsharing;// .. or an image from the internet:windowpluginssocialsharing;
If your app still supports iOS5, you'll want to check whether or not the plugin is available as it only supports iOS6 and up.
windowpluginssocialsharing;
If you can't get the plugin to work, have a look at this demo project.
Notes about the successCallback (you can just ignore the callbacks if you like)
Since version 3.8 the plugin passes a boolean to the successCallback to let the app know whether or not content was actually shared, or the share widget was closed by the user. On iOS this works as expected (except for Facebook, in case the app is installed), but on Android some sharing targets may return false, even though sharing succeeded. This is not a limitation of the plugin, it's the target app which doesn't play nice. To make it more confusing, when sharing via SMS on Android, you'll likely always have the successCallback invoked. Thanks Google.
Sharing multiple images (or other files)
Since version 4.3.0 of this plugin you can pass an array of files to the share and shareVia functions.
// sharing multiple images via Facebook (you can mix protocols and file locations)windowpluginssocialsharing; // sharing a PDF and an imagewindowpluginssocialsharing;
Note that a lot of apps support sharing multiple files, but Twitter just doesn't accept more that one file.
Saving images to the photo album (iOS only currently)
Since version 4.3.16 of this plugin you can save an array of images to the camera roll:
windowpluginssocialsharing;
iOS quirk (with camera plugin)
When using this plugin in the callback of the Phonegap camera plugin, wrap the call to share()
in a setTimeout()
.
The share widget has the same limitation as the alert dialogue mentioned in the Phonegap documentation.
Excluding some options from the widget
If you want to exclude (for example) the assign-to-contact and copy-to-pasteboard options, add this to your main plist file:
SocialSharingExcludeActivities com.apple.UIKit.activity.AssignToContact com.apple.UIKit.activity.CopyToPasteboard
Here's the list of available activities you can disable :
- com.apple.UIKit.activity.PostToFacebook
- com.apple.UIKit.activity.PostToTwitter
- com.apple.UIKit.activity.PostToFlickr
- com.apple.UIKit.activity.PostToWeibo
- com.apple.UIKit.activity.PostToVimeo
- com.apple.UIKit.activity.TencentWeibo
- com.apple.UIKit.activity.Message
- com.apple.UIKit.activity.Mail
- com.apple.UIKit.activity.Print
- com.apple.UIKit.activity.CopyToPasteboard
- com.apple.UIKit.activity.AssignToContact
- com.apple.UIKit.activity.SaveToCameraRoll
- com.apple.UIKit.activity.AddToReadingList
- com.apple.UIKit.activity.AirDrop
5. Web Share API
Chrome introduced the Web Share API to share data:
navigator;
It doesn't provide all the options that the other share methods do but it is spec compliant.
6. Usage on Windows Phone
The available methods on WP8 are: available
, canShareViaEmail
, share
, shareViaEmail
and shareViaSMS
.
Currently the first two always return true, but this may change in the future in case I can find a way to truly detect the availability.
The share
function on WP8 supports two flavours: message only, or a combination of message, title and link.
Beware: for now please pass null values for all non used attributes, like in the examples below.
Sharing a message:
message only
Sharing a link:
message, title, link
Sharing an image (only images from the internet are supported). If you pass more than one image as an array, only the first one is used:
image only
7. Share-popover on iPad
Carlos Sola-Llonch, a user of this plugin, pointed me at an iOS document stating "On iPad, you must present the view controller in a popover. On iPhone and iPod touch, you must present it modally."
He also provided me with the required code to do so (thanks!). I've adapted it a little to make sure current behaviour is not altered, but with a little extra effort you can use this new popover feature.
The trick is overriding the function window.plugins.socialsharing.iPadPopupCoordinates
by your own implementation
to tell the iPad where to show the popup exactly. It need to be a string like "100,200,300,300" (left,top,width,height).
You need to override this method after deviceready
has fired.
You have various options, like checking the click event on a button and determine the event.clientX and event.clientY, or use this code Carlos showed me to grab the coordinates of a static button somewhere on your page:
windowpluginssocialsharing { var rect = document; return rectleft + "," + recttop + "," + rectwidth + "," + rectheight;};
Note that since iOS 8 this popup is the only way Apple allows you to share stuff, so this plugin has been adjusted to use this plugin as standard for iOS 8 and positions the popup at the bottom of the screen (seems like a logical default because that's where it previously was as well). You can however override this position in the same way as explained above.
Note: when using the WkWebView polyfill the iPadPopupCoordinates
overrides doesn't work so you can call the alternative setIPadPopupCoordinates
method to define the popup position just before you call the share
method.
example :
var targetRect = eventtargetElement targetBounds = targetRectleft + ',' + targetRecttop + ',' + targetRectwidth + ',' + targetRectheight; windowpluginssocialsharing;windowpluginssocialsharing
8. Whitelisting on iOS 9
On iOS 9 you have to make sure to whitelist the applications you want to use for sharing. Without whitelisting "query schemes", you may get the error callback invoked when calling the canShareVia
function (and possibly the shareVia
). You can verify this is a permissions issue by observing the output in XCode for something like:
-canOpenURL: failed for URL: "whatsapp://app" - error: "This app is not allowed to query for scheme whatsapp"
You have a few options to prevent this by whitelisting the application you want to share via:
Directly editing the .plist file
This is a stright forward approach - you just manually edit the .plist file - either from within XCode or using a text editor. You can see example entries above (e.g. xyz). While this is simple to do, the changes may be lost when rebuilding the project or tweaking the platform (e.g. upgrading) and is less recomended.
Use query schema plugin
There is a plugin designed specifically to address query schema whitelisting. You can find the plugin and how to use it here. In general, after installation, you can change plugin.xml file under the plugin subfolder within the plugins directory of your project to add the required schemas. Here again though, you have to edit an additional file and should take care not to overwrite it when making changes to your project.
Use Custom Config plugin
The Custom Config plugin (here) allows you to add configuration to your platforms "native" configuration files (e.g. .plist or AndroidManifest.xml) through the project's main config.xml file.
To address query schema issue, after installaing the plugin you can edit the iOS platform section of your config.xml (in the project main folder) to include the required entries:
<!-- a bunch of elements like name, description etc --> <!-- add this entry --> whatsapp <!-- add more query scheme strings -->
The advantage with this method is that editing is done in the config.xml file which will most often be in your source control anyway and hence, changes to it will be reserved.