Search code examples
javascriptandroidcordovaphonegap-plugins

Phonegap-plugin-push's on.('notification') doesn't fire


I'm trying to implement push-notification in my hybrid app, which is built with reactjs and cordova, using phonegap-plugin-push.

i have setup everything correctly (added the plugin, registered with firebase, the google-services.js file is in the right place).

i put this in my index.js file:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

// ReactDOM.render(<App />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: 

const startApp = () => {
    ReactDOM.render(
        <App />,
        document.getElementById('root')
    );
    serviceWorker.unregister();

    var push = window.PushNotification.init({
        android:{}
    });
    console.log(push);
    
    push.on('registration', function (data) {

        console.log("on registration");
        console.log(data);
    });
    
    push.on('notification', function (data) {
        // console.log("notification received");
        alert("Title:"+data.title+" Message:"+ data.message);
    });
    
    push.on('error', function (e) {
        console.log(e.message)
    });
}
    
if(!window.cordova) {
    console.log("cordova is null");
    startApp();
} else {
    document.addEventListener('deviceready', startApp, false);
}

when i run the app on android emulator, and debug it using the chrome inspect devices, i can see the on('registration') is fired and work properly. But when i try to send a notification from firebase to the device, nothing happen. This is how i compose my notification:

*Notification title(optional): title

Notification text: test noti

Notification label: test noti

*Target
App com.allen.thomas.netdi //the package name that i registered

*Scheduling
i chose "send now"

*Conversion events(optional)
didn't do anything with this

*Additional options(optional)
//left the Android "Notification Channel" field blank

//For custom data I filled in the following keys-values
title              Test Notification
body               Please work!
badge              1
content-available  1

priority: high
sound: enabled

expires: 4 weeks

then i hitted publish. But nothing happened. I don't understand what is the problem here?


Solution

  • It seems that i figure out the solution to this. All i need to do was adding these lines of code inside the on('notification) 's callback function:

    push.finish(function(){
      console.log("notification received successfully");
    })

    It solve my problem.