Cla*_*raG 2 notifications push-notification reactjs progressive-web-apps aws-amplify
我正在使用 React 开发一个渐进式 Web 应用程序,当新优惠添加到数据库时,它会收到通知。一切正常,我打开网页,要求用户授予启用通知的权限,我们允许他们,安装 PWA,运行它,在数据库中添加新优惠,然后显示带有新优惠的通知(Chrome + Windows 10)。
但问题是,如果 PWA 未运行,我不会收到任何通知。即使 PWA 关闭,我也认为服务工作人员正在后台运行。我缺少什么?
这是我的 notification.ts 文件中的 notificationNewOffer 函数
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');
}
}
Run Code Online (Sandbox Code Playgroud)
我就是这样称呼它的:
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()
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗 ?非常感谢
为了在应用程序未打开时显示通知,您还需要使用网络推送。Web 推送允许您从服务器向设备发送通知。当推送到达设备时,它会唤醒 Service Worker,并在其中显示通知。
有关设置网络推送和通知的说明,请访问https://developers.google.com/web/fundamentals/push-notifications
| 归档时间: |
|
| 查看次数: |
5650 次 |
| 最近记录: |