Ad

How Do I Add A URL To A Notification When Using The Notification API?

- 1 answer

I have created a simple notification in a standard index.html file by adding the following script to the bottom of the page. However, my goal is to add a URL to the notification, so that when the user clicks on the notification they are taken to a specific URL (window.open). I know this can be done as when searching for an answer on Google many sites have notifications that when clicked navigate to a different page or website. Nevertheless, I have not found a solution that I can get working. Any help welcome.

    Notification.requestPermission();
Notification.requestPermission((permission) => {
  switch (permission) {
    case 'granted': {
      console.log('Now we can send notifications!');
      doNotify();
      break;
    }
    case 'denied': {
      console.log('User close the request pop-up!')
    }
  }
});

function doNotify(){
        const title = "Test notification";
        const img = "https://via.placeholder.com/600x400";
        const text = Lorem ipsum;

        const options = {
            body: text,
            icon: "https://via.placeholder.com/600x400",
            data: {
            },
            vibrate: [200, 100, 200],
            tag: "new-product",
            image: img,
            badge: "https://via.placeholder.com/128x128",
        };

        notification.onclick = function(event) {
          event.preventDefault(); // prevent the browser from focusing the Notification's tab
          window.open('http://www.mozilla.org', '_blank');
        }

      navigator.serviceWorker.ready.then(function(serviceWorker) {
        serviceWorker.showNotification(title, options);
      });

    // setTimeout( n.close.bind(n), 9000); //close notification after 3 seconds
}
Ad

Answer

You missed a line that is very important for this to work. Define a notification with the Notification constructor in which you enter the title and options variables.

function doNotify() {

  const title = "Test notification";
  const img = "https://via.placeholder.com/600x400";
  const text = "Lorem ipsum";

  const options = {
    body: text,
    icon: "https://via.placeholder.com/600x400",
    data: {},
    vibrate: [200, 100, 200],
    tag: "new-product",
    image: img,
    badge: "https://via.placeholder.com/128x128",
  };

  // Add this line.
  const notification = new Notification(title, options);

  notification.onclick = function(event) {
    event.preventDefault(); // prevent the browser from focusing the Notification's tab
    window.open('http://www.mozilla.org', '_blank');
  }

  navigator.serviceWorker.ready.then(function(serviceWorker) {
    serviceWorker.showNotification(title, options);
  });

}
Ad
source: stackoverflow.com
Ad