Question 69
Question
Answer
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/service-worker.js')
.then(registration => console.log('Service worker registered:', registration))
.catch(error => console.log('Service worker registration failed:', error));
});
}self.addEventListener('install', (event) => {
event.waitUntil(
// ... Your existing cache setup from previous examples ...
);
});
self.addEventListener('fetch', (event) => {
// ... Existing fetch event handling ...
});
self.addEventListener('sync', (event) => {
if (event.tag === 'my-sync-tag') {
console.log('Background sync for my-sync-tag');
// Process your pending tasks here:
const taskData = getPendingTasks(); // Replace with how you store your data
for (const task of taskData) {
try {
// Send the task to your backend server or perform other actions
sendTaskToServer(task);
} catch (error) {
console.error('Error processing task:', error);
// Handle errors gracefully, perhaps retrying later
}
}
// After processing tasks, clear them from storage:
clearPendingTasks();
}
});Last updated