Notifications API 使用入门

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

  • 请求权限以发送通知
  • 发送通知
  • 尝试不同的通知选项

浏览器支持

  • 20
  • 14
  • 22
  • 7

来源

对示例应用进行混剪,然后在新标签页中查看该应用

系统会自动屏蔽来自嵌入式 Glitch 应用程序的通知,因此您无法在此页面上预览该应用程序。不过,您需要执行以下操作:

  1. 点击 Remix to Edit 使项目可修改。
  2. 如需预览网站,请按查看应用,然后按全屏 全屏

系统应该会在新的 Chrome 标签页中打开 Glitch:

屏幕截图:在新标签页中显示 Remix 直播应用

在学习此 Codelab 时,请更改本页面上嵌入式 Glitch 中的代码。使用已发布的应用刷新新标签页以查看更改。

熟悉启动应用及其代码

首先,在新的 Chrome 标签页中查看已发布的应用:

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

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

    Notification permission is default
    

    如果你不知道这意味着什么,别担心,所有变化很快就会揭晓!

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

    控制台会输出来自两个函数存根的“TODO”消息:requestPermissionsendNotification。这些是您将在此 Codelab 中实现的函数。

现在,我们来看看本页面上嵌入式 Glitch 中的示例应用代码。 打开 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. 在实时应用界面中,点击 Request permissions to send notifications(请求权限以发送通知)。系统随即会显示一个弹出式窗口。

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

用户响应 通知权限状态
用户选择允许 granted
用户选择屏蔽 denied
用户关闭弹出式窗口而不做出选择 default

如果用户点击“Allow”(允许)

  • 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 完成后的代码:glitch.com/edit/#!/codelab-notifications-get-started-completed

请查看本系列的下一个 Codelab 使用 Service Worker 处理通知,深入探索!