javascript - Service-Worker addEventListener,如何使用事件参数?
问题描述
我现在正在尝试使推送通知与 Node.js 一起使用。
为此,我遵循了一些可以在网上找到的教程和文档,我终于有了使用所谓的 Service Worker 的东西。
在这一点上,Node.js 和 Service Worker 上的推送通知都不是我所熟悉的。
这是我的相关代码:
.....
console.log("Registering ServiceWorker.");
const register = await navigator.serviceWorker.register('/worker.js', {
scope: "/"
});
console.log('ServiceWorker registered.');
console.log("Registering Push.");
const subscription = await register.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(publicVapIdKey)
});
console.log('Push registered.');
console.log("Sending Push.");
await fetch('/subscribe', {
method: 'POST',
body: JSON.stringify(subscription),
headers: {
'content-type': 'application/json'
}
});
console.log('Push sent.');
.....
和服务人员:
console.log('Service Worker Loaded.');
self.addEventListener('push', e => {
const data = e.data.json;
console.log('Push Received');
self.registration.showNotification(data.title, {
body: 'It is time to go for lunch.',
icon: 'MyLogo.png'
})
});
还有这个,在我的 index.js 文件中:
// Subscribe Route.
app.post('/subscribe',(req,res) => {
const subscription = req.body; // Get Push Subscription Object.
res.status(201).json({}); // Sen 201. Resource created.
// Create PayLoad.
const payload = JSON.stringify({title:'This is a payload-title'});
// Pass Object to sendNotification.
webPush.sendNotification(subscription,payload).catch(err => console.error(err));
});
我想问的问题是关于使用addEventListener
. 那是事件参数。在我看来,这个参数对于向Service Worker传递信息一定很重要,但在我的例子中它完全没用,我不知道如何使用它。
当我在 FireFox 或 Chrome 中运行此示例时,我可以看到这种通知:
可以看到屏幕截图上显示“未定义”。这就是来自 data.title 的内容(来自 e 参数)。我应该如何更改代码以查看显示的“未定义”以外的内容?我当然希望能够在这个块之外做出改变:
self.addEventListener('push', e => {...})
我已经尝试设置一些“标题”字段,我认为这可能是一个解决方案,但没有任何效果。我显然没有做正确的事。
换句话说,更笼统地说;我想知道的是“如何使用addEventListener的事件参数”。即使是一个非常基本的示例(如何更改我的代码)也会非常感激。
解决方案
根据 Push API 规范e.data
是PushMessageData
. 您可以在此处查看有关其界面的更多信息。你的代码应该是:
self.addEventListener('push', function(e) {
let data = {};
if (e.data) {
// IMPORTANT:
// The following line does not use "e.data.json",
// but "e.data.json()" !!!!!
data = e.data.json();
}
self.registration.showNotification(data.title, {
body: 'It is time to go for lunch.',
icon: 'MyLogo.png'
})
});