view mrjunejune/src/public/pwa-register.js @ 211:a6d8d32a0261

[MrJuneJune] Simple animations for darkmode.
author MrJuneJune <me@mrjunejune.com>
date Sun, 15 Feb 2026 21:38:23 -0800
parents 3b47e82ac57e
children
line wrap: on
line source

// PWA Service Worker Registration
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker
      .register('/public/sw.js')
      .then((registration) => {
        // console.log('[PWA] Service Worker registered:', registration.scope);

        // Check for updates periodically
        setInterval(() => {
          registration.update();
        }, 60000); // Check every minute

        // Handle updates
        registration.addEventListener('updatefound', () => {
          const newWorker = registration.installing;
          newWorker.addEventListener('statechange', () => {
            if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
              // New content available, show update notification
              if (confirm('New version available! Reload to update?')) {
                newWorker.postMessage({ type: 'SKIP_WAITING' });
                window.location.reload();
              }
            }
          });
        });
      })
      .catch((error) => {
        console.error('[PWA] Service Worker registration failed:', error);
      });

    // Handle service worker updates
    let refreshing = false;
    navigator.serviceWorker.addEventListener('controllerchange', () => {
      if (!refreshing) {
        refreshing = true;
        window.location.reload();
      }
    });
  });
}

// Add install prompt handler
let deferredPrompt;

window.addEventListener('beforeinstallprompt', (e) => {
  e.preventDefault();
  deferredPrompt = e;

  showInstallPromotion();
});

function showInstallPromotion() {
  // Create an install button if it doesn't exist
  if (document.getElementById('pwa-install-btn')) return;

  const installBtn = document.createElement('button');
  installBtn.classList.add('with-icon');
  installBtn.id = 'pwa-install-btn';
  installBtn.textContent = 'Install as App';

  installBtn.addEventListener('click', async () => {
    if (!deferredPrompt) return;

    deferredPrompt.prompt();
    const { outcome } = await deferredPrompt.userChoice;
    console.log(`[PWA] User response: ${outcome}`);

    deferredPrompt = null;
    installBtn.remove();
  });

  document.body.appendChild(installBtn);

  setTimeout(() => {
    installBtn.style.opacity = '0';
    installBtn.style.transition = 'opacity 0.3s';
    setTimeout(() => installBtn.remove(), 300);
  }, 5000);
}

window.addEventListener('appinstalled', () => {
  console.log('[PWA] App installed successfully!');
  deferredPrompt = null;

  const installBtn = document.getElementById('pwa-install-btn');
  if (installBtn) installBtn.remove();
});