--- title: notification slug: Web/API/notification tags: - API - 参考 - 通知 translation_of: Web/API/Notification ---
Notifications API 的通知接口用于向用户配置和显示桌面通知。
let notification = new Notification(title, options)
title
options
{{optional_inline}}dir
: 文字的方向;它的值可以是 auto(自动)
, ltr(从左到右)
, or rtl
(从右到左)lang
: 指定通知中所使用的语言。这个字符串必须在 BCP 47 language tag 文档中是有效的。body
: 通知中额外显示的字符串tag
: 赋予通知一个ID,以便在必要的时候对通知进行刷新、替换或移除。icon
: 一个图片的URL,将被用于显示通知的图标。这些属性仅在 Notification
对象上有效。
denied
(用户拒绝了通知的显示), granted
(用户允许了通知的显示), 或 default
(因为不知道用户的选择,所以浏览器的行为与 denied 时相同).这些属性仅在 Notification
的实例中有效。
这些方法仅在 Notification
对象中有效。
这些方法仅在 Notification
实例或其 prototype
中有效。
Notification
对象继承自 {{domxref("EventTarget")}} 接口。
{{page("/en-US/docs/Web/API/EventTarget","Methods")}}
假定有如下 HTML:
<button onclick="notifyMe()">Notify me!</button>
接下来发送一条通知:
function notifyMe() { // 先检查浏览器是否支持 if (!("Notification" in window)) { alert("This browser does not support desktop notification"); } // 检查用户是否同意接受通知 else if (Notification.permission === "granted") { // If it's okay let's create a notification var notification = new Notification("Hi there!"); } // 否则我们需要向用户获取权限 else if (Notification.permission !== "denied") { Notification.requestPermission().then(function (permission) { // 如果用户接受权限,我们就可以发起一条消息 if (permission === "granted") { var notification = new Notification("Hi there!"); } }); } // 最后,如果执行到这里,说明用户已经拒绝对相关通知进行授权 // 出于尊重,我们不应该再打扰他们了 }
{{ EmbedLiveSample('Example', '100%', 30) }}
规范 | 状态 | 备注 |
---|---|---|
{{SpecName('Web Notifications')}} | {{Spec2('Web Notifications')}} | Initial specification. |
当你要在开放 web 应用中使用通知时,请确保将 desktop-notification
权限添加到你的 manifest 文件中。通知可以被用于任何权限级别,hosted 或更高。
"permissions": {
"desktop-notification":{}
}