Created
June 5, 2025 20:47
-
-
Save AstraLuma/48e06e56016b4fad9feda0495f023c81 to your computer and use it in GitHub Desktop.
Service worker synthesizing a response
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8" /> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |
<meta name="viewport" content="width=device-width" /> | |
<title>Service worker demo</title> | |
</head> | |
<body> | |
<h1>Synthesized Response Demo</h1> | |
<p>Response: <span id="resp"></span></p> | |
<p><a href="/hello.txt">Open as page</a></p> | |
<script type="module"> | |
const registerServiceWorker = async () => { | |
if ('serviceWorker' in navigator) { | |
try { | |
const registration = await navigator.serviceWorker.register( | |
'worker.js', | |
{ | |
scope: './', | |
} | |
); | |
if (registration.installing) { | |
console.log('Service worker installing'); | |
} else if (registration.waiting) { | |
console.log('Service worker installed'); | |
} else if (registration.active) { | |
console.log('Service worker active'); | |
} | |
} catch (error) { | |
console.error(`Registration failed with ${error}`); | |
} | |
} | |
}; | |
registerServiceWorker(); | |
setInterval(() => { | |
fetch("/hello.txt").then(async (resp) => { | |
let body; | |
if (resp.ok) { | |
body = await resp.text(); | |
} else { | |
body = resp.statusText; | |
} | |
document.getElementById("resp").textContent = body; | |
}); | |
}, 5000); | |
</script> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const handleRequest = async ({ request }) => { | |
if (request.url.endsWith("/hello.txt")) { | |
console.log("Synthesizing response!"); | |
let seconds = (new Date()).getSeconds(); | |
let body = `Hello from service worker, it is ${seconds} seconds past the minute` | |
return new Response(body, { | |
status: 200, | |
headers: { "Content-Type": "text/plain" }, | |
}); | |
} else { | |
return await fetch(request); | |
} | |
}; | |
self.addEventListener("fetch", (event) => { | |
console.log("fetch", event) | |
event.respondWith( | |
handleRequest({ | |
request: event.request, | |
}), | |
); | |
}); | |
console.log("Service worker started"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment