reactjs - 应用程序未运行时不显示 PWA 推送通知
问题描述
我正在开发一个带有 React 的渐进式 Web 应用程序,它会在将新报价添加到数据库时收到通知。一切正常,我打开网络,要求用户授予启用通知的权限,我们允许他们,安装 PWA,运行它,在数据库中添加新报价,并显示带有新报价的通知(Chrome + 视窗 10)。
但问题是,如果 PWA 未运行,我不会收到任何通知。即使 PWA 已关闭,我也会认为服务人员正在后台运行。我错过了什么?
这是我的 notification.ts 文件中的 notifyNewOffer 函数
function notifyNewOffer(newOffer: Offer) {
if ('serviceWorker' in navigator) {
const options = {
body: newOffer.subheading,
icon: './logo192.png',
image: './static/media/placeholder-offer.1bcbf040.png',
vibrate: [100, 50, 200],
badge: './favicon.ico',
tag: 'new-offers',
renotify: true,
actions: [
{ action: 'confirm', title: 'Check offer', icon: '' },
],
};
navigator.serviceWorker.ready.then(swreg => {
swreg.showNotification(newOffer.heading, options);
});
} else {
console.log('no serviceWorker');
}
}
这就是我所说的:
function addedOfferSubs<T>(setOffers: (offers:any) => void) {
// @ts-ignore
const subscription = API.graphql(graphqlOperation(addedOffer)).subscribe({
next: async (eventData: SubscriptionValue<T>) => {
const newOffer = (eventData.value.data as any).addedOffer;
await indexedDb.createObjectStore('offers', 'id'); // Opens db. Will create the table offers only if it doesnt already exist
await indexedDb.putValue('offers', newOffer); // Adds new offer
// Push notification
notifyNewOffer(newOffer);
// Set offers
const offersData = await getOffersFromIdb();
setOffers(offersData);
},
});
return () => subscription.unsubscribe()
}
有任何想法吗 ?非常感谢
解决方案
为了在应用程序未打开时显示通知,您还需要使用 Web Push。Web 推送允许您从服务器向设备发送通知。当推送到达设备时,它会唤醒服务工作者,并在那里显示通知。
有关设置 Web 推送和通知的说明,请访问https://developers.google.com/web/fundamentals/push-notifications
推荐阅读
- python - 我无法使用 pip 安装 logpy
- javascript - Google 分析在单页应用程序上拆分会话(流氓推荐问题)
- python - 反向查找返回 -1 尽管内容“古腾堡计划的犯罪结束”在文本中
- java - Java - 2D-array - 逐步填充游戏表
- python - Ansible 无法在单个服务器上执行“百胜安装”任务(在许多服务器中)
- node.js - 我如何对一个 Lucid Orm 关系进行分页?
- html - 加载页面时将所有移动设备的图像居中
- python - 如何在已经本地安装 Python (3.7.3) 的 MacBook 上使用 Homebrew 运行我的 Python (3.7.5) 版本
- amazon-web-services - 如何使用 boto3 更改 AWS Glue 爬虫创建的表的名称
- f# - F# 如何从 AND 运算返回布尔值?