Node.js Web notification


Example

First, you will need to install Push.js module.

$ npm install push.js --save

Or import it to your front-end app through CDN

<script src="./push.min.js"></script> <!-- CDN link -->

After you are done with that, you should be good to go. This is how it should look like if u wanna make simple notification:

Push.create('Hello World!')

I will assume that you know how to setup Socket.io with your app. Here is some code example of my backend app with express:

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(80);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
  
  socket.emit('pushNotification', { success: true, msg: 'hello' });

});

After your server is all set up, you should be able to move on to front-end stuff. Now all we have to do is import Socket.io CDN and add this code to my index.html file:

<script src="../socket.io.js"></script> <!-- CDN link -->
<script>
  var socket = io.connect('http://localhost');
  socket.on('pushNotification', function (data) {
    console.log(data);
    Push.create("Hello world!", {
        body: data.msg, //this should print "hello"
        icon: '/icon.png',
        timeout: 4000,
        onClick: function () {
            window.focus();
            this.close();
        }
    });
  });
</script>

There you go, now you should be able to display your notification, this also works on any Android device, and if u wanna use Firebase cloud messaging, you can use it with this module, Here is link for that example written by Nick (creator of Push.js)