Send Web notification using GCM Google Cloud Messaging System
suggest changeGoogle Cloud Messaging is shut down. Firebase Cloud Messaging replaced it. node-gcm and a manifest gcm_sender_id talk to the old service, so this sample will not deliver notifications on a new project. The shape below is how that old server was wired.
npm install node-gcmnpm install express socket.io- The sender id and server key used to come from the Google console. FCM uses a Firebase project instead.
- Open a code editor and add the following code:
'use strict';
const express = require('express');
const app = express();
const gcm = require('node-gcm');
const sender = new gcm.Sender('server key');
const regTokens = [];
const message = new gcm.Message({
data: {
key1: 'msg1'
}
});
app.use(express.static('public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
const server = app.listen(3000);
const io = require('socket.io')(server);
io.on('connection', socket => {
console.log('we have a new connection ...');
socket.on('new_user', (reg_id) => {
if (regTokens.indexOf(reg_id) === -1) {
regTokens.push(reg_id);
sender.send(message, {
registrationTokens: regTokens
}, (err, response) => {
if (err) console.error('err', err);
else console.log(response);
});
}
});
});
Socket.IO attaches to the HTTP server listen returns. It does not need a separate Express plugin.
A web app manifest can name the old sender id. Link this file from the page. The name and folder are yours. FCM no longer uses gcm_sender_id.
{
"name": "Application Name",
"gcm_sender_id": "GCM Project ID"
}
What the server does:
- It serves
index.html. - It listens for a Socket.IO
connectionfrom that page. - The page emits
new_userwith a registration token from the browser push API. See the Notifications API. node-gcmsends that token a message. Showing it in the browser is the service worker's job. See Service Worker API.
The page that obtains the token and the service worker are not in this example.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents