How To Add Browser Notification Using JavaScript

By Saruque Ahamed Mollick

There is a lot of methods to enable popup notification for a certain event. But all of that notifications will be in your webpage. The user will see the notification if the user is on that page.
But today I am here to tell you guys a cool JavaScript that will give notification on your browser.
In recent times to promote your blog, it’s very useful to add these push notification so that you can achieve more visitors to your website.

Popup notification using JavaScript and CSS that will hide after a certain time

 

This notification will work even the user is not on the webpage. The browser will send the user a notification.

You can use this feature as per your need, but here I will create a button.



When a user will click that button user will be asked for permissions from the web browser, and you just need to allow that button in order to receive notifications.

So without wasting time I’m gonna show you how does it work and will tell you some basic implementations.

Change the browser URL on click without loading the page in JavaScript

 

Create a JavaScript for browser push notification

below is the JavaScript Source code

You just need to put it anywhere you want to.

Or for testing, you might save it in a “.html” file or PHP file

// browser will ask for permission
<script type="text/javascript">document.addEventListener('DOMContentLoaded', function () {
  if (!Notification) {
    alert('Desktop notifications not available in your browser. Try Chromium.'); //if browser is not compatible this will occur
    return;
  }

  if (Notification.permission !== "granted")
    Notification.requestPermission();
});

function notifyMe() {
  if (Notification.permission !== "granted")
    Notification.requestPermission();
  else {
    var notification = new Notification('CodeSpeedy (Notification Title)', {
      icon: 'https://www.codespeedy.com/wp-content/themes/codespeedy/img/CodeSpeedy-Logo.png',
      body: "New Notification! Click to Check",
    });

    notification.onclick = function () {
      window.open("https://codespeedy.com");      
    };

  }

}</script>

Now to achieve your target you need to add a button so that users can click on that and javascript starts working.

Add Button

<button onclick="notifyMe()">Click me!</button>

 

notifyMe() is the JavaScript Function which is provided in the previous source code. Check the first code to clarify it.

notification.onclick = function () {
      window.open("https://codespeedy.com");      
    }

This is the onclick function for the event which is going to be occurred after clicking the notification.
window.open(“URL”)    —- In the  URL field you can place the website URL which you want your users to be driven.

Disable HTML button after clicking on it in JavaScript

 

 

Leave a Reply

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