Implement Simple Web Push Notifications in <5 Min πŸ•¬

1. Overview

Web Push Notifications can be complicated to implement. In this post you will see how to create a very simple version of a push notification.

Requirements

  • HTTPs
  • A modern Browser (not Internet Explorer)
  • Allow Browser Notification
  • JavaScript

2. The web app with push notify

We need three files for our simple website to show a push notification. First the website (html) itself, a javascript file that will execute the notification and a supplementary png file that will be shown in the browser push notification.

Create three files and copy the code. Upload the files to your https web server of your choice.

The html file only contains a textarea for our message body and a button to trigger a message push.

<html>
<body>
<form action="#">
	<textarea></textarea>
	<button>Notify!</button>
	
</form>
<script src="notification.js"></script>
</body>
</html>

In the javascript file the code checks whether our browser supports push notifications at all (‘Notification’ in Window). Second if permissions for this site to show push notifications are not available yet, the script will request them. If the said permissions are there a new Notification object will be created.

Also, our message object will have a onclick handler, so we know when the user has clicked on our message.

document.querySelector('button').addEventListener('click', ev => {
	ev.preventDefault();
	if (('Notification' in Window)) 
		throw new Error ('No Push Available');
	Notification.requestPermission(permission=> {
			if (permission !== 'granted')
			{
				alert('No Permission');
				return
			}
			const msg = new Notification('Message',{ 
				body:document
				.querySelector('textarea')
				.value, icon:'info.png'
			});
			msg.onclick = ev => alert ('Message clicked!');
	});
});

The png file can be downloaded >here< (right-click and save)

3. The result

Our result is quite modest, but considering the minimal effort, it can already be implemented in many applications.

4. Conclusion

It’s very easy to set up the basic version of push notifications. They will even show when your browser is minimized or a different tab is active.

However, if you want to have “real” push notifications like on your mobile phone where the user does not have to open the website / app in order to receive notifications, you will need more configuration. How to do that we will see next.

Leave a Reply

Your email address will not be published. Required fields are marked *