Cordova FCM-Push Notification
Tags: cordova, javassript, firebase
Published: 2021-06-20 22:12:47

Image From Pexels by [Brett Jordan](https://www.pexels.com/@brettjordan)


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](#newProject)
  * [Adding Android Platform](#platform)
  * [Adding FCM plugin](#plugin)
  * [Creating new Firebase Project](#firebase)
  * [Editing Config.xml file](#config)
  * [Adding the google-services.json File](#file)
  * [Correcting Plugin Bugs in Files](#bug)
  * [Running getToken Function inside Device Ready](#fun)

### Creating new Cordova Project <a name="newProject"></a>

   Navigate to the Folder you want to keep this project in.
```javascript
cd 'C:\georgeikwegbu\usser\Documents\GitHub\_sideProjects\'
```

   Then create a new folder (directory) either from the GUI or 
```javascript
mkdir cordovaFcm
// this creates a new folder with name cordovaFcm
cd cordovaFcm
// this changes the current working directory to the newly created one.
```

  Next, create a cordova app within the new directory

```javascript
cordova create .
 // This creates a boilerplate of the cordova app within the current  
 // project because of the period (.) we added.
```

### Adding Android Platform <a name="platform"></a>
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 😥)

```javascript
cordova platform add android
// this adds the android platform to the project
```

### Adding FCM plugin <a name="plugin"></a>
We now need to add our plugin, with this, you won't need the firebase SDK, this plugin will handle everything... well yeah 😎.

```javascript
cordova plugin add cordova-plugin-fcm
// Notice, I used 'fcm' and not 'FCM', as uppercase will throw an 
// error.
```

### Creating new Firebase Project <a name="firebase"></a>
Break time....🥱🥱🥱, 
![Tired Baby Boss gif](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z579hkk80u2krsx195qa.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).
```js
<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"> 
```
##
    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'

11. After clicking on the 'Register app', the accordion, will bring out your 'google-services.json' for your app, download it.
    

### Editing Config.xml file <a name="config"></a>
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 <a name="file"></a>

![google-services json file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h7i96w8h1bhi5f6orqyq.PNG)

The google-services.json file you downloaded, is to be added to:
1. The root of the cordova project
```js
C:\georgeikwegbu\usser\Documents\GitHub\_sideProjects\cordova_fcm\
```

2. The 'platform\android\app\' of the platform
```js
C:\georgeikwegbu\usser\Documents\GitHub\_sideProjects\cordova_fcm\platforms\android\app\
```

### Correcting Plugin Bugs in Files <a name="bug"></a>
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qtvqm5iaffae9jt2kynd.gif)

### 1. Change the following things:
```js
firebase-core:+
firebase-messaging:+

//to 

firebase-core:16.0.3
firebase-messaging:17.6.0
```
#### in
 ```js
 
C:\georgeikwegbu\usser\Documents\GitHub\_sideProjects\cordova_fcm\platforms\android\app\build.gradle

``` 
#### and
```js
C:\georgeikwegbu\usser\Documents\GitHub\_sideProjects\cordova_fcm\platforms\android\project.properties
```
 
### 2. Change the following things:
```js
// 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);
```

#### in

```js
C:\georgeikwegbu\usser\Documents\GitHub\_sideProjects\cordova_fcm\plugins\cordova-plugin-fcm\scripts\fcm_config_files_process.js
```

## Ok..... we done 😎😎😎😎
![Congratulations gif](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rktqjxhelvgoeru7fbk6.gif)

### Running getToken Function inside Device Ready <a name="fun"></a>
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:

```js
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 😋
```

## [Link to the cordova-plugin-fcm github](https://github.com/fechanique/cordova-plugin-fcm)