乐闻世界logo
搜索文章和话题

How to persist data in a Service Worker

1个答案

1

Service Worker itself cannot directly persist data, but it can achieve data persistence by utilizing storage APIs provided by the browser. Here are several methods to persist data in Service Worker:

1. Using IndexedDB

IndexedDB is a non-relational database that runs in the browser and allows you to store large volumes of structured data. Service Worker can persist data through IndexedDB. This API is designed for handling substantial data volumes and supports transactions.

Example:

Consider caching and persisting user data in the Service Worker:

javascript
self.addEventListener('install', (event) => { event.waitUntil( (async () => { const dbOpenRequest = indexedDB.open('myDatabase', 1); dbOpenRequest.onupgradeneeded = function(event) { let db = event.target.result; db.createObjectStore('userData', { keyPath: 'id' }); }; const db = await dbOpenRequest; const tx = db.transaction('userData', 'readwrite'); const store = tx.objectStore('userData'); store.put({ id: 1, name: 'John Doe', email: 'john@example.com' }); await tx.complete; })() ); });

2. Using Cache API

The Cache API enables persistent caching of requests and their responses, making it ideal for storing application shells (e.g., static assets like HTML, CSS, and JavaScript files).

Example:

The following code demonstrates caching and retrieving resources using the Cache API:

javascript
self.addEventListener('install', (event) => { event.waitUntil( caches.open('my-cache').then((cache) => { return cache.addAll([ '/index.html', '/styles.css', '/script.js', // Other resources... ]); }) ); }); self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request).then((response) => { return response || fetch(event.request); }) ); });

3. Using LocalStorage

Although Service Worker lacks direct access to localStorage, you can communicate with the page via the Client API to persist data to localStorage.

Example:

This requires inter-process communication between Service Worker and the page. Service Worker sends messages to the page:

javascript
self.clients.matchAll().then(clients => { clients.forEach(client => { client.postMessage({ command: 'storeData', data: { key: 'value' } }); }); });

On the page, listen for messages from Service Worker and use localStorage:

javascript
navigator.serviceWorker.addEventListener('message', event => { if (event.data.command === 'storeData') { localStorage.setItem('myKey', event.data.data.key); } });

4. Using Web SQL (Not Recommended)

Web SQL is a deprecated Web API as it is not a W3C standard and has been removed from most modern browsers.

In summary, for persisting data in Service Worker, it is generally recommended to use IndexedDB or Cache API, as both are widely supported by modern browsers and are specifically designed for worker threads and Service Worker to handle large data volumes effectively even offline.

2024年6月29日 12:07 回复

你的答案