Note: Safari still uses the callback syntax to get the permission. Read Using the Notifications API for a good example of how to feature detect this and run code as appropriate.
The requestPermission()
method of the Notification
interface requests permission from the user for the current origin to display notifications.
Notification.requestPermission()
Notification.requestPermission(callback)
A Promise
that resolves to a string with the permission picked by the user. Possible values for this string are:
Assume this basic HTML:
<button onclick="notifyMe()">Notify me!</button>
It's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification.
function notifyMe() {
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
} else if (Notification.permission === "granted") {
const notification = new Notification("Hi there!");
} else if (Notification.permission !== "denied") {
Notification.requestPermission().then((permission) => {
if (permission === "granted") {
const notification = new Notification("Hi there!");
}
});
}
}
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 see an example in action, check out our To-do list example (also see the app running live).
Note: In the above example we spawn notifications in response to a user gesture (clicking a button). This is not only best practice — you should not be spamming users with notifications they didn't agree to — but going forward browsers will explicitly disallow notifications not triggered in response to a user gesture. Firefox is already doing this from version 72, for example.