JavaScript Internals (521 Qs)•Part 1: Core Objects, Prototypes, Functions & Scope (1 - 53)
How do you manipulate DOM using a service worker
Service worker can't access the DOM directly. But it can communicate with the pages it controls by responding to messages sent via the postMessage interface, and those pages can manipulate the DOM.
Practical Code Example
javascript
// Service Worker does NOT have direct access to 'window' or 'document' DOM.
// Communication must happen via PostMessage:
// In Service Worker (sw.js)
self.addEventListener('push', (event) => {
self.clients.matchAll().then((clients) => {
clients.forEach((client) => {
client.postMessage({ type: 'NEW_NOTIFICATION', payload: 'New Message!' });
});
});
});
// In Web Page (main.js)
navigator.serviceWorker.addEventListener('message', (event) => {
if (event.data.type === 'NEW_NOTIFICATION') {
document.getElementById('badge').textContent = event.data.payload; // Updates DOM!
}
});