simpleanalytics / roadmap

File you bugs and feature requests here
24 stars 2 forks source link

Add Chrome App #641

Open adriaandotcom opened 2 years ago

adriaandotcom commented 2 years ago

Fairly easy:

image

Add serviceworker.js in the root:

/* globals self, clients, Request, fetch, caches */

// Put `offline.html` page into cache on install.
// Ref: https://serviceworke.rs/offline-fallback_service-worker_doc.html

self.addEventListener('install', event => {
  const offlineRequest = new Request('/offline.html')
  event.waitUntil(
    fetch(offlineRequest).then(response => {
      caches.open('offline').then(cache => {
        cache.put(offlineRequest, response)
      })
    })
  )
})

// Serve offline fallback when the server is unreachable for HTML requests.
// Ref: https://serviceworke.rs/offline-fallback_service-worker_doc.html
self.addEventListener('fetch', event => {
  const request = event.request

  // Only fall back for HTML documents.
  if (
    request.method === 'GET' &&
    request.headers.get('accept').includes('text/html')
  ) {
    event.respondWith(
      // `fetch()` throws an exception when the server is unreachable but not
      // for valid HTTP responses, even `4xx` or `5xx` range.
      fetch(request).catch(error => {
        // eslint-disable-next-line no-console
        console.warn(
          '[onfetch] Failed. Serving cached offline fallback ' + error
        )

        return caches
          .open('offline')
          .then(cache => cache.match('/offline.html'))
      })
    )
  }
})
self.addEventListener('activate', event => event.waitUntil(clients.claim()))
self.addEventListener('message', event => {
  const handleEvent = async () => {
    const allClients = await clients.matchAll({ includeUncontrolled: true })

    const fireInactiveTabs = eventName =>
      Promise.all(
        allClients
          .filter(client => client.visibilityState === 'hidden')
          .map(client => Promise.resolve(client.postMessage(eventName)))
      )

    switch (event.data) {
      case 'CURRENT_TAB_ACTIVE':
        return fireInactiveTabs('ANOTHER_TAB_BECAME_ACTIVE')

      case 'PRIORITISE_TAB':
        return fireInactiveTabs('DEPRIORITISE_TAB')

      case 'DEPRIORITISE_TAB':
        return fireInactiveTabs('RESET_TAB_PRIORITY')

      case 'IDLE_TAB':
        return fireInactiveTabs('DISCONNECT_TAB')
    }
  }

  event.waitUntil(handleEvent())
})
kasperkamperman commented 1 year ago

I think a service-worker is not needed anymore for this PWA behaviour. Only a manifest file.

When working on a PWA service-workers cost me a lot of headaches and I don't really see the benefit of having analytics offline available anyway.