MOCKSTACKS
EN
Questions And Answers

More Tutorials









NodeJS Push notifications

Web notification


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)

Conclusion

In this page (written and validated by ) you learned about NodeJS Push notifications . What's Next? If you are interested in completing NodeJS tutorial, we encourage you simply to start here: NodeJS Tutorial.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.