notifications - 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);
};
}
}
解决方案
首先,您需要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();
}
});
推荐阅读
- r - 如何对一个数据框中的列值求和并将结果添加为另一个数据框中的列?
- java - 如何使用 SQS 事件对 aws lambda 进行单元测试
- docker - 拥有非 root 用户时的文件所有者
- c# - VSCode 未显示 MonoDevelop/Unity/C# 的建议代码
- c# - 无法访问已处置的对象。对象名称:AspNet Core/EF Core 项目中的“IServiceProvider”错误
- python - 无法按分位数选择 Pandas DataFrame
- discord.py - 我怎样才能制作一个禁止 dm 用户的机器人?
- python - Python For 循环遍历范围
- groovy - 来自 http-builder 的二进制内容的 NoSuchMethodError
- bootstrap-4 - 在引导程序中管理具有背景图像的表格的响应式缩放的最佳方法是什么?