使用推送消息重新吸引用户

推送消息是一个有用的通信通道,使应用程序可以使用相关且及时的内容更新其用户。 推送消息可用于通过应用重新吸引用户。

推送消息的最显著优势之一是即使用户未主动使用应用,也可以由应用服务器传递。

推送消息通知参与系统的通知中心,并且可以显示图像和文本信息。 通知可用于提醒用户应用中的重要更新。 但是,通知应很少使用,因为它们往往对用户的工作流造成干扰。

若要创建支持推送通知的 PWA,请执行以下操作:

  1. 请求用户在 PWA 的客户端代码中接收推送通知的权限。
  2. 订阅服务器的推送消息。
  3. 从 PWA 的服务器端代码发送推送消息。
  4. 收到推送消息时显示通知。

步骤 1 - 请求用户接收推送通知的权限

在向 PWA 发送推送通知之前,必须请求用户接收消息的权限。 若要请求权限,请在客户端代码中使用 Notification.requestPermission API ,例如当用户单击某个按钮时:

button.addEventListener("click", () => {
  Notification.requestPermission().then(permission => {
    if (permission === "granted") {
      console.log("The user accepted to receive notifications");
    }
  });
});

稍后可以再次检查权限状态:

if (Notification.permission === "granted") {
  console.log("The user already accepted");
}

步骤 2 - 订阅推送通知

若要从服务器接收推送事件,请使用推送 API 订阅推送通知。

在创建新的推送订阅之前,Microsoft Edge 会检查用户是否已授予 PWA 接收通知的权限。

如果用户未授予 PWA 接收通知的权限,浏览器会提示用户获取权限。 如果用户未向浏览器授予权限,则 对 的请求 registration.pushManager.subscribeDOMException引发 。

以下代码片段演示如何在 PWA 中订阅推送通知:

async function subscribeToPushMessages() {
  const serviceWorkerRegistration = await navigator.serviceWorker.ready;

  // Check if the user has an existing subscription
  let pushSubscription = serviceWorkerRegistration.pushManager.getSubscription();
  if (pushSubscription) {
    // The user is already subscribed to push notifications
    return;
  }

  try {
    // Subscribe the user to push notifications
    pushSubscription = await serviceWorkerRegistration.pushManager.subscribe({
      userVisibleOnly: true,
      applicationServerKey: urlBase64ToUint8Array("YOUR PUBLIC VAPID KEY HERE")
    });
  } catch (err) {
    // The subscription wasn't successful.
    console.log("Error", err);
  }
}

// Utility function for browser interoperability
function urlBase64ToUint8Array(base64String) {
  var padding = '='.repeat((4 - base64String.length % 4) % 4);
  var base64 = (base64String + padding)
      .replace(/\-/g, '+')
      .replace(/_/g, '/');
  
  var rawData = window.atob(base64);
  var outputArray = new Uint8Array(rawData.length);
  
  for (var i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i);
  }
  return outputArray;
}

前面的代码片段中提到的 VAPID 密钥是一个公钥,用于标识发送推送消息并加密推送消息有效负载的服务器。 有关 VAPID 密钥的详细信息,请参阅 步骤 3 - 从服务器发送推送消息

函数 userVisibleOnly 的配置 registration.pushManager.subscribe 选项必须存在并设置为 true。 此选项指示必须向用户显示推送消息。 Microsoft Edge 不支持不向用户显示的推送消息。

步骤 3 - 从服务器发送推送消息

应用程序需要 VAPID (自愿应用程序服务器标识) 密钥,以便将推送消息从服务器发送到 PWA 客户端。 联机提供了多个 VAPID 密钥生成器, (例如 ,Vapidkeys.com) 。

拥有 VAPID 密钥后,可以使用 Web 推送协议将推送消息发送到 PWA 客户端。

可以使用库从服务器发送推送消息,具体取决于所使用的编程语言。 例如,如果服务器使用 Node.js,则可以使用 Web 推送 库。 WebPush 库存储库中提供了其他库。

步骤 4 - 在收到推送消息时显示通知

在 PWA (中创建订阅后,如 步骤 2 - 订阅推送通知) 所示,请在服务辅助角色中添加 push 事件处理程序来处理服务器发送的推送消息。

以下代码片段演示如何在收到推送消息时显示通知:

// Listen to push events.
self.addEventListener('push', event => {
  // Check if the user has granted permission to display notifications.
  if (Notification.permission === "granted") {
    // Get the notification data from the server.
    const notificationText = event.data.text();

    // Display a notification.
    const showNotificationPromise = self.registration.showNotification('Sample PWA', {
      body: notificationText,
      icon: 'images/icon512.png'
    });

    // Keep the service worker running until the notification is displayed.
    event.waitUntil(showNotificationPromise);
  }
});

如果 PWA 在收到推送消息时不显示通知,Microsoft Edge 会显示一个通用通知,指示已收到推送消息。

另请参阅