Javascript ServiceWorker推送通知选项未传递到通知
我传递给我的通知的通知选项没有传递给通知,我将得到一个默认通知。(标题为网站,正文为“网站已在后台更新”) Service worker是一个应用程序服务工作者 此外,推送事件处理程序中的console.log语句不会传递到浏览器。为什么会这样 推送事件侦听器直接位于CRA Service Worker中的加载事件侦听器之后 用于创建Web推送通知的Web推送API调用:Javascript ServiceWorker推送通知选项未传递到通知,javascript,reactjs,progressive-web-apps,service-worker,web-push,Javascript,Reactjs,Progressive Web Apps,Service Worker,Web Push,我传递给我的通知的通知选项没有传递给通知,我将得到一个默认通知。(标题为网站,正文为“网站已在后台更新”) Service worker是一个应用程序服务工作者 此外,推送事件处理程序中的console.log语句不会传递到浏览器。为什么会这样 推送事件侦听器直接位于CRA Service Worker中的加载事件侦听器之后 用于创建Web推送通知的Web推送API调用: router.post('/:userid', auth, async (req, res) => { try {
router.post('/:userid', auth, async (req, res) => {
try {
const user = await User.findById(req.params.userid);
user.pushSubscriptions.forEach((sub) => {
if (sub === null) {
return;
}
webpush.setVapidDetails(
'mailto:contact@email.com',
config.get('vapidPublic'),
config.get('vapidSecret')
);
const options = {
endpoint: sub.endpoint,
expirationTime: sub.expirationTime,
keys: {
p256dh: sub.keys.p256dh,
auth: sub.keys.auth,
},
};
console.log(options.endpoint);
webpush
.sendNotification(
options,
JSON.stringify({
title: 'NotifTitle',
body: 'Body',
})
)
.catch((error) => console.log(error));
});
return res.status(200).json({ msg: 'Notification Sent' });
} catch (error) {
console.log(error);
return res.status(500);
}
});
在sw.js中推送侦听器:
window.addEventListener('push', (event) => {
console.log('Notification Recieved', event);
//Fallback data
let data = {
title: 'TestABC',
body: '123456',
};
if (event.data) {
data = JSON.parse(event.data.text());
}
//Notification options
var options = {
body: data.body,
icon: '../public/logo192.png',
image: '../public/logo192.png',
};
event.waitUntil(
console.log(options),
navigator.serviceWorker.registration.showNotification(
data.title,
options
)
);
});
谢谢尝试这样转换数据
data = event.data.json();
你可以读更多