[英]Service-Worker addEventListener, how to use the event parameter?
我現在正在嘗試使推送通知與Node.js一起使用。
為此,我遵循了可以在網上找到的一些教程和文檔,最后終於有了使用“服務工作者”的工作方法。
目前,我完全不熟悉Node.js上的Push Notifications和Service Workers。
這是我的相關代碼:
.....
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'
})
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.