我是 Service Worker 领域的初学者,现在我可以显示通知,但我的要求是使用从推送事件收到的数据更新 DOM。我尝试使用 postMessage api。但我不明白如何使用。我尝试使用 [ Chrome ServiceWorker postMessage的答案, 但我无法使用它。谁能帮我举个例子,这样我就可以理解并完成这个!?在 Main js..我正在使用 initializeUI() 我正在为 user:: 调用 sendMessage 和订阅
if ('serviceWorker' in navigator && 'PushManager' in window) {
navigator.serviceWorker.register('../js/sw.js', {scope: 'xyz'})
.then(function (swReg) {
console.log('Service Worker is registered', swReg);
swRegistration = swReg;
initializeUI();
})
.catch(function (error) {
console.error('Service Worker Error', error);
});
} else {
console.warn('Push messaging is not supported');
pushButton.textContent = 'Push Not Supported';
}
function sendMessage(message) {
return new Promise(function (resolve, reject) {
var messageChannel = new MessageChannel();
messageChannel.port1.onmessage = function (event) {
if (event.data.error) {
reject(event.data.error);
console.log('rejected message');
} else {enter code here
resolve(event.data);
console.log('received message :: ' + event.data);
}
};
navigator.serviceWorker.controller.postMessage(message, [messageChannel.port2]);
});
}
在 sw.js 中
self.addEventListener('message', function(event) {
console.log('inside message listener');
event.ports[0].postMessage({'test': 'This is my response.'});
});
self.addEventListener('push', function (event) {
console.log('[Service Worker] Push Received.');
console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);
const title = 'New Project';
const options = {
body: `"${event.data.text()}"`,
icon: 'images/icon.png',
badge: 'images/badge.png'
};
console.log("data :: " + event.data.text());
event.waitUntil(self.registration.showNotification(title, options));
});
谢谢