Notification: requestPermission() 静态方法
Notification 接口的 requestPermission() 静态方法用于请求当前源显示通知的权限。
该方法返回一个 Promise,该 Promise 以一个字符串解析,指示权限是已授予还是已被拒绝。
语法
js
Notification.requestPermission()
// Deprecated syntax using a callback
Notification.requestPermission(callback)
参数
callback可选 已弃用-
一个可选的回调函数,它会接收权限值作为参数。已弃用,应优先使用
Promise的返回值。
返回值
一个 Promise,它解析为一个字符串,表示用户选择的权限。此字符串的可能值为:
granted-
用户已明确授予当前源显示系统通知的权限。
denied-
用户已明确拒绝当前源显示系统通知的权限。
default-
用户决定未知;在这种情况下,应用程序将像权限被
denied一样处理。
该方法的已弃用版本返回 undefined。
示例
假设以下基本 HTML
html
<button>Notify me!</button>
发送通知的方法如下——这里我们提供了一套相当冗长且完整的代码,您可以使用它来首先检查通知是否受支持,然后检查当前源是否已获得发送通知的权限,如果需要则请求权限,然后再发送通知。
请注意,请求应在响应用户交互时发出:下面,该方法在 click 事件处理程序中调用。
js
document.querySelector("button").addEventListener("click", notifyMe);
function notifyMe() {
if (!("Notification" in window)) {
// Check if the browser supports notifications
alert("This browser does not support desktop notification");
} else if (Notification.permission === "granted") {
// Check whether notification permissions have already been granted;
// if so, create a notification
const notification = new Notification("Hi there!");
// …
} else if (Notification.permission !== "denied") {
// We need to ask the user for permission
Notification.requestPermission().then((permission) => {
// If the user accepts, let's create a notification
if (permission === "granted") {
const notification = new Notification("Hi there!");
// …
}
});
}
// At last, if the user has denied notifications, and you
// want to be respectful there is no need to bother them anymore.
}
我们不再在此页面上显示实时示例,因为 Chrome 和 Firefox 不再允许从跨源 <iframe> 请求通知权限,其他浏览器也将效仿。要查看实际示例,请查看我们的 待办事项列表示例(另请参阅 实时运行的应用)。
规范
| 规范 |
|---|
| Notifications API # dom-notification-requestpermission |
浏览器兼容性
加载中…