How do we display browser notifications from a web application?
In this blog, I will discuss how to display browser notifications from the web application. You can push notifications for event reminders, message information, etc.
Browser desktop notification system
Using this, you can push notifications for event reminders and message information like WhatsApp to desktop users in realtime from your web project. Very few lines of JavaScript code are needed.
Step 1 - Show Permission for Notification
Add the below JavaSscript code in the webpage.
- document.addEventListener('DOMContentLoaded', function() {
- if (Notification.permission !== "granted")
- {
- Notification.requestPermission();
- }
- });
Notification.requestPermission() will give an alert for notification permission.
Step 2 - Custom Notification function
- function customnotify(title,desc,url)
- {
-
- if (Notification.permission !== "granted")
- {
- Notification.requestPermission();
- }
- else
- {
- var notification = new Notification(title, {
- icon:'http://Your_Website.com/logo.png',
- body: desc,
- });
-
-
- notification.onclick = function () {
- window.open(url);
- };
-
-
- notification.onclose = function () {
- console.log('Notification closed');
- };
-
- }
- }
Now, the notification is set up on a web page. You can call any notification from the webpage by just calling the customnotify function.
We can call this function like this:
customnotify('Bhavdip Talaviya','enter your description hear','http://www.bhavdip.somee.com')
Thanks for reading.