ttmind

Main Navigation

ttmind
  • jim-jams
  • Tech
  • Positive
Login

Login

Facebook Google

OR

Remember me Forgot password?

Don't have account? Signup here.

Sort by Categorys

.Net

PHP

Java

JavaScript

Database

Server

Client Side

Tools

Artificial Intelligence

Cloud

Hybrid Development

Event

Smart City

Education

Security

Scrum

Digital Marketing

APP Development

Business

Internet

Simulation

Art

Network

Microservices

Architecture

Technology

Leadership

    Top Articles

  • How Does Social Media Bring People Together?
    TTMind Author
  • How to read appSettings JSON from Class Library in ASP.NET Core
    Anil Shrestha
  • Printing Support In Asp.Net Core
    TTMind Author
  • HOW TO EXTRACT TEXT FROM IMAGE USING JAVASCRIPT (OCR with Tesseract.js)?
    Prakash Pokhrel
  • Images Upload REST API using ASP.NET Core
    Prakash Pokhrel
  • Related Topic

  • Cordova Upload Images using File Transfer Plugin and .Net core WebAPI
  • How to get Current user Location from device in ionic Cordova?
  • Could not find gradle wrapper within Android SDK. Might need to update your Android SDK. Looked here: Local\Android\Sdk\tools\templates\gradle\wrapper
  • What is ionic? How to start mobile app development with ionic?
  • How to make the two side-menu in ionic?
  • Tech
  • About Us
  • Contact Us
  • TechHelp
  • PositiveHelp
  • Jim-Jams Help
  • Terms & Conditions

© Copyright ttmind.com

Main Content

Firebase Cloud Messaging (FCM) using Cordova FCM Plugin

Hybrid Development Cordova about 7 years ago || 7/26/2018 || 9.3 K View

  • Hide

Firebase Cloud Messaging (FCM) is the latest push notification service of Google. In this article, we will see how to integrate FCM in a Cordova project and send the notification to devices.

Create Cordova Project:

  • "cordova create push com.test.pushnotification push"

Setting Up FireBase:

  • Firstly, we must create an Android app in Firebase. Login to https://console.firebase.google.com with your google account.
  • Select “Add Project”.

  • Provide project name.
  • Click on Create Project.

  • Click on continue. 

  • Select "Add Firebase to your Android App".

  • Provide your Android package name, here my package name is “com.test.pushnotification” and click on Register app.

  • Download "google-service.json".

And place "google-service.json" in to your project folder. In my case, my project folder is "D:\push"

  • Now, back to browser click on next.

  • Again, click on next.

  • Now, back to our command prompt. And add fcm Plugin by using following plugin.
  • "cordova plugin add cordova-plugin-fcm"

Now, change some lines in your “fcm_config_files_process.js”. You can find it on “plugin\corodva-plugin-fcm\scripts”. In my case, it is located at “D:\push\plugins\cordova-plugin-fcm\scripts”.

// change Line 58
fs.writeFileSync("platforms/android/google-services.json", contents);
		
// to
fs.writeFileSync("platforms/android/app/google-services.json", contents);

// Also

//change Line 61
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
//change Line 78
fs.writeFileSync("platforms/android/res/values/strings.xml", strings);
//to
fs.writeFileSync("./platforms/android/app/src/main/res/values/strings.xml", strings);
  • Next, we have to write some client-side code to get Device token for push notifications. My Index.html is as follow:
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">
        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <title>Push Notification Test</title>
    </head>
    <body>
	<div id="divToken"></div>
        <div class="app">
            <h1>Apache Cordova</h1>
            <div id="deviceready" class="blink">
                <p class="event listening">Connecting to Device</p>
                <p class="event received">Device is Ready</p>
            </div>
        </div>
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
    </body>
</html>
  • Final Index.js is as follow:
var app = {
    initialize: function() {
        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    },
onDeviceReady: function() {
        this.receivedEvent('deviceready');
    },
receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');
		FCMPlugin.onTokenRefresh(function(token){
            alert( token );
			var div = document.getElementById('divToken');
            div.innerHTML += token;
        });
        FCMPlugin.onNotification(
            function(data){
              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) );
              }
            },
            function(msg){
              console.log('onNotification callback successfully registered: ' + msg);
            },
            function(err){
              console.log('Error registering onNotification callback: ' + err);
            }
          );

        console.log('Received Event: ' + id);
    }
};
app.initialize();
  • Now, go your command prompt and add platform “cordova platform add android”

  • Now, let’s run our app.command to run app is as 
cordova run android

  • Now, you can see FCM Device token on Android.

  •  And  also “Congratulations, you've successfully added Firebase to your app!” message on browser.

  • Click on continue on browser. You can see one device registered on following screenshots.

  • Scroll down and click on get started of push notification. 

  • Click on send your first message.

  • Type your message and select your app.

 

And click on "send Message".

Click on "Send".

  • Then, you can see following interface.

  •  After few second you can see push notification on your mobile device.

Summary:

In this article, we learned how to get firebase push notification token and send push notification using cordova fcm plugin.

Happy Coding!!!

  • 3
  • 0
  • 1
    • Facebook
    • Twitter
    • Google +
    • LinkedIn

About author

Prakash Pokhrel

Prakash Pokhrel

https://np.linkedin.com/in/prakash-pokhrel-42a699a2

Reset Your Password
Enter your email address that you used to register. We'll send you an email with your username and a link to reset your password.

Quick Survey