From 6eae39861a41e51d03df9f47150e099622ccb9f8 Mon Sep 17 00:00:00 2001 From: Jakub Jankiewicz Date: Sun, 2 Jul 2023 14:28:33 +0200 Subject: [PATCH] add offline demo --- docs/index.html | 3 ++- docs/offline/index.html | 35 +++++++++++++++++++++++++++++++++++ docs/offline/sw.js | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 docs/offline/index.html create mode 100644 docs/offline/sw.js diff --git a/docs/index.html b/docs/index.html index 9d39626..07a0f31 100644 --- a/docs/index.html +++ b/docs/index.html @@ -15,9 +15,10 @@

Wayne library demo

diff --git a/docs/offline/index.html b/docs/offline/index.html new file mode 100644 index 0000000..fc615db --- /dev/null +++ b/docs/offline/index.html @@ -0,0 +1,35 @@ + + + + + + + + + + + + +

Offline Wayne Demo

+

Disconnect the internet connection and refresh the page

+ + diff --git a/docs/offline/sw.js b/docs/offline/sw.js new file mode 100644 index 0000000..c64623f --- /dev/null +++ b/docs/offline/sw.js @@ -0,0 +1,37 @@ +importScripts('https://cdn.jsdelivr.net/npm/@jcubic/wayne/index.umd.min.js'); + +const app = new wayne.Wayne(); + +// don't intercept requests to other domains using middleware +app.use(async (req, res, next) => { + const url = new URL(req.url); + if (url.origin === location.origin) { + // use normal route + next(); + } else if (!navigator.onLine) { + // any file to different domain when user is offline is blank + res.send('', 'text/plain'); + } else { + // normal HTTP request to the server + const _res = await fetch(req.url); + const type = _res.headers.get('Content-Type') ?? 'application/octet-stream'; + res.send(await _res.arrayBuffer(), { type }); + } +}); + +app.get('*', async (req, res) => { + if (navigator.onLine) { + const path = '.' + req.params[0]; + const _res = await fetch(path); + const type = _res.headers.get('Content-Type') ?? 'application/octet-stream'; + res.send(await _res.arrayBuffer(), { type }); + } else { + res.html(`

You're offline

`); + } +}); + +// take control of uncontrolled clients on first load +// ref: https://web.dev/service-worker-lifecycle/#clientsclaim +self.addEventListener('activate', (event) => { + event.waitUntil(clients.claim()); +});