Notifications API 使用入门

在此 Codelab 中,您将使用 Notifications API 的基本功能来执行以下操作:

  • 请求发送通知的权限
  • 发送通知
  • 尝试使用通知选项

Browser Support

  • Chrome: 20.
  • Edge: 14.
  • Firefox: 22.
  • Safari: 7.

Source

熟悉起始应用及其代码

首先,在新的 Chrome 标签页中查看实时应用:

  1. 按 `Control+Shift+J`(在 Mac 上,按 `Command+Option+J`)打开开发者工具。 点击控制台标签页。

    您应该会在控制台中看到以下消息:

    Notification permission is default
    

    如果您不知道这意味着什么,请不要担心;很快一切都会揭晓!

  2. 点击实时应用中的按钮:请求发送通知的权限发送通知

    控制台会输出来自几个函数桩的“TODO”消息:requestPermissionsendNotification。以下是您将在本 Codelab 中实现的函数。

现在,我们来看一下示例应用的代码。 打开 public/index.js 并查看现有代码的一些重要部分:

  • showPermission 函数使用 Notifications API 获取网站的当前权限状态,并将其记录到控制台:

    // Print current permission state to console;
    // update onscreen message.
    function showPermission() {
      let permission = Notification.permission;
      console.log('Notification permission is ' + permission);
      let p = document.getElementById('permission');
      p.textContent = 'Notification permission is ' + permission;
    }
    

    在请求权限之前,权限状态为 default。在 default 权限状态下,网站必须先请求并获得权限,然后才能发送通知。

  • requestPermission 函数是一个桩:

    // Use the Notification API to request permission to send notifications.
    function requestPermission() {
      console.log('TODO: Implement requestPermission()');
    }
    

    您将在下一步中实现此函数。

  • sendNotification 函数是一个桩:

    // Use the Notification constructor to create and send a new Notification.
    function sendNotification() {
      console.log('TODO: Implement sendNotification()');
    }
    

    您将在实现 requestPermission 之后实现此函数。

  • window.onload 事件监听器会在页面加载时调用 showPermission 函数,在控制台和页面上显示当前权限状态:

    window.onload = () => { showPermission(); };
    

请求发送通知的权限

在此步骤中,您将添加请求用户授予发送通知权限的功能。

您将使用 Notification.requestPermission() 方法触发一个弹出式窗口,要求用户允许或屏蔽来自您网站的通知。

  1. 将 public/index.js 中的 requestPermission 函数存根替换为以下代码:

    // Use the Notification API to request permission to send notifications.
    function requestPermission() {
      Notification.requestPermission()
        .then((permission) => {
          console.log('Promise resolved: ' + permission);
          showPermission();
        })
        .catch((error) => {
          console.log('Promise was rejected');
          console.log(error);
        });
    }
    
  2. 重新加载您正在查看实时应用的 Chrome 标签页。

  3. 在实时应用界面上,点击请求发送通知的权限。系统会显示一个弹出式窗口。

用户可以对权限弹出式窗口做出以下三种响应之一。

用户回答 通知权限状态
用户选择允许 granted
用户选择屏蔽 denied
用户在未做出选择的情况下关闭了弹出式窗口 default

如果用户点击“允许”

  • Notification.permission 设置为 granted

  • 该网站将能够显示通知。

  • 后续对 Notification.requestPermission 的调用将解析为 granted,而不会显示弹出式窗口。

如果用户点击“屏蔽”

  • Notification.permission 设置为 denied

  • 网站将无法向用户显示通知。

  • 后续对 Notification.requestPermission 的调用将解析为 denied,而不会显示弹出式窗口。

如果用户关闭弹出式窗口

  • Notification.permission 仍然为 default

  • 网站将无法向用户显示通知。

  • 后续对 Notification.requestPermission 的调用会生成更多弹出式窗口。

    不过,如果用户继续关闭弹出式窗口,浏览器可能会屏蔽相应网站,并将 Notification.permission 设置为 denied。这样一来,系统便无法向用户显示权限请求弹出式窗口或通知。

    在撰写本文时,浏览器在用户关闭通知权限弹出式窗口后做出的行为仍可能会发生变化。处理此问题的最佳方式是,始终在用户发起某些互动后请求通知权限,这样用户就会有所预期并了解情况。

发送通知

在此步骤中,您将向用户发送通知。

您将使用 Notification 构造函数创建一个新通知,并尝试显示该通知。 如果权限状态为 granted,系统会显示您的通知。

  1. 将 index.js 中的 sendNotification 函数存根替换为以下代码:

    // Use the Notification constructor to create and send a new Notification.
    function sendNotification() {
      let title = 'Test';
      let options = {
        body: 'Test body',
        // Other options can go here
      };
      console.log('Creating new notification');
      let notification = new Notification(title, options);
    }
    

    Notification 构造函数接受两个参数:titleoptionsoptions 是一个对象,其属性表示您可以在通知中包含的视觉设置和数据。如需了解详情,请参阅 有关通知参数的 MDN 文档

  2. 刷新您正在查看实时应用的 Chrome 标签页,然后点击发送通知按钮。 系统应显示一条包含文本 Test body 的通知。

未经许可发送通知会发生什么情况?

在此步骤中,您将添加几行代码,以便了解在未征得用户许可的情况下尝试显示通知时会发生什么情况。

  • public/index.js 中,在 sendNotification 函数的末尾,定义新通知的 onerror 事件处理程序:
// Use the Notification constructor to create and send a new Notification.
function sendNotification() {
  let title = 'Test';
  let options = {
    body: 'Test body',
    // Other options can go here
  };
  console.log('Creating new notification');
  let notification = new Notification(title, options);
  notification.onerror = (event) => {
    console.log('Could not send notification');
    console.log(event);
  };
}

如需观察通知权限错误,请执行以下操作

  1. 点击 Chrome 网址栏旁边的锁形图标,然后将网站的通知权限设置重置为默认设置。

  2. 点击请求发送通知的权限,然后从弹出式窗口中选择禁止

  3. 点击发送通知,看看会发生什么情况。 错误文本 (Could not send notification) 和事件对象会记录到控制台。

(可选)再次重置网站的通知权限。 您可以尝试多次请求权限并关闭弹出式窗口,看看会发生什么情况。

尝试使用通知选项

您现在已了解如何请求权限和发送通知的基础知识。 您还了解了用户响应对应用显示通知的能力有何影响。

现在,您可以尝试在创建通知时使用各种视觉和数据选项。 下面列出了所有可用的选项。 (如需详细了解这些选项,请参阅 MDN 上的通知文档。)

请注意,浏览器和设备对这些选项的实现方式各不相同,因此值得在不同平台上测试通知,看看它们的效果如何。

let options = {
  dir: 'auto',              // Text direction
  lang: 'en-US',            // A language tag
  badge: '/orange-cat.png', // Display when insufficient room
  body: 'Hello World',      // Body text
  tag: 'mytag',             // Tag for categorization
  icon: '/line-cat.png',    // To display in the notification
  image: '/orange-cat.png', // To display in the notification
  data: {                   // Arbitrary data; any data type
    cheese: 'I like cheese',
    pizza: 'Excellent cheese delivery mechanism',
    arbitrary: {
      faveNumber: 42,
      myBool: true
    }},
  vibrate: [200, 100, 200], // Vibration pattern for hardware
  renotify: false,          // Notify if replaced? Default false
  requireInteraction: false,// Active until click? Default false
  /*
    actions:   // Array of NotificationActions
               // Only usable with a service worker
    [{
      action: 'shop',
      title: 'Shop!',
      icon: '/bags.png'
    },],
  */
}

如需了解更多创意,请参阅 Peter Beverloo 的通知生成器

请查看本系列中的下一个 Codelab:使用 Service Worker 处理通知,以进一步探索!