Such Example is knowing wide spreading among PWAs (Progressive Web Applications) and in this example we’re going to send a simple Backend like notification using NodeJS and ES6
npm install node-gcm
npm install socket.io
'use strict';
const express = require('express');
const app = express();
const gcm = require('node-gcm');
app.io = require('socket.io')();
// [*] Configuring our GCM Channel.
const sender = new gcm.Sender('Project Secret');
const regTokens = [];
let message = new gcm.Message({
data: {
key1: 'msg1'
}
});
// [*] Configuring our static files.
app.use(express.static('public/'));
// [*] Configuring Routes.
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
// [*] Configuring our Socket Connection.
app.io.on('connection', socket => {
console.log('we have a new connection ...');
socket.on('new_user', (reg_id) => {
// [*] Adding our user notification registration token to our list typically hided in a secret place.
if (regTokens.indexOf(reg_id) === -1) {
regTokens.push(reg_id);
// [*] Sending our push messages
sender.send(message, {
registrationTokens: regTokens
}, (err, response) => {
if (err) console.error('err', err);
else console.log(response);
});
}
})
});
module.exports = app
PS : I’m using here a special hack in order to make Socket.io works with Express because simply it doesn’t work outside of the box.
Now Create a .json file and name it : Manifest.json, open it and past the following :
{
"name": "Application Name",
"gcm_sender_id": "GCM Project ID"
}
Close it and save in your application ROOT directory.
PS : the Manifest.json file needs to be in root directory or it won’t work.
In the code above I’m doing the following :
This is from NodeJS point of view. in other examples I will show how we can send custom data, icons ..etc in our push message.
PS : you can find the full working demo over here.