使用 Notifications API

Ernest Delgado
Ernest Delgado

简介

借助 Notifications API,您可以针对指定事件(无论是被动事件,例如新电子邮件、推文或日历活动,还是用户互动事件)向用户显示通知,而无论哪个标签页处于焦点状态。存在草稿规范,但目前未纳入任何标准。

只需按照以下简单步骤操作,您就可以在几分钟内实现通知:

第 1 步:检查是否支持 Notifications API

我们检查是否支持 webkitNotifications。请注意,之所以命名为 webkitNotifications,是因为它是草稿规范的一部分。最终规范将包含 notifications() 函数。

// check for notifications support
// you can omit the 'window' keyword
if (window.webkitNotifications) {
console.log("Notifications are supported!");
}
else {
console.log("Notifications are not supported for this Browser/OS version yet.");
}

第 2 步:让用户向网站授予显示通知的权限

如果我们提到的任何构造函数在用户未手动向网站授予显示通知的权限时被调用,都会抛出安全错误。 如需处理异常,您可以使用 try-catch 语句,也可以使用 checkPermission 方法达到相同的目的。

document.querySelector('#show_button').addEventListener('click', function() {
if (window.webkitNotifications.checkPermission() == 0) { // 0 is PERMISSION_ALLOWED
// function defined in step 2
window.webkitNotifications.createNotification(
    'icon.png', 'Notification Title', 'Notification content...');
} else {
window.webkitNotifications.requestPermission();
}
}, false);

如果 Web 应用没有显示通知的权限,则 requestPermission 方法将显示信息栏:

Google Chrome 中的通知权限信息栏
Google Chrome 中的通知权限信息栏。

不过,请务必记住,requestPermission 方法仅适用于由用户操作(例如鼠标或键盘事件)触发的事件处理程序,以避免出现不请自来的信息栏。在本例中,用户操作是点击 ID 为“show_button”的按钮。 如果用户从未明确点击过某个按钮或链接来触发 requestPermission,则上述代码段将永远无法正常运行。

第 3 步:附加监听器和其他操作

document.querySelector('#show_button').addEventListener('click', function() {
  if (window.webkitNotifications.checkPermission() == 0) { // 0 is PERMISSION_ALLOWED
    // function defined in step 2
    notification_test = window.webkitNotifications.createNotification(
      'icon.png', 'Notification Title', 'Notification content...');
    notification_test.ondisplay = function() { ... do something ... };
    notification_test.onclose = function() { ... do something else ... };
    notification_test.show();
  } else {
    window.webkitNotifications.requestPermission();
  }
}, false);

此时,您可能需要封装所有这些事件和操作,创建自己的通知类,以使代码更简洁,但这超出了本教程的范围。