Home  Web-development   Service wor ...

Service Worker Use Cases

Service Workers offer a wide range of capabilities making them a powerful tool for enhancing web applications. Here are some key use cases:

1. Offline Support

2. Background Sync

3. Push Notifications

4. Network Proxy

5. Periodic Background Sync

6. Enhanced Performance

7. Analytics and Logging

8. Security Enhancements

Example Use Case: Background Sync and Push Notifications

1. Registering for Background Sync

navigator.serviceWorker.ready.then(registration => {
  return registration.sync.register('sync-tag');
}).catch(error => {
  console.error('Background sync registration failed:', error);
});

2. Handling Background Sync in the Service Worker

self.addEventListener('sync', event => {
  if (event.tag === 'sync-tag') {
    event.waitUntil(syncData());
  }
});

function syncData() {
  // Logic to sync data with the server
  return fetch('/sync-endpoint', {
    method: 'POST',
    body: JSON.stringify({ data: 'Your data' }),
    headers: {
      'Content-Type': 'application/json'
    }
  });
}

3. Registering for Push Notifications

navigator.serviceWorker.ready.then(registration => {
  return registration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: urlB64ToUint8Array('YOUR_PUBLIC_VAPID_KEY')
  });
}).then(subscription => {
  // Send subscription to the server
}).catch(error => {
  console.error('Push subscription failed:', error);
});

4. Handling Push Notifications in the Service Worker

self.addEventListener('push', event => {
  const data = event.data.json();
  const options = {
    body: data.body,
    icon: 'icon.png',
    badge: 'badge.png'
  };

  event.waitUntil(
    self.registration.showNotification(data.title, options)
  );
});

5. Caching

Caching can also be managed by Service workers

Published on: Jul 25, 2024, 02:32 AM  
 

Comments

Add your comment