SW-JS-V2

JavaScript ParaNerd 1 Views Size: 2.49 KB Posted on: Dec 10, 25 @ 9:11 PM
  1. 1// Service Worker for persistent audio across pages
  2. 2const CACHE_NAME = 'paranormal-fm-v1';
  3. 3const AUDIO_STATE_KEY = 'paranormal_fm_audio_state';
  4. 4
  5. 5// Install event
  6. 6self.addEventListener('install', (event) => {
  7. 7 console.log('Paranormal FM Service Worker installing...');
  8. 8 self.skipWaiting();
  9. 9});
  10. 10
  11. 11// Activate event
  12. 12self.addEventListener('activate', (event) => {
  13. 13 console.log('Paranormal FM Service Worker activated');
  14. 14 event.waitUntil(self.clients.claim());
  15. 15});
  16. 16
  17. 17// Audio state management
  18. 18let audioState = {
  19. 19 isPlaying: false,
  20. 20 currentTime: 0,
  21. 21 volume: 1,
  22. 22 streamUrl: '',
  23. 23 lastUpdate: Date.now()
  24. 24};
  25. 25
  26. 26// Message handling for audio state
  27. 27self.addEventListener('message', (event) => {
  28. 28 const { type, data } = event.data;
  29. 29
  30. 30 switch (type) {
  31. 31 case 'AUDIO_STATE_UPDATE':
  32. 32 audioState = { ...audioState, ...data, lastUpdate: Date.now() };
  33. 33 console.log('Service Worker: Audio state updated', audioState);
  34. 34
  35. 35 // Broadcast to all clients
  36. 36 self.clients.matchAll().then(clients => {
  37. 37 clients.forEach(client => {
  38. 38 client.postMessage({
  39. 39 type: 'AUDIO_STATE_SYNC',
  40. 40 data: audioState
  41. 41 });
  42. 42 });
  43. 43 });
  44. 44 break;
  45. 45
  46. 46 case 'GET_AUDIO_STATE':
  47. 47 event.ports[0].postMessage({
  48. 48 type: 'AUDIO_STATE_RESPONSE',
  49. 49 data: audioState
  50. 50 });
  51. 51 break;
  52. 52
  53. 53 case 'AUDIO_PLAY':
  54. 54 audioState.isPlaying = true;
  55. 55 audioState.lastUpdate = Date.now();
  56. 56 broadcastToClients('AUDIO_PLAY_COMMAND', audioState);
  57. 57 break;
  58. 58
  59. 59 case 'AUDIO_PAUSE':
  60. 60 audioState.isPlaying = false;
  61. 61 audioState.lastUpdate = Date.now();
  62. 62 broadcastToClients('AUDIO_PAUSE_COMMAND', audioState);
  63. 63 break;
  64. 64 }
  65. 65});
  66. 66
  67. 67function broadcastToClients(type, data) {
  68. 68 self.clients.matchAll().then(clients => {
  69. 69 clients.forEach(client => {
  70. 70 client.postMessage({ type, data });
  71. 71 });
  72. 72 });
  73. 73}
  74. 74
  75. 75// Keep service worker alive
  76. 76self.addEventListener('fetch', (event) => {
  77. 77 // Just return the request as-is, but keeps SW active
  78. 78 event.respondWith(fetch(event.request));
  79. 79});

Raw Paste

Comments 0
Login to post a comment.
  • No comments yet. Be the first.
Login to post a comment. Login or Register
We use cookies. To comply with GDPR in the EU and the UK we have to show you these.

We use cookies and similar technologies to keep this website functional (including spam protection via Google reCAPTCHA or Cloudflare Turnstile), and — with your consent — to measure usage and show ads. See Privacy.