Luuk Faasse
Luuk Faasse

Reputation: 33

Detect browser push notifications are enabled and display alert

I have enabled push-notifications for my website. When a user clicks a link on my site, a request will be send to the browser and the user have to click allow or disallow. Is there a way to detect if notifications are turned on and display an javascript alert box with the message that push notifications are successfully enabled? This may only display when the user allows notifications in his/her browser. Example:

  1. The user clicks the link.
  2. The user clicks allow in his/her browser.
  3. There will be an alert with the message: "Successfully enabled"

Another example:

  1. The user clicks the link.
  2. The user clicks disallow in his/her browser.
  3. There will be an alert with the message: "Error with enabling"

Does anyone understand me? If there are more questions, please write a comment, I'll add more info. Thanks for helping me!

Upvotes: 3

Views: 3273

Answers (1)

Below the Radar
Below the Radar

Reputation: 7635

Notification.requestPermission() is a Promise, that resolve with the permission chosen by the user.

https://developer.mozilla.org/en-US/docs/Web/API/Notification/requestPermission

var myLink = document.getElementById("myLink");

myLink.addEventListener("click", function() {
   Notification.requestPermission().then(function(result) {
      if (result === 'denied' || result === 'default' ) {
        alert("Error with enabling");
        return;
      }
      alert("Succesfully enabled");
    });
});
<a id="myLink" href="#">Link</a>

Upvotes: 4

Related Questions