首页 > 解决方案 > PWA关闭时如何接收点击通知数据?

问题描述

我的 Progressive Web App (PWA) 中的桌面通知工作得很好。在 PWA 打开的情况下,当我单击通知时,我能够接收到通知的数据属性。当 PWA 关闭时,当我单击通知时,PWA 会打开但我的 onclick 处理程序从未执行,我也看不到在启动 Web 应用程序时从通知接收数据的方法。

当 PWA 当前未运行时,如何接收通知数据属性?

当我的 PWA 出现 2 条通知时,我想知道在我的 PWA 关闭时单击了哪些 PWA。查看Notification API,我看不到检查我的网络应用程序启动的方法。

这是我的代码:

if ('Notification' in window) {
    const options = {
        icon: 'https://i.imgur.com/l8qOen5.png',
        image: 'https://i.imgur.com/l8qOen5.png',
        requireInteraction: true,
    };

    if (Notification.permission === 'granted') {
        const desktopNotification = new Notification('My Title', {
            ...options,
            body: 'My body text',
            data: 'A string I want to receive when PWA is opened',
            tag: 'A unique identifier',
        });

        desktopNotification.onclick = (e) => {
            // Not received when PWA is closed and then opened on click of notification
            const data = e.currentTarget.data || {};
            console.log('desktopNotification clicked!', e, data);
        };
    }
}

标签: notificationsprogressive-web-apps

解决方案


首先,您需要service-worker.js运行,即使您的 PWA 应用程序已关闭。如果您不熟悉 Service Worker API,请查看此处给出的非常好的示例:推送通知简介

notificationclick要在技术层面回答您的问题,您需要service-worker.js. 还有一些其他事件可用,例如:notificationclose.

这是内部所需内容的简要示例serviceworker.js

self.addEventListener('notificationclick', function(e) {
  var notification = e.notification;
  var primaryKey = notification.data.primaryKey;
  var action = e.action;

  if (action === 'close') {
    notification.close();
  } else {
    clients.openWindow('http://www.example.com');
    notification.close();
  }
});

推荐阅读