Implement Social Media Sharing With Ionic Framework

So you’ve made a great app, but need some help marketing it.  Adding social media features to your application is a great way help spread the word, without actually doing anything.  Social media can bring good traffic for you, the developer, and provide useful features to your user at the same time.

Take for example, you made a mobile app that finds funny pictures on the internet.  You might want to add a share button that shares a particular funny picture on your users social media account while including reference to your app so all their friends can use it too.

The following will show you how to make use of social media sharing in your Android and iOS mobile application using Ionic Framework.

To make this happen, we’ll be using the AngularJS extension set, ngCordova, along with the Apache Cordova plugin SocialSharing.

Let’s start by creating a fresh Ionic project from the command line with the Android and iOS platforms:

Please note, if you are not using a Mac, you cannot add and build for iOS.

The next thing we want to do is, add the Apache Cordova plugin that will be facilitating all these shares:

From this point, we can technically follow the official SocialSharing documentation to use this plugin, but we want to keep things AngularJS.

Download the latest stable ngCordova release and copy ng-cordova.min.js to your www/js directory.  With the library in place, you now need to add it to your projects index.html file similar to the following:

Note that ng-cordova.min.js must come before cordova.js in order for this project to work.

With the JavaScript file included into our project, we also need to include it in our app.js file.  Open it and modify angular.module to look like the following:

ngCordova is now set up in our Ionic project and ready for use.

For simplicity, we are going to do two things.  We are going to create a generic share button that lets the user pick how they want to share, and we are going to create a Twitter share button that will share only on Twitter.

Start by creating a new controller in your app.js file:

In the above code you’ll notice two functions.  A generic function for letting the user decide where to share, and a share via Twitter only.  In the generic function, we are sending a message, subject, link, and image from the www directory.  In the share via Twitter function, we first check to see if sharing through Twitter is allowed on the device.  If it is, then make a tweet.  A scenario where share via Twitter may not work is if Twitter is not installed on the users device.

In your index.html file, you can use something like this to execute the functions:

I personally use social media sharing to grow my user base.  Somewhere in your application, maybe in a settings view, you could have a button that tells the user to share on Twitter.  The function that goes with this button could look like this:

Notice in the above code, that a specific URL is used depending on the device platform.  This way Android users share the Android URL and iOS users share the iTunes URL.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

  • Daniel Lopez

    Hi, thanks for the code. I’m completely newbie with angularJs and ionic. I’ve tried the code using one of the ionic starter templates and I get the following error:

    Error: ionicApp is not defined

    I’ve the following angular module in app.js:

    angular.module(‘starter’, [‘ionic’, ‘starter.controllers’,’ngCordova’])

    Thanks in advanced

    • Hi Daniel,

      Make sure you do the following:

      var ionicApp = angular.module('starter', ['ionic', 'ngCordova'])

      ionicApp represents your module and it is what controllers, factories, services, ect., rely on.

      Hopefully that made sense.

      Regards,

  • asecondwill

    to check for twitter i needed i slightly different method call

    $cordovaSocialSharing.canShareVia(“com.apple.social.twitter”, message).then(function(result) {…

  • Hi Nic Thanks for the code.
    I would like to request you to kindly share the project zip file so that we can have look and understand more easily.

    • I don’t create and share projects. However, I’ll work on a video tutorial for this to clear things up.

      Regards,

  • Uri Naor

    Hi nick first of all great job on your ionic tuts, im trying to share via facebook and it does open the faceook app (im on a real android device) but it doesn’t pass the image or link parameters i pass to the function any idea what im doing wrong?
    var message =”See test Ecosystem in”;
    var image =’img/new/logo-home-s.png’;
    var link = ‘http://test.com’;

    $cordovaSocialSharing
    .shareViaFacebookWithPasteMessageHint(message,image,link,’Message pasted to clip board ,press on the area to paste it in the feed’)
    .then(function(result) {
    console.log(result);
    var alertPopup = $ionicPopup.alert({
    title: ‘Thanks for sharing via facebook’
    });
    alertPopup.then(function(res) {
    });
    }, function(err) {
    console.log(err);
    var alertPopup = $ionicPopup.alert({
    title: ‘Could not post to Facebook’,
    template : ‘Do you have the app installed?’
    });
    alertPopup.then(function(res) {
    });
    });

    • I’m not sure where you’re getting shareViaFacebookWithPasteMessageHint from. Why not use shareViaFacebook?

      • Uri Naor

        according to the official plugin git page
        https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin

        this method is there since facebook won’t allow to prefill a message on the share post

        • You may want to open a ticket on the main GitHub repo as there could be a bug. It would be out of control.

          Sorry,

          • Uri Naor

            ok
            and thanks again, i also learnt alot from your video about angular-translation ,great vid

          • Thanks for the compliment!

  • Anjum

    Hello Nic,
    This is a very useful post indeed. Thanks for sharing.
    Can you advise if there is a way to add carriage return in the message? Adding html codes like sends it as text.

    • Anjum

      I figured out. Apparently n is the answer 🙂

      • Awesome! Glad it is working now 🙂

  • Hoang

    Thanks for the code.I have a question. The plugin don’t support SMS on IOS (error: index.html when app run and click share by sms) and send email not support on IOS 8…

    • It should work fine on iOS 8. Can you share some of your code and what the exact error is?

      Regards,

  • Sab

    Thanks for your articles and videos.

    I am trying to use social media share and Custom URL Schemes in a single app.

    When i use the custom URL scheme as a link in social media share function, the link is coming as a plain text in the social media. Can you suggest a solution to fix this.

    • I think that is up to the social media provider, not anything we can fix via the app or code. If they don’t recognize it as a link, they will parse it out on their end.

      Regards,

      • Sab

        Thank Nic for the quick reply.

  • Legu Beat

    Hi, I get this error “Cannot read property ‘socialsharing’ of undefined” when i run with “ionic serve” and when I run in ionic view, nothing happens, I hope you will help me. Thanks

  • Pavit Singh

    Hi, thanks for the tutorial. I have one question what if we change the url like from index.html i will call a function that redirects to another url. Will the above cordova function still works if i include function with the library.

    • I’m not sure I understand. Can you give me an example?

      • Pavit Singh

        i have a app that have facebook login in ionic. After login redirect it to somedomain.com that also have ionic,cordova libraries using window.location.href. As i am redirecting, will social sharing still works ?

        • It might work if you’re not using the InAppBrowser plugin, but I really don’t know. I can’t say I recommend hosting Ionic and Cordova libraries on your server. Your application performance is probably going to suffer big time.

  • eka

    Hai, I am new to ionic and i still confused abour the file structure. can i get this file?

    • I don’t give out files to my blog posts. The goal here is to make the written and video tutorials sufficient enough to be able to reproduce on your own without issue.

      I do have a few Ionic projects on my GitHub if you wanted to look, but they are not for beginners:

      https://github.com/nraboy

      Regards,

      • eka

        finally i can implement it.. 🙂 btw, have u ever try savetophotoalbum?

        • I’m glad you got it working!

          I have not tried savetophotoalbum, sorry.

  • Raj Kumar.MP

    Nic. Is it possible to use sharing in whatsapp ?

    • The official plugin documentation says it is possible.

  • disqus_MWkWVWwx9A

    Im wondering if there is another step I am missing for ios? I followed your instructions, both video and written to a T, and i get an error in the console (.share undefined) and nothing occurs in the emulator. Any tips would GREATLY be appreciated

    • Are you using Ionic Server, Ionic View, or Ionic Live-Reload? If you are, stop. You should build the application and then install it directly to a device or simulator.

      If this isn’t what you’re doing, let me know and we’ll go from there 🙂

      Regards,

      • disqus_MWkWVWwx9A

        what is the best way to install directly to xcode simulator?

        • Use:

          Then open the Xcode file and install to your device or simulator.

          Regards,

          • disqus_MWkWVWwx9A

            i am so sorry for the questions, this is my first ios app, and first time using ionic, and i have spent too many hours on this issue. I have done the ionic build ios. I was doing ionic emulate after that. instead of ionic emulate, where would i find the xcode file, and what are the simulator commands to install it? Once again, sorry for the noobie questions.

          • You’ll find the Xcode project in your project’s platforms/ios directory. For testing applications with Xcode, I suggest you do a little research on the topic, but it should be straight forward.

            Regards,

          • KatieVG

            Ok, I got it running in the simulator, and still am having the same problems. of the share function being undefined. My shareAnywhere looks exactly like your tutorial. Any other tips? Thank you so much for your time

          • You might be suffering from a race condition. What happens when you wrap the function in a $ionicPlatform.ready or onDeviceReady function? This way the app is ready before trying to execute the plugin.

            Regards,

          • KatieVG

            yes, still getting $cordovaSocialSharing.share is not a function.. here is my code:

            $scope.shareAnywhere = function(){

            })

            }

          • KatieVG

            ok i think it is with cordova..would you recommend manually installing the plugin instead?

          • I don’t recommend installing manually. Can you put your project on GitHub so I can take a look?

          • KatieVG
          • KatieVG

            thank you for taking the time to help out!

          • I did a quick look only, but it seems fine. I also checked the ngCordova plugin website:

            http://ngcordova.com/docs/plugins/socialSharing/

            Says that .share() should still work. You may want to open an issue ticket here or post in the forums:

            https://github.com/driftyco/ng-cordova/issues

            Regards,

          • KatieVG

            thank you again, i really appreciate the help

  • Prag

    Thanks for the tutorial, couple of questions. Will this work in the PhoneGap Developer App? Also, is adding the platforms necessary in some way for the plugin to install correctly? I was thinking of avoiding adding the platforms and using PhoneGap Build…

    • Careful with PhoneGap Build. Not all plugins are fully supported. No idea the status of this one. What is the PhoneGap developer application?

      • Prag

        Based on this I would think it’s supported in PG Build (https://build.phonegap.com/plugins).
        PhoneGap dev app (http://app.phonegap.com/), you can wirelessly pair the app to your phone through the app from the cli.

        I’ve even tried deploying through test flight, and am still having trouble with the plugin, my mac is old and the emulator is extremely slow but maybe I’ll give that a try again.

        So sorry, is adding the platforms before installing plugins necessary for them to install to those platforms correctly? Or is that just a setup for the build process later on?

        • The hooks bundled with Apache Cordova should take care of platforms vs plugin problems, thus removing the need to already have particular platforms already installed.

          I don’t use PhoneGap build though, so you’re pretty much on your own on this one. I can’t help you troubleshoot it.

          If you install it to a device or simulator via Xcode and it doesn’t work, please share the logs.

          Regards,

  • junerockwell

    Hi Nick. Very straightforward. But I have a question, how to send an image like “http://something.com/image.png” with $cordovaSocialSharing in Android? I tried it using $cordovaSocialSharing.share(“hi”, “”, “http://something.com/image.png”, “http://something.com”)… and the Android phone says “Image could not be loaded” and then I also tried $cordovaSocialSharing.shareViaTwitter(…) and it doesn’t post anything to Twitter. I have Twitter installed in the Android phone.

    • You may want to open an issue ticket for the plugin developer. Doesn’t sound like it is problems with your code.

      Regards,

  • Alpesh Trivedi

    I want to show only Twitter, Facebook, Google+,Gmail, SMS, Whatsapp options in the sharing list, and don’t want to show others in the list. So, how can I do it ?

  • mario

    hi, I followed your cordovaCamera tutorial and I want to share the photo taken in that tutorial

    how can I put the image > $rootScope.imgURI = “data:image/jpeg;base64,” + imageData;

    into

    $scope.shareAnywhere = function() {

    replacing “www/imagefile.png”, but I don’t know how

    thanks!

    • I believe that parameter accepts a file path or a base64 variable. You might want to consult the plugin developers documentation.

      Regards,

      • mario

        thanks for your answer.

        but, where is the image stored? in a variable? how can I retrieve it?

        • It is stored in your imgURI variable. It is a base64 string, not an attachment on the file system.

          Regards,

  • sirMuffles

    Hi Nic. Great article. I was just wondering if there is a way to promt the user to open the shared link in your app if they have it installed? I am not too familiar with intents but I see that, when on android, when I click the shared link it offers to open it in chrome, standard browser, etc… Is there a way to open that shared link back in the app?

  • Christian Gill

    Hi, great tutorial 🙂

    I’ve been trying to add the general share but I’m getting this error “Cannot read property ‘socialsharing’ of undefined”

    Any ideas why ti could be undefined?

    This is how I define the shareAnywhere fuction

    $scope.shareAnywhere = function(title, link) {
    $cordovaSocialSharing.share(title, “Devops Reactions”, null, link); }

    P.S.: how do you markup code here?

    • You can markup code by wrapping it in code and pre tags.

      Is your code wrapped in $ionicPlatform.ready or onDeviceReady? If not, you might want to try that.

      Also, can you confirm that you are NOT running ionic serve, ionic live-reload, ionic view, or phonegap build? All of those have a history of problems with plugins.

      Regards,

  • Hello Nic, my name is Stenio and I’m Front-end developer and I’m starting at angularjs with Ionic. The creation of my first app, I’m using Social Sharing as you did in the tutorial, but when emulate does not. See the pictures of my code and the App:

    PS: By clicking on the icons does not happen any event. The emulator used is the same as yours, Genymotion v.2.5.0. The cordova was installed via the command line, by this is not included in the head.

    • What do your error logs say?

      • Do not return any error in both the debug in the browser as in the emulator, it’s just not returned any action from the click buttons.

      • I performed the tests with Facebook Sharing, Whatsapp Sharing, Sharing Any and Twitter Sharing, as you can see in print the app.js

      • Provided that it is necessary, I send you the project on GitHub

        • You should have errors in your ADB logs if it isn’t working. I guess post your project to GitHub.

          • I’ll check for errors in ADB logs

          • I did a quick look at your code. I believe that you should have error messages.

            Try adding a .then(function(result) {}, function(error) {}) to the social functions that don’t have them and print out the logs.

            Something to note, you probably won’t have anything to share with in your emulator, and you definitely won’t have anything to share with in your web browser. I highly recommend testing this on a device.

            Regards,

          • Hi Nic, I could see the mistakes the device returns to touch the sharing icons, see:

          • Wrap your plugin calls in an $ionicPlatform.ready or onDeviceReady. You may be suffering from a race condition.

            Regards,

          • Thus?

          • Close, but it is $ionicPlatform.ready not ionic.Platform.ready

            Regards,

          • So Nic, I researched a lot today about the error and still not managed to solve … 🙁
            This is one of Inappbrowser are catching me at this point. I will keep searching and trying to solve initially the SocialShare error:

            I/chromium( 3635): [INFO:CONSOLE(20306)] “TypeError: Cannot call method ‘canShareVia’ of undefined
            I/chromium( 3635): at Scope.$scope.shareViaWhatsapp (file:///android_asset/www/js/app.js:22:31)

          • How about you update your project on GitHub and I’ll take a look.

            Regards,

          • From what I understand and could analyze the problem is that when it loads the app.js, and call one of the functions to share, $ cordovaSocialSharing is null, so it does not recognize the share function, because getting null.share

          • I mentioned this to you two times already:

            https://www.thepolyglotdeveloper.com/2014/10/implement-social-media-sharing-ionicframework/#comment-2128592496
            https://www.thepolyglotdeveloper.com/2014/10/implement-social-media-sharing-ionicframework/#comment-2128626744

            Your code is not being wrapped in the $ionicPlatform.ready like I told you. Until this is done, I won’t be able to help you further.

            Regards,

          • I apologize, it is that as there were no changes, not had maintained. I will return it to the code and update on GitHub … A moment.

          • I have some doubt about the inclusion of $ ionicPlatform.ready involving the code because, when the place is returned in the console it is not possible to find a ready function. What would I be doing wrong?

          • Looks like you’re creating your controller incorrectly. I see you’re using annotations, but you’re annotating the wrong injections.

            You probably want:

            You don’t have annotations for $window and $cordovaSocialSharing so you cannot inject them to my knowledge. I could be wrong though.

            Regards,

          • Então, o problema é que, quando declarei a anotação $cordovaSocialShare foi devido a que, se não o fizer, me é alegado no console que $cordovaSocialShare não foi declarado. Realizei o update do código no GitHub: https://github.com/stenioanibal/plantaojti/

          • So the problem is that when I stated to $ cordovaSocialShare note was due to that if you do not, I is alleged in the console that $ cordovaSocialShare was not declared. I performed the update code on GitHub: https://github.com/stenioanibal/plantaojti/

          • I’m not sure what you’re trying to say. Google Translate didn’t do a very good job. Please try again.

            Regards,

          • I apologize, I don’t speak fluent english… I used annotation $cordovaSocialShare because if I don’t use, was returned on console: $cordovaSocialShare on undefined. I performed the update code on GitHub: https://github.com/stenioanibal/plantaojti

          • I’m having trouble helping you, so at this point you might have better luck asking in the forums. Sorry

          • I did such tests but the error persists, see:
            Each tap on the icon generates a block with error.

      • Anderson Murakami

        Hi Nic,
        I use the plugin in two controllers. On LoginCtrl it s ok !
        But on GalleryCtrl returns this mesage:
        TypeError: Cannot read property ‘socialsharing’ of undefined
        Login:
        .controller(‘LoginCtrl’, function ($http, $scope, $rootScope, $timeout, $stateParams, ionicMaterialInk, Escopos, $cordovaSocialSharing, $state, $localStorage)

        Gallery:
        .controller(‘GalleryCtrl’, function ($scope, $rootScope,$stateParams, $localStorage, $sce, $http, $timeout, $cordovaSocialSharing, ionicMaterialInk, ionicMaterialMotion, Escopos,$state)

        What is wrong ?

        Thanks in advance

        • Anderson Murakami

          I found the “solution”.kkk in browser he does not work.. Sorry.

          • Native plugins cannot be used in a browser.

  • Onkar Lal Janwa

    is that possible to limit sharing options? Like i want to enable only for Twitter and Facebook.

    • I think the only way to do this would be with shareViaTwitter and shareViaFacebook. If you call the main share command, I believe it is up to your operating system in regards to what is displayed and we don’t have control over that.

      Regards,

      • Onkar Lal Janwa

        Thanks @Nic for your quick reply, we can do a custom display of share popup then perform action accordingly.

  • Karthikeya Mishra

    I am using shareviafacebook and passing text, image & link. But on the share it is only showing the image, not the text and the link. How can I pass the text in the share option of facebook with the image?

    • What command are you using? Are there any error logs?

      • Karthikeya Mishra

        There is no error log. Let me show what I am trying to do:

        $scope.shareViaFacebook = function(message, image, link) {

        }

        This message I want to be in the dialog box of facebook along with the photo and link.

        • You probably want to open an issue ticket with the plugin developer. Your code looks correct.

          Regards,

          • Karthikeya Mishra

            I raised this issue ticket with the plugin developer. I have another question with the “shareAnywhere” option of the plugin. From there I can share it any of the apps installed on the phone. Can I customize this sharing and limit it to certain apps?One more question – “Do I have any other method through which I can directly share on the google+?”

          • I don’t think you can customize what options are available for sharing. I believe that is baked into the operating system. For sharing on Google+ you can use one of three things:

            The social sharing plugin
            The Google+ RESTful APIs
            The Google+ plugin

            Regards,

          • Karthikeya Mishra

            thanx a lot !! It will help a lot !!

          • No problem!

          • Karthikeya Mishra

            Hi ,
            I am stuck with a problem. I am trying to use the nativeUrl of mobile storage in my image parameter. By on debugging this value is showing me undefined. How can I share a image through local storage.

          • Are you storing the base64 of the image? I am confused by your comment.

            Regards,

    • Gene

      I Hope I am not too late but as of Facebook’s policy, you are not allowed to pre-defaultly stating the message for the user. The user will have to do it their self but if you test it with another application like Twiiter, your message will appear.

      • Can you please link us to the policy so we all have it?

        Best,

  • FX Bayu Anggara

    Trying it now, I just think the same thing that it could boost the marketing of my app. Great tutorial.

  • FX Bayu Anggara

    Trying it now, I just think the same thing that it could boost the
    marketing of my app. Great tutorial. By the way can I set a parameter in
    sendAnywhere(myParam1,..myParam4) .. so that the content of the shared
    messages is dynamic depend on what it loaded in html before. Thanks

    • FX Bayu Anggara

      I’ve succeed add a parameter into the shareAnywhere function, by change the controller like $scope.shareAnywhere = function(msg) {
      $cordovaSocialSharing.share(
      msg.title,
      msg.contentl,
      null,
      msg.url
      );
      }
      in html :
      shareAnywhere(item) , where item is doing a ng-repeat

      just share, thanks for this articles.

  • estiven ramirez

    Hi, Nic I’m using this plugin and I can share content, but when I go back to my app, app restarts. Do you know what the problem is?

    • What do your logs say?

      • estiven ramirez

        I’m using Moto g xt1040 with android 4.4.4, on others android devices that is not happening. I’m going verify logs.

  • djs

    Hi Nic, do you know if there is a ways to check if the user actually shared the item or canceled when using:

    $cordovaSocialSharing.share(message,subject, image, link)

    I want to verify the item was actually shared (or see if the user decided to cancel)

    Also do you have an idea how to add the message at the bottom of a facebook shares that said which app it was shared from I have seen those posts with “via xxxxx” at the bottom of posts on facebook

    • The sharing functions use promises so when it completes the success callback will be hit, otherwise error. As far as “Shared via xxxxx” goes, I’m not sure this plugin can handle that. You’d have to ask the developer that question.

      Regards,

      • djs

        Thanks Nic! yes I know its returning a promise and that works well when I use: shareViaFacebook(message, image, link)

        but when using: $cordovaSocialSharing.share(message,subject, image, link) the promise return is true not when a massage is posted (shared) but if the sharing sheet opened, so even if the user doesn’t share and hit cancel on the sharing sheet the promise is still true.

        • Yea canceling is still a successful event. I don’t think you’re going to be able to watch for if the user canceled. Maybe talk to the plugin developer and see if he can add a property to the success response that says if they canceled or not?

          • Nicolas

            Hi Nic! did you find any way to watch for if the user canceled?

        • sagar chaudhari

          hey..did you find any way for this..!?

  • Masthan

    Hi Nic Raboy, i am new to ionic framework. I followed your steps in video. But it is not working after building app. my ionic version is 1.6.4, cordova version is 5.1.1 and node js version is v0.12.7.
    can you check my code and suggest how to share app in twitter.
    My git repository id:- https://github.com/MasthanSheik/SharingApp

  • Mohammad Al-mouallem

    Hello Nic, Thank you for the great articles you post.
    i had small issue with this plugin when i press on the share via FB button in my app it takes long time to launch the FB UI where i put the description and post the content. Do you have a way to boost the performance for this !

  • Mohammad Al-mouallem

    I remember i posted a comment here but i can’t find it however, i use this plugin in my app but it’s so slow it takes around 2 min to open the Facebook UI where you can post the data you want to share from the app. i used the implementation on the ng-cordova site any solution for this ! thank you

  • Shrinivas Kattimani

    Thanks for the nice tutorial. I just want to know whether it supports Linkedin as well.

    • I believe that is up to your device platform. I don’t think there is a shareViaLinkedIn function, but if you do the generic share, your device OS might recognize LinkedIn as a valid share option.

      Regards,

  • Enrike Nurmammadov

    Hi Nic,
    Thank you for this tutorial.
    I was trying to write sms share code, but I got errors.

    Can you share working sms share code?

  • Ryan Marchock

    Do you have any examples using $cordovaImagePicker to select an image and using $cordovaSocialSharing to share? I created a quick test and IOS seems to be working but not Android.

    • I don’t have any examples like this, sorry. Are you getting any errors in your logs?

      • Ryan Marchock

        No log errors. I receive a toast message “image could not be loaded” when i try to share an image on twitter and google+ a blank grey box with a broken image icon is displayed.

        • You may want to communicate with the developer of the image picker plugin.

  • Soumen Naskar

    Hi Nic,

    I want to share picture with comment in WhatsApp using this plugin. In android its working fine, but in IOS only the picture is been shared, not the comment.
    I have checked the official doc of the plugin, there I found It shares only the picture not the comment in IOS. So now my question are:
    1. Is there any other plugin available like this, which will allow me to share picture with comment in WhatsApp?
    2. Can I post only comment in the WhatsApp Using the function: {window.plugins.socialsharing.shareViaWhatsApp(‘Message via WhatsApp’)} ?

    Thanks in advance.

    • I don’t use WhatsApp so I honestly couldn’t tell you what plugins exist for it. Your best bet would probably be to contact the plugin developer.

  • Joel Elangovan

    Hi Nic, I am trying to share some text from page, I tried to assign the div as a ng-model and tried to get it as scope , but it doesnt work. Here is my code . Can u help me out.

      • Joel Elangovan

        Thank you so much, Really was helpful reading the article. I am actually trying to create a Daily Devotional for my church. I wanted to have a calendar list to click on and read the articles, What i did is i made a calendar in html and i hardcoded links to pages with the content, I thought of using sqlite to load the articles but i thought it would be faster to load a page then to load it from the database, I am sure which one is better, In the details page (where the daily devotional is) i would like to have share button, where people would click on it and share the devotional (all the text and images) on facebook mainly. I havent used much of angular in the code, i have so far used only html and css. On the devotional page, how would i get hold of the text and images , as it is hardcoded on the page, $scope doesnt seem to work, what i tried was to make the div ng-model, and i tried to get it in the scope, doesnt work, I get an error on adb log, as message empty. Thank you so much for helping others out.

        • Please paste your full logs.

          • Joel Elangovan

            I/ActivityManager( 399): Displayed com.android.email/.activity.MessageCompose:
            +126ms

            This is almost the log other than the genymotion logs, when i click share button with email, the email compose buttons open the link appears but not the message, it seems i am not doing right with getting the text to $scope to pass it to the plugin, The plugin works fine, with predefined text. is it possible to take the harcoded text in the page and pass it to the plugin ?

          • Full logs please.

          • Joel Elangovan

            I fixed the errors, thank you.

          • Great 🙂

  • Germain Tanon

    Hello all, I developed with an application using social sharing SMS, but I want to share by customizing the message to send. Here is my code:

    I try to add the concatenation of characters but it does not pass ,
    i.e.
    onclick=”window.plugins.socialsharing.share(‘”+{{detailService.itemName}}+”‘, ‘The subject’)
    or

    onclick=”window.plugins.socialsharing.share({{detailService.itemName}}, ‘The subject’)
    but it does not pass , please help me

    • I suggest you make a function in your controller and pass detailService.itemName in via an ng-click rather than trying to do what you’re doing in an onclick.

      Best,

      • Germain Tanon

        I have a listview that I called with this controller

        .controller(‘ExcuseCtrl’, function($scope, $http, $ionicLoading,detailService) {
        $ionicLoading.show({
        template: ‘Chargement …’
        });
        //Get profile information
        $http.get(‘http://xxx/ha_videos.json’).
        success(function(data, status, headers, config) {
        $ionicLoading.hide();
        $scope.badges = data.badges;
        }).
        error(function(data, status, headers, config) {
        $ionicLoading.hide();
        $ionicLoading.show({
        template: ‘Mauvais chargement!’
        });
        setTimeout(function(){
        $ionicLoading.hide();
        }, 1000)
        });

        $scope.getDetail=function(ObjectData){
        detailService.itemName = ObjectData.contenu;
        }

        })

        to selection of the view I have transmitted my other view content (text or link) thanks to the controller

        .controller(‘DExcuCtrl’, function ($scope, $stateParams, detailService) {
        $scope.detailService = detailService;

        })

        And I want to send the SMS according {{detailService.itemName}} selection made

        But i can not , help me Nic thank

  • Guille Acosta

    Thanks Nic, worked great for me on an existent project.
    I was not passing right the url link, because I forgot braces on angular expression.
    My suggestion is to add error message on alert:
    alert(“Cannot share on Twitter ” + error);

  • Germain Tanon

    Hi I wonder if we can add two controller in a same view.
    Example: ng-controller = “controller1 controller 2”

    • Can you explain why that would be useful?

      • Germain Tanon

        I have a listview that I called with this controller ExcuseCtrl

        .controller(‘ExcuseCtrl’, function($scope, $http, $ionicLoading,detailService) {
        $ionicLoading.show({
        template: ‘Chargement …’
        });
        //Get profile information
        $http.get(‘http://xxx/ha_videos.json’).
        success(function(data, status, headers, config) {
        $ionicLoading.hide();
        $scope.badges = data.badges;
        }).
        error(function(data, status, headers, config) {
        $ionicLoading.hide();
        $ionicLoading.show({
        template: ‘Mauvais chargement!’
        });
        setTimeout(function(){
        $ionicLoading.hide();
        }, 1000)
        });
        $scope.getDetail=function(ObjectData){
        detailService.itemName = ObjectData.contenu;
        }
        })

        to selection of the view I have transmitted my other view content (text or link) thanks to the controller DExcuCtrl

        .controller(‘DExcuCtrl’, function ($scope, $stateParams, detailService) {
        $scope.detailService = detailService; })

        And I want to send the SMS according {{detailService.itemName}} selection made

        Excuse ” {{detailService.itemName}} ”

        Envoyer via SMS

        It does not go with the ng-click of cordova and I am in the dark

        • Usually you want one controller per view. If you have nested routes, you can still assign one controller per partial. Have you tried this? I’d rather not see code, but instead logs and descriptions.

          • Germain Tanon

            12-15 10:26:09.831 23195-23195/io.cordova.myapp877d0f I/chromium: [INFO:CONSOLE(25)] “No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin.”, source: file:///android_asset/www/plugins/cordova-plugin-whitelist/whitelist.js (25)
            12-15 10:26:19.881 23195-23195/io.cordova.myapp877d0f I/chromium: [INFO:CONSOLE(25)] “No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin.”, source: file:///android_asset/www/plugins/cordova-plugin-whitelist/whitelist.js (25)
            12-15 10:26:29.932 23195-23195/io.cordova.myapp877d0f I/chromium: [INFO:CONSOLE(25)] “No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin.”, source: file:///android_asset/www/plugins/cordova-plugin-whitelist/whitelist.js (25)

  • Stewiek K

    how exactly do you add this plugin?

    “Add SocialSharing Apache Cordova Plugin
    Shell
    1https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin.git

  • Neema Dinosaurad

    Is it possible to direct the user to App Store, if the respective app is not installed, and perhaps direct to the app if it is installed?
    I realise that you probably need to use Eddy Verbruggens Custom-URL-Scheme plugin for this.

    Just not quite sure how to check if the app is installed from the URL sent with the social-share link.

    Thanks in advance.

    • Are you wanting to open your app from within a different app or are you wanting to open the app store / other app from within your app for a different app?

      Best,

      • Neema Dinosaurad

        The idea was if a link to my app was shared on for example Facebook, and someone clicks it.
        I want them to be redirected to either my app if it’s installed, or app store if it’s not.

        Thanks for the quick reply.

        • My best recommendation would be to share links that point to a landing page on your web server giving the person the option to visit the app store.

          • Neema Dinosaurad

            Ah, alright. I’ll try that. Was hoping for some sort of if-statement that could check if the app was installed, like the one you made for Google Play vs. App Store.
            But thanks for the help!

          • The if-statement stuff only works if you’re doing it within the Ionic app. Coming from some third party application, you have no control.

  • Mounika

    Hello Nic,

    I’m using Facebook sharing in my app.I have created a local file and stored images in local file, when i have written image path in Facebook share it doesn’t display image. I would like to share image it will get from local file.would please suggest me any solution.I have gone through many tutorials but i didn’t get any file.I have used below code for getting images and stored in local file.

    $scope.takePhoto = function (a) {

    destinationType : Camera.DestinationType.FILE_URI,

    sourceType : Camera.PictureSourceType.PHOTOLIBRARY, // Camera.PictureSourceType.CAMERA

    allowEdit : false,

    encodingType: Camera.EncodingType.JPEG,

    popoverOptions: CameraPopoverOptions,

    };

    window.resolveLocalFileSystemURL(fileURI, copyFile, fail);

    }

    function copyFile(fileEntry) {

    var name = fileEntry.fullPath.substr(fileEntry.fullPath.lastIndexOf(‘/’) + 1);

    var newName = makeid() + name;

    window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(fileSystem2) {

    fileEntry.copyTo(

    fileSystem2,

    newName,

    onCopySuccess,

    fail

    );

    },

    fail);

    }

    function onCopySuccess(entry) {

    $scope.$apply(function () {

    });

    }

    function fail(error) {

    }

    function makeid() {

    var text = “”;

    var possible = “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789”;

    for (var i=0; i < 5; i++) {

    text += possible.charAt(Math.floor(Math.random() * possible.length));

    }

    return text;

    }

    var trueOrigin = cordova.file.dataDirectory + name;

    return trueOrigin;

    $cordovaSocialSharing.shareViaFacebookWithPasteMessageHint(“hi”, $rootScope.image, null, ‘Paste it here!’, function() {console.log(‘share ok’)}, function(errormsg){alert(errormsg)});

  • Gianfra

    Hi Nic!
    Do you know if it is possible to share also videos or just pictures and texts?
    Thanks

    • I believe only pictures and text. Videos are generally too large in size to share.

      Regards,

  • Andrien Pecson

    Hello Nic I’ve used the facebook sharing of the cordova plugin. It was awesome using it but sadly when a facebook lite application is installed in the phone, the facebook sharing is not working. Any thoughts on this one? Cheers

    • You might want to contact the plugin developer for this one. My guess is that the plugin was only designed to work with the official standard version of the Facebook application.

      • Andrien Pecson

        Thanks Nic for the reply. Just want you to know that you helped me so much with your tutorials.

        • No problem, please spread the word.

  • Pretty easy and amazing, thanks Nic

  • hi sir..i need to call all fucntions for share(eg. gmail, google, and social apps)…should I use popover for these options????
    can i use eedy’s controller function??is it working??(y..when i click on button..alert() is not called??…in browser).

    • Per the documentation, if you just call ‘share’ it will present you with a popup and let the user choose what they’d like to share with.

      In terms of the web browser, this is a native plugin and can only be used on a device.

      Regards,

      • Thank You..
        Plaese…can you send me code??

        • I only share an archive of the source code with my paid content or sponsored posts. This is neither.

          Best,

          • Thank u..sir..
            And urs fileopener is not working.. Even ngCordova function also.. Just v can call d fun.. But not working..!!

      • its working..and simply cool

      • sir..how to get increment by click on like button (reffer: facebook) in angular js for ionic

  • Anurag Pandey

    Hello Nic , social sharing working fine but when i not share or cancel then how to show cancel by user.

    • I’m pretty sure you can’t check for this. You can only check if it succeeded or if there was an error.

  • Arvind Babu Chandrasekaran

    HI Nic Social Sharing is working well, On Facebook sharing can we post the message to only a single friend timeline, instead of posting it to a Group or Friends or Public.

    • It is whatever your device OS allows as this plugin uses the native device APIs baked into the device OS.

      Best,

  • Gegejosper Ceniza

    Hello Nic,

    I tried your code but it displays

    [INFO:CONSOLE(25642)] “TypeError: Cannot read property ‘socialsharing’ of undefined
    I/chromium(32639): at Object.share (file:///android_asset/www/js/ng-cordova.min.js:9:17021)

    Please help..

    • Maybe ngCordova changed since writing this?

      • Gegejosper Ceniza

        Do you have any alternatives? I just start to learn developed ionic app following your blog.. pleas help..

      • Gegejosper Ceniza

        Do you have any alternatives?

        • I encourage you to take a step back and start with the Ionic basics. If you’re new, jumping into complicated subjects is not a good idea.

          Since you’re new to this blog and didn’t know, I won’t hold it against you, but do not post more of the same comment if I don’t respond. I’m a busy person and often cannot respond to everyone right away. Posting multiple times is a good way to get ignored.

          Best,

  • sufiyan khan

    Hi Nic,
    You have a tutorial for everything.Implemented your code and it works wonders.I hope to see more videos in future..

  • Gopinath Kaliappan

    Hi … Nic I have doubt … if the user not installed twitter means …
    i want to redirect the user to Twitter installation Page in Google App
    Store …. How can we perform that action ….

    • Call the canShareVia function for Twitter. If it comes back false redirect to the app store or Twitter website.

      • Gopinath Kaliappan

        Wow I did it i have used

        window.open(‘https://play.google.com/store/apps/details?id=com.twitter.android’) ,

        It works fine , thanks a lot Nic….

      • Gopinath Kaliappan

        I did using ,window.open(‘https://play.google.com/store/apps/details?id=com.twitter.android’,’_system’);

        Thanks a lot Nic ,

      • Gopinath Kaliappan

        Hi Nic … I Did this in android … But I don’t know whether the following code will work in IOS or not .. because i don’t have MAC to check … Is the below code Work for ios device ???

        if(isIOS==true)
        {
        // Don’t Know right or wrong ??
        window.open(‘https://itunes.apple.com/in/app/twitter/id333903271?mt=8′,’_system’);
        }
        else if(isAndroid==true)
        {
        // Working in android
        window.open(‘https://play.google.com/store/apps/details?id=com.twitter.android’,’_system’);

        • For iOS, I think you want this:

          Best,

          • Gopinath Kaliappan

            Thank You Nic I will check it … and let u know …

  • Tom Costa

    Hello NIC RABOY!

    Great example! I’m following your tutorials…
    Not allways it works good, sorry for saying that.
    I’m begginer, I will not be it forever, and I use MVC, like at least 3 files.
    So it is like: app.js, controllers.js and services.js also…
    In yours examples everything is going on to app.js.
    I thinks is not a good practice, and not works sometimes.
    Well… Thanks anyway!

    • I agree with you that not everything should be placed in the app.js file. However, I do this because it is generally easier to follow along with for beginners when everything is in a single file than a hundred smaller files containing services, controllers, etc.

      It may not be clean, but it should work every time. Do you have an example where it does not?

      Best,

      • Gopinath Kaliappan

        I agree with Nic Definitely it will work with the single file …

  • kashshah43

    Hey Nic,
    Awesome Tutorial…!
    Can you share the same for Instagram ?

  • Gopinath Kaliappan

    Hi … Nic … Nice to meet u again …

    If The Application not installed i want to redirect the user to Google Play store , How to do that

    For Ex .. If the user trying to share via twitter , How to Do that …

    Thanks in Advance …

  • Mangal

    Hello Nic,

    Thanks for code. It is working on android emulator but when i upload the app on ionic view no response are getting from button click. please suggest to resolve the issue.

    • None of the Ionic deployment services should be used if your application contains plugins. This includes ionic serve, ionic view, ionic live reload, or phonegap build.

      Best,

  • venis

    Except Facebook all other social sharing were working fine. In facebook, message is wrongly displayed as “Gmail is email that’s intutive, efficient, and useful. 15 GB of storage, less spam and mobile access” instead displaying my actual message. Please help me with an solution

    • You should probably raise this issue with the plugin developer.

      • venis

        Thanks for your reply. I will do the same

  • Rajput Vicky

    Hello Nic,
    I tried your code but it displays
    TypeError: Cannot read property ‘socialsharing’ of undefined
    at Object.share (ng-cordova.min.js:9)
    at Scope.$scope.shareAnywhere (app.js:30)
    at fn (eval at compile (ionic.bundle.js:27638), :4:230)
    at ionic.bundle.js:65427
    at Scope.$eval (ionic.bundle.js:30395)
    at Scope.$apply (ionic.bundle.js:30495)
    at HTMLButtonElement. (ionic.bundle.js:65426)
    at defaultHandlerWrapper (ionic.bundle.js:16787)
    at HTMLButtonElement.eventHandler (ionic.bundle.js:16775)
    at triggerMouseEvent (ionic.bundle.js:2953)

    plz help me i am new in ionic with angulerjs

  • noor

    Hi there,

    Such a great tutorial! But i was wondering when I press share all the installed apps that can be shared to are viewed. Is there any way to limit the apps that can be shared to when pressing the ‘share everywhere button’

    • This is up to your device OS. That said I think it is all or nothing.

  • Abhi Kureshi

    I am making one app project. while i add function of social share in this app then it is not working but while i create new project then it is working well. i dnt know what is the error. my project is based on IT JOBS. I implemented many features in this app. many libraries included. i think because of this reason this is cant working. do you guess what error??

    my code is
    app.controller(‘Social’, function ($scope) {
    //
    $scope.share = function (t, msg, img, link) {
    if (t == ‘w’)
    window.plugins.socialsharing
    .shareViaWhatsApp(msg, ”, link);
    else if (t == ‘f’)
    window.plugins.socialsharing
    .shareViaFacebook(msg, img, link);
    else if (t == ‘t’)
    window.plugins.socialsharing
    .shareViaTwitter(msg, img, link);
    else if (t == ‘sms’)
    window.plugins.socialsharing
    .shareViaSMS(msg + ‘ ‘ + img + ‘ ‘ + link);
    else {
    var sub = ‘Beautiful images inside ..’;
    window.plugins.socialsharing
    .shareViaEmail(msg, sub, ”);
    }
    }
    })

    i also implement plugin “cordova plugin add cordova-plugin-x-socialsharing”
    in controller js “var app = angular.module(‘starter.controllers’, [‘ionic’, ‘ngCordova’, ‘starter.services’])”
    in app.js “var app = angular.module(‘starter’, [‘ionic’,’starter.controllers’, ‘starter.services’, ‘ngCordova’, ‘starter.services’, ‘morphCarousel’, ‘ionic.ion.headerShrink’, ‘ionic-ratings’])

  • Jyotsna

    Hi, Thanks for a nice tutorial.

    I am trying to share a pdf as text message using shareAnywhere() {$cordovaSocialSharing.share(“”, “”, someServer/pdffile.pdf , null)}. However, my text message does not show the pdf attachment. Any suggestions on this please?

    • Text messages typically only support picture and video. PDF falls under documents. I imagine that is why you’re having issues.

  • Anderson Murakami

    My console returns this error:

    Error: $window.plugins is undefined
    .[email protected]://localhost:8100/lib/ngCordova/dist/ng-cordova.js:6668:9
    [email protected]://localhost:8100/js/controllers.js:223:9
    [email protected]://localhost:8100/lib/ionic/js/ionic.bundle.js line 27643 > Function:2:227
    @http://localhost:8100/lib/ionic/js/ionic.bundle.js:65429:9
    $RootScopeProvider/this.$get<[email protected]://localhost:8100/lib/ionic/js/ionic.bundle.js:30400:16
    $RootScopeProvider/this.$get<[email protected]://localhost:8100/lib/ionic/js/ionic.bundle.js:30500:20
    @http://localhost:8100/lib/ionic/js/ionic.bundle.js:65428:7
    [email protected]://localhost:8100/lib/ionic/js/ionic.bundle.js:16792:3
    [email protected]://localhost:8100/lib/ionic/js/ionic.bundle.js:16780:9
    [email protected]://localhost:8100/lib/ionic/js/ionic.bundle.js:2953:3
    [email protected]://localhost:8100/lib/ionic/js/ionic.bundle.js:2942:3
    [email protected]://localhost:8100/lib/ionic/js/ionic.bundle.js:3018:5

    Why ?

    • Native plugins cannot be tested with server, livereload or view. Your error indicates you’re using one of those.

      Best,

      • Anderson Murakami

        Ohh, ok ! I have to compile to test.. ok, thank you ! Nice tutorial !

  • Anderson Murakami

    Hi Nic, I have problems to sharing on facebook. The screen appears, but the text field is empty. Without the subject, message, image or link. What is wrong ?

    On the WhatsApp, it fails. But I think it might be because it’s not on google play, correct ?

    Thank´s in Advance

    • You might want to contact the plugin developer. Sounds like there could be a bug.

      • Anderson Murakami

        Ok, do you have the developer email ? How do I contact ?

        • Open an issue ticket on the developers GitHub.

    • Rajan

      Hi Nic, Did it worked for you I am also getting the same error, but it works for gmail

      thanks,

  • Varun Tendulkar

    hello sir, can you tell me how to receive data from other apps. I mean when we click share button in whatsapp/google drive , how to see our app in the list and get the data from there.