feat: auto-registration of service-worker

This commit is contained in:
Ayo Ayco 2024-08-13 20:21:58 +02:00
parent b87c18d74b
commit 4cddb04e33
4 changed files with 64 additions and 7 deletions

View file

@ -11,6 +11,10 @@ export default defineConfig({
serviceWorker({ serviceWorker({
path: "./example_sw.js", path: "./example_sw.js",
assetCachePrefix: 'cozy-reader', assetCachePrefix: 'cozy-reader',
// onInstalled: () => console.log('Installed...'),
// onInstalling: () => console.log('Installing...'),
// onActive: () => console.log('Active!'),
// onError: (error) => console.error(`Registration failed on ${error}`)
}) })
] ]
}); });

View file

@ -5,16 +5,20 @@ import { randomUUID } from "node:crypto";
/** /**
* @typedef {{ * @typedef {{
* path: string,
* assetCachePrefix?: string, * assetCachePrefix?: string,
* assetCacheVersionID?: string, * assetCacheVersionID?: string,
* path: string, * onInstalling?: Function,
* onInstalled?: Function,
* onActive?: Function,
* onError?: Function
* }} ServiceWorkerConfig * }} ServiceWorkerConfig
* @typedef {import('astro').AstroIntegration} AstroIntegration * @typedef {import('astro').AstroIntegration} AstroIntegration
*/ */
/** /**
* Accepts configuration options with service worker path * Accepts configuration options with service worker path
* and injects needed variables such as `assets` generated by Astro * and injects needed variables such as `__assets` generated by Astro
* @param {ServiceWorkerConfig} config * @param {ServiceWorkerConfig} config
* @returns {AstroIntegration} * @returns {AstroIntegration}
*/ */
@ -22,7 +26,15 @@ export default function serviceWorker(config) {
let { let {
assetCachePrefix, assetCachePrefix,
assetCacheVersionID = randomUUID(), assetCacheVersionID = randomUUID(),
path: serviceWorkerPath path: serviceWorkerPath,
/**
* TODO: use registration hooks callbacks
*/
// onInstalling,
// onInstalled,
// onActive,
// onError,
// onUnsupported,
} = config; } = config;
/** /**
@ -30,9 +42,40 @@ export default function serviceWorker(config) {
*/ */
let assets = []; let assets = [];
const registrationScript = `const registerSW = async () => {
if ("serviceWorker" in navigator) {
try {
const registration = await navigator.serviceWorker.register("/sw.js", {
scope: "/",
});
if (registration.installing) {
// installingFn();
console.log('[astro-sw] Installing...')
} else if (registration.waiting) {
// installedFn();
console.log('[astro-sw] Installed...')
} else if (registration.active) {
// activeFn();
console.log('[astro-sw] Active...')
}
} catch (error) {
// onError(error);
console.error('[astro-sw] ERR', error)
}
} else {
// onUnsupported();
console.log('[astro-sw] Browser does not support Service Worker')
}
}
registerSW();`
return { return {
'name': 'astro-sw', 'name': 'astro-sw',
'hooks': { 'hooks': {
'astro:config:setup': ({injectScript}) => {
injectScript('page', registrationScript);
},
'astro:build:ssr': ({ manifest }) => { 'astro:build:ssr': ({ manifest }) => {
assets = manifest.assets.filter(ass => !ass.includes('sw.js')) assets = manifest.assets.filter(ass => !ass.includes('sw.js'))
}, },

View file

@ -1,4 +0,0 @@
---
---
hello

14
src/pages/index.astro Normal file
View file

@ -0,0 +1,14 @@
---
---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello</title>
</head>
<body>
Hello
</body>
</html>
<!-- <Fragment set:html={content} /> -->