Ionic 2 – Sending push notifications to specific devices (Part 1)

Hi Friends,

Hope you are all well. This post is one of the most requested posts on this site. We’ll see how to send push notifications to specific devices through a program. This is done with the help of device tokens and the cordova fcm plugin.

Let’s get started.

A screencast of this post

The complete code of this post can be found here.

I’ll divide the post into two parts.

1) Part 1 – Ionic 2 app that allows us to login and send a message.

2) Part 2 – Real-time database trigger running on firebase cloud that sends a push notification.

First scaffold out an Ionic 2 application. Then install the cordova-plugin-fcm using the below command.

Okay. Now let’s install firebase and angularfire2.

Generate a login page using the below command.

Now open up app.module.ts file and modify it as shown below.

Next, open up your login.html and include some code as shown below.

Open up login.ts and write the signin function.

We have simply got the username and password from the user and we use it to login into our app.

Open up home.ts file and add the below code.

Let’s break this down.

  1. The FCM Plugin methods are pretty much self-explanatory. They do as their name suggests. The onNotification method  watches for notifications, and displays the notifications in alert.
  2. We simply get the device token of the device that the user uses to login and store it in a pushtokens collection. Then we push a message to the messages collection.
  3. We also have a onTokenRefresh method that jumps into action whenever the device token is refreshed. (Here, we haven’t done anything in that method, but in an ideal scenario you need to store the new token in the pushtokens collection).

Now before we run this app, we need to do a few things.

Open up your firebase console. You should see a screen as shown below.


Now in this screen click on Add firebase to your android app.

You will see a screen as shown below.


From your config.xml copy the widget it and paste it in the package name.

Click on register app and you will see a big blue button called google-service.json.

Click on the button. Once the google-services.json file is downloaded, copy and paste it on to your Ionic project’s main folder.

Run the app on any device now. It should go fine.

I will explain how to make use of this token stored in the collections and send msgs automatically to devices whenever a message is stored in the next post. Stay tuned.

Hope this helped you guys. Share it with someone else and help them too.

Thanks for reading. Peace.. :)


Liked it? Take a second to support admin on Patreon!
  • José Martínez

    What happend?, this error:
    Runtime Error
    Uncaught (in promise): ReferenceError: FCMPlugin is not defined ReferenceError: FCMPlugin is not defined at http://localhost:8100/build/main.js:56617:13

    I can not find the error.