DEV Community

Cover image for Cordova FCM-Push Notification
George Ikwegbu Chinedu
George Ikwegbu Chinedu

Posted on

Cordova FCM-Push Notification

Image From Pexels by Brett Jordan

Are you a cordova developer and trying to implement the FCM push notification but encounter errors, ok, I was once like you few hours ago from writing this article.

So, I'd like to drop what I learned on how to solve this problem. Because the plugin itself has some bugs in it (At the time of writing this article).

Table Of Contents

Creating new Cordova Project

Navigate to the Folder you want to keep this project in.

cd 'C:\georgeikwegbu\usser\Documents\GitHub\_sideProjects\'
Enter fullscreen mode Exit fullscreen mode

Then create a new folder (directory) either from the GUI or

mkdir cordovaFcm
// this creates a new folder with name cordovaFcm
cd cordovaFcm
// this changes the current working directory to the newly created one.
Enter fullscreen mode Exit fullscreen mode

Next, create a cordova app within the new directory

cordova create .
 // This creates a boilerplate of the cordova app within the current  
 // project because of the period (.) we added.
Enter fullscreen mode Exit fullscreen mode

Adding Android Platform

Once you have created the new cordova app, the next thing to do
is to add a platform.

I currently do not own a macbook (πŸ˜ͺ), so my article will be 
based on the android platform. (I'm really sorry πŸ˜₯)
Enter fullscreen mode Exit fullscreen mode
cordova platform add android
// this adds the android platform to the project
Enter fullscreen mode Exit fullscreen mode

Adding FCM plugin

We now need to add our plugin, with this, you won't need the firebase SDK, this plugin will handle everything... well yeah 😎.

cordova plugin add cordova-plugin-fcm
// Notice, I used 'fcm' and not 'FCM', as uppercase will throw an 
// error.
Enter fullscreen mode Exit fullscreen mode

Creating new Firebase Project

Break time....πŸ₯±πŸ₯±πŸ₯±,
Tired Baby Boss gif
just kidding,

ok, hope you are already familiar with Firebase, as we won't explain much about it.

  1. Go to firebase: https://firebase.google.com/
  2. Create an account if you don't have any, or go to console if you have and logged into it.
  3. Click on 'Add Project'
  4. Enter the project name, most suitable will be the actual project name.
  5. Accept the next slide.
  6. Choose or create a new account (I went with the default account).
  7. Create the project.
  8. Scroll down (on the side navigation bar, to the (at the time of writing this article) Engage section, and select the cloud messaging).
  9. Select the android icon, and continue.
  10. The next slide, will ask you to enter the android package name, this name must rhyme with the ID or Package name your have in you config.xml file (If you can, read the next section about config.xml).
<widget id="com.fcmpushnotification.georgeikwegbu" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0"> 
Enter fullscreen mode Exit fullscreen mode
It will be in reverse domain name eg. 'mrbrowny.dev.to' will be 
'to.dev.mrbrowny'

And the 'App nickname', will be the value you have in your 'name 
tag' within your config.xml file.

Please leave the 'Debug signing certificate SHA-1 (optional)' 
empty, as it's beyond this article, then click on the 'Register 
app'
Enter fullscreen mode Exit fullscreen mode
  1. After clicking on the 'Register app', the accordion, will bring out your 'google-services.json' for your app, download it.

Editing Config.xml file

Nothing much to do here, as you should know what and how you wish your app to look and work. But, key things to take into considerations are:

  1. The Package name, which is what you will provide on the firebase console.

  2. The name of the project, which is found within the 'name' tag.

  3. The description is left for you to decide what that will be πŸ˜‰.

Adding the google-services.json File

google-services json file

The google-services.json file you downloaded, is to be added to:

  1. The root of the cordova project
C:\georgeikwegbu\usser\Documents\GitHub\_sideProjects\cordova_fcm\
Enter fullscreen mode Exit fullscreen mode
  1. The 'platform\android\app\' of the platform
C:\georgeikwegbu\usser\Documents\GitHub\_sideProjects\cordova_fcm\platforms\android\app\
Enter fullscreen mode Exit fullscreen mode

Correcting Plugin Bugs in Files

The 'cordova-plugin-fcm' has a bug init (as of the time of writing this article), so we would try and resolve those now:

Happy Gif

1. Change the following things:

firebase-core:+
firebase-messaging:+

//to 

firebase-core:16.0.3
firebase-messaging:17.6.0
Enter fullscreen mode Exit fullscreen mode

in


C:\georgeikwegbu\usser\Documents\GitHub\_sideProjects\cordova_fcm\platforms\android\app\build.gradle

Enter fullscreen mode Exit fullscreen mode

and

C:\georgeikwegbu\usser\Documents\GitHub\_sideProjects\cordova_fcm\platforms\android\project.properties
Enter fullscreen mode Exit fullscreen mode

2. Change the following things:

// From
var strings = fs.readFileSync("platforms/android/res/values/strings.xml").toString();
// to
var strings = fs.readFileSync("platforms/android/app/src/main/res/values/strings.xml").toString();

// AND

// From
fs.writeFileSync("platforms/android/res/values/strings.xml", strings);

// to
fs.writeFileSync("platforms/android/app/src/main/res/values/strings.xml", strings);
Enter fullscreen mode Exit fullscreen mode

in

C:\georgeikwegbu\usser\Documents\GitHub\_sideProjects\cordova_fcm\plugins\cordova-plugin-fcm\scripts\fcm_config_files_process.js
Enter fullscreen mode Exit fullscreen mode

Ok..... we done 😎😎😎😎

Congratulations gif

Running getToken Function inside Device Ready

I will be leaving the link to the github repo of the plugin itself, but all codes should be run after the device ready, so place it within the onDeviceReady function:

onDeviceReady: function() {
        this.receivedEvent('deviceready');
            FCMPlugin.getToken(function(token) {
            //this is the FCM token which can be used
            //to send notification to specific device 
            console.log('George here is the token', token);
            alert(token)
            prompt('', token)
            //FCMPlugin.onNotification( onNotificationCallback(data), successCallback(msg), errorCallback(err) )
            //Here you define your application behaviour based on the notification data.
            FCMPlugin.onNotification(function(data) {
                console.log(data);
                //data.wasTapped == true means in Background :  Notification was received on device tray and tapped by the user.
                //data.wasTapped == false means in foreground :  Notification was received in foreground. Maybe the user needs to be notified.
                if (data.wasTapped) {
                    //Notification was received on device tray and tapped by the user.
                    alert(JSON.stringify(data));
                } else {
                    //Notification was received in foreground. Maybe the user needs to be notified.
                    alert(JSON.stringify(data));
                }
            });
        });
    },

// Since you'll need the token, to try and send notification from the firebase, I used the 
// 'prompt()', so you could copy the token from your phone, look for a way to get it to the 
// firebase website πŸ˜‹
Enter fullscreen mode Exit fullscreen mode

Link to the cordova-plugin-fcm github

Top comments (1)

Collapse
 
sewmer profile image
sewmer

I am accepting this error in run browser
Error: exec proxy not found for :: FCMPlugin :: ready
FCMPlugin.js:40 FCMPlugin Ready ERROR
FCMPlugin.js:4 FCMPlugin.js: is created
cordova.js:989 Error: exec proxy not found for :: FCMPlugin :: getToken

And when I try to build android I get this error
Configure project :app
google-services plugin could not detect any version for com.google.android.gms or com.google.firebase, default version: 9.0.0 will be used.
please apply google-services plugin at the bottom of the build file.

FAILURE: Build completed with 2 failures.

1: Task failed with an exception.

  • Where:
    Script 'C:\Users\User\push\platforms\android\cordova-plugin-fcm\rappidex-FCMPlugin.gradle' line: 13

  • What went wrong:
    A problem occurred evaluating script.

    Failed to apply plugin class 'com.google.gms.googleservices.GoogleServicesPlugin'.
    Configuration with name 'compile' not found.

  • Try:

    Run with --stacktrace option to get the stack trace.
    Run with --info or --debug option to get more log output.

    Run with --scan to get full insights.

2: Task failed with an exception.

  • What went wrong:
    A problem occurred configuring project ':app'.

    com.android.builder.errors.EvalIssueException: compileSdkVersion is not specified. Please add it to build.gradle

  • Try:

    Run with --stacktrace option to get the stack trace.
    Run with --info or --debug option to get more log output.

    Run with --scan to get full insights.

  • Get more help at help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See docs.gradle.org/7.6/userguide/comm...

BUILD FAILED in 1m 1s
Command failed with exit code 1: C:\Users\User\push\platforms\android\gradlew -b C:\Users\User\push\platforms\android\build.gradle cdvBuildDebug
PS C:\Users\User\push>