【问题标题】:How to receive notification data from click when PWA is closed?PWA关闭时如何接收点击通知数据?
【发布时间】:2019-04-07 02:51:23
【问题描述】:

我的 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);
        };
    }
}

【问题讨论】:

    标签: notifications progressive-web-apps


    【解决方案1】:

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

    要从技术层面回答您的问题,您需要订阅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();
      }
    });
    

    【讨论】:

    • 关键是服务工作者必须是发出通知的人。您的回答帮助“推动”我朝那个方向发展 :)
    猜你喜欢
    • 1970-01-01
    • 2022-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 2020-03-14
    相关资源
    最近更新 更多