0

I am trying to get permission for notification from my user like this

enter image description here

However, This code doesn't send request for permission

function notifyMe() {
  // Let's check if the browser supports notifications
  if (!("Notification" in window)) {
    alert("This browser does not support desktop notification");
  }

  // Let's check if the user is okay to get some notification
  else if (Notification.permission === "granted") {
    // If it's okay let's create a notification
    var notification = new Notification("Hi there!");
  }

  // Otherwise, we need to ask the user for permission
  // Note, Chrome does not implement the permission static property
  // So we have to check for NOT 'denied' instead of 'default'
  else if (Notification.permission !== 'denied') {
    Notification.requestPermission(function (permission) {

      // Whatever the user answers, we make sure we store the information
      if(!('permission' in Notification)) {
        Notification.permission = permission;
      }

      // If the user is okay, let's create a notification
      if (permission === "granted") {
        var notification = new Notification("Hi there!");
      }
    });
  } else {
    alert(`Permission is ${Notification.permission}`);
  }
}

just says "Permission is denied"

Is it because I'm using codepen?

JJJohn
  • 915
  • 8
  • 26

1 Answers1

2

It's not because you are using CodePen - not directly. It's because you are trying to request Notifications permission from a cross-origin iframe, and Chrome and Firefox (and probably other browsers) do not allow that, as stated in the docs:

We no longer show a live sample on this page, as Chrome and Firefox no longer allow notification permissions to be requested from cross-origin <iframe>s, with other browsers to follow.

To prove that it's a cross-origin browser, you can see in the Dev Tools that the iframe's src attribute on CodePen points to https://cdpn.io/ and the iframe itself is embedded on the https://codepen.io/ domain - that's a cross-origin iframe.

To make it work on CodePen, you can try doing it that way. It basically omits the Notification.permission !== 'denied' check.

But in general, your code will work fine in the real browser. You can confirm that by pasting your function in the browser's console and then running it.

Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38