Push Notifications are features that allow a website to show instant messages to the user on a desktop. Push Notifications are very handy when it comes to communicating with the user as these notifications are easy to implement and understand and a developer can allow a user to perform multiple actions on these notifications.
The code for showing the notifications on desktop is in vanilla JS and doesn’t require any external library or dependency. The only thing it requires is a live server along with an IP address that has HTTPS in the beginning. (i.e. it should be secured by HTTPS. Eg:- https://www.google.com/). To ease the requirements a bit, the code can be simply deployed on any deployment site like Github, Heroku, Firebase, GCP, etc. All these deployment engines always give a secure HTTPS link on deployment.
Now, we make a simple JS file (here a HTML file with the below code inside the <script> tag or embedded JS) and code our notification function. Walking through the code:-
· The first line of the code introduces a function that contains a constant of type Notification.
· This notification type contains two major things, the title (“New message..”) and the body of the notification. This body contains the description that you want to give as a notification and an image that gets displayed alongside the description.
· The following if construct is used to obtain permission from the user as in to allow our application to push notification on the user’s desktop.
· Now, if the permission is granted the showNotification function is called and the notification with the title, body, and image is showed at the bottom right to the user.
· If the user denies the permission, the code will once again ask for the permission and checks if the user has given his nod for the same or not.
Now we just need to deploy the code on a service or run the code on the server giving us HTTPS link and we’ll get a prompt asking for permission and subsequently, we’ll get the notification of the body we have made above. The user must compulsorily allow the website to show notifications. Further, the showNotification function can be called anywhere in the code, and hence we can make use of this push notification with any click of a button or any other interaction, etc. For the ease of understanding, the full code of the file having the notification is as:-
Although, there are many external API’s and many other interactive ways to show push notifications to the user but this the basic way and in plain vanilla JS and hence it may help in one way or the other.