Skip to content

Commit

Permalink
feat: Add service worker for setting headers
Browse files Browse the repository at this point in the history
  • Loading branch information
Sheraff committed Oct 4, 2024
1 parent c938c06 commit 96aa50c
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
1 change: 1 addition & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
</head>
<body>
<div id="root"></div>
<script src="/src/register.ts"></script>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
29 changes: 29 additions & 0 deletions public/sw.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/// <reference lib="webworker" />

const s = /** @type {ServiceWorkerGlobalScope} */(/** @type {unknown} */(self))

s.addEventListener("install", () => s.skipWaiting())
s.addEventListener("activate", (event) => event.waitUntil(s.clients.claim()))

s.addEventListener("fetch", (event) => {
if (event.request.cache === "only-if-cached" && event.request.mode !== "same-origin") {
return
}

event.respondWith(
fetch(event.request)
.then((response) => {
const newHeaders = new Headers(response.headers)
newHeaders.set("Cross-Origin-Opener-Policy", "same-origin")
newHeaders.set("Cross-Origin-Embedder-Policy", "require-corp")

const moddedResponse = new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHeaders,
})

return moddedResponse
})
)
})
13 changes: 13 additions & 0 deletions src/register.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const controlling = navigator.serviceWorker && navigator.serviceWorker.controller
if (!window.isSecureContext) {
console.log("Not registering service worker because the site is not hosted on HTTPS.")
} else {
navigator.serviceWorker.register('./sw.js')
.then(registration => {
console.log(`Service worker registered: scope "${registration.scope}"`)
registration.addEventListener("updatefound", () => window.location.reload())
if (registration.active && !navigator.serviceWorker.controller) {
window.location.reload()
}
})
}

0 comments on commit 96aa50c

Please sign in to comment.