Send Web notification using GCM Google Cloud Messaging System

suggest change

Google 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.

  1. npm install node-gcm
  2. npm install express socket.io
  3. The sender id and server key used to come from the Google console. FCM uses a Firebase project instead.
  4. 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:

  1. It serves index.html.
  2. It listens for a Socket.IO connection from that page.
  3. The page emits new_user with a registration token from the browser push API. See the Notifications API.
  4. node-gcm sends 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents