DEV Community

Cover image for How to set up Firebase Push Notifications with Ionic & Vue.js
Marco Improda
Marco Improda

Posted on

How to set up Firebase Push Notifications with Ionic & Vue.js

Did you have issues configuring Push Notifications with Ionic & Vue.js? Did you not found the documentation for Vue, but only for Angular? This is something I had too and that's why I have decided to make this post. By the end, you have your Ionic application ready and working with Firebase's Cloud Messaging service.
Plus, you will found a repository with a basic app that has already everything up to work.

So let's begin!

Step 1 - Create our app

First of all, make sure to create a new Ionic Vue.js app with Ionic CLI. Open your Terminal or CMD/PowerShell and write

ionic start --type=vue

Set all the requirements for your application and open the folder of your project with your favourite code editor.

Open the file capacitor.config.json and set an appId. Could be for example: com.myionicapp.demo
appId

Now go on Firebase, select Get Started & Add Project.

On Android package name set the appId that you had set previous on your capacitor.config.json.
Firebase appId

Save google-services.json. We need it later to configure correctly our application with Firebase.
JSON File

Step 2 - Integrate Firebase plugin

To begin, we need to install Capacitor Firebase Cloud Messaging plugin. You can do with a simple command:

npm i @capacitor-community/fcm

Open your App.vue file with your code editor. And... Oh, wait!

Thanks to Elbphilharmonie via StackOverFlow
We now know how to set it correctly and avoid the result of undefined.
I had it too
First, we need to import FCM by add this line to App.vue:

import { FCM } from '@capacitor-community/fcm';

Then after components, add this line:

  data() {
    return {
fcm: new FCM()
    }
  },
Enter fullscreen mode Exit fullscreen mode

In this way, we have avoided this potential issue. But we need to execute it to generate a token and communicate with Push Notifications from Capacitor.

Step 3 - Integrate Capacitor Plugin

Let's begin by importing Push Notifications' plugin. Add this line to App.vue:

import { Plugins } from '@capacitor/core';
const { PushNotifications } = Plugins;

And a mounted method with this function:

// Request permission to use push notifications
    // iOS will prompt user and return if they granted permission or not
    // Android will just grant without prompting
PushNotifications.requestPermission().then(result => {
      alert("result " + JSON.stringify(result));
    });
         // Add registration error if there are.
        PushNotifications.addListener("registrationError", (error) => {
          console.log(`error on register ${JSON.stringify(error)}`);
        }),
        // Add Notification received
          PushNotifications.addListener(
            "pushNotificationReceived",
            (notification) => {
              console.log(`notification ${JSON.stringify(notification)}`);
            }
          ),
          // Add Action performed
          PushNotifications.addListener(
            "pushNotificationActionPerformed",
            async (notification) => {
                alert("notification " + notification)
              console.log("notification succeeded");
            }
          ),
          // Initialize the registration with FCM Token
          PushNotifications.register();
        const fcmToken = this.fcm.getToken();
       alert(JSON.stringify(fcmToken));
        console.log("token:" + JSON.stringify(fcmToken));
  },
Enter fullscreen mode Exit fullscreen mode

Remember: You cannot test this function with a web browser. Because FCM and Push Notifications plugin doesn't have a web implementation.

Step 4 - Build Android app

We need to add support for the Android platform. Let's do it by following the Ionic documentation.

For your convenience, I leave here all the steps that you need.

ionic build
ionic cap add android
ionic cap copy
ionic cap sync
ionic cap open android
Enter fullscreen mode Exit fullscreen mode

Before you build the app, you need first to copy the file google-services.json from Firebase into android/app. Then on Android Studio,
select app -> the folder with the name of your app -> MainActivity.java

And add the following code after

import java.util.ArrayList;

import com.getcapacitor.community.fcm.FCMPlugin;
Enter fullscreen mode Exit fullscreen mode

Then into // Initializes the Bridge

add(FCMPlugin.class);
Enter fullscreen mode Exit fullscreen mode

Save it.

Step 5 - Optional

Is your MainActivity.java flagged with the red color? Something went wrong and the main issue is Android Studio isn't capable to load the package com.getcapacitor.community.fcm.FCMPlugin.
Thanks to wekas at Ionic Forum, we have the solution for this issue.
On Android studio follow these steps:

Build -> Clean Project
File -> Sync Project With Gradle Files
Run
Enter fullscreen mode Exit fullscreen mode

Voilà! Now build your Android App and test it on your device.

Step 6 - Test the notification

We can send a test notification to see if everything is set up correctly.
Connect to Firebase select your project --> See all features --> Cloud Messaging -> Send your first message.
Firebase Cloud Messaging

Set a title and text for it.
Firebase Push Notification

Now you can try to send a push notification only on your device with the token. You can have it by debugging and look into the console. Follow the Ionic Documentation for debugging your Ionic app.
Firebase Token

Or you can set the notification by completing all the Firebase steps. This will work with all devices that have installed your Ionic app. No matter if your application is open or not.

Success

Step 7 - iOS

I'm sorry, but currently, I cannot test the application on iOS. I will update as soon I can.

Step 8 - Source code

Do you prefer to take a look at the code? Please see here. I have uploaded a demo application.
Don't forget to upload your google-services.json and build & sync the code with Android Studio.

Thanks

I hope this post could help everyone that needs to enable push notifications on their Ionic Vue application. I did my best to make it plain and simple and to provide a stable resource with an up-to-date tutorial to follow. That's it.
Let me know if you find it helpful and until then, see you next time. Ciao :)

References

Push Notifications with Ionic/Angular
Firebase Cloud Messaging to receive Push Notification in Ionic 4 Vue app using Capacitor.
Capacitor - TypeError: Cannot read property 'getToken' of undefined
Android Package io.stewan.capacitor.fcm.FCMPlugin does not exist
Capacitor-community / firebase-analytics not working

Top comments (4)

Collapse
 
jrgen_lundgren_7dd1bde5c profile image
Jörgen Lundgren

Thanks for the great post!
I had integrated Push Notifications with FCM for Ionic 4 Angular many times before, but really needed this informatino in order to do it for Ionic 5 Vue. But due to Capacitor 3 is now being used when you start a new ionic app, I had to do the following changes in order to play along with Capacitor 3:
The plugin capacitor-community/fcm does not support Capacitor 3 yet - read the issue here, so that can be skipped. Instead you have to use the native capacitor/push-notifications. Then you only import like this

import { PushNotifications } from '@capacitor/push-notifications';

No mods to MainActivity.java in Android Studio is needed then.
Also to fetch the fcm token, you obviously can't use this.fcm.getToken(), but you can to like this:

      PushNotifications.requestPermissions().then(result => {
        console.log('result ' + JSON.stringify(result));
        // Initialize the registration with FCM Token
        PushNotifications.register();
      });
      // On registration we can get the token
      PushNotifications.addListener('registration', (token) => {
        console.log('Push registration success, token: ' + token.value);
        //TODO: store token server side?
      });
Enter fullscreen mode Exit fullscreen mode
Collapse
 
marcoimproda90 profile image
Marco Improda

Ciao,
Thanks for your message and update! When I had written this post, I was still with Capacitor 2 and didn't know this issue. So it's great that you decided to share this update and solution :)

Collapse
 
rizqisrijal profile image
rizqisrijal

Thank you sir for the update, can u help me with recent updates with capacitor and Vue. I've been looking anywhere but still can't figure it out. Can u make a brief tutorial sir. Thank you.

Collapse
 
bjochelle profile image
bjochelle

Thank you for this tutorial . But I have encounter a problem with push notification in foreground. I cannot receive a notification in foreground but if i close the application , everything is fine. Is there something I missed out? Your response is greatly appreciated . Thanks.