diff --git a/lesson-06/service-wookiee/main.js b/lesson-06/service-wookiee/main.js index d3c8b4e..5213327 100644 --- a/lesson-06/service-wookiee/main.js +++ b/lesson-06/service-wookiee/main.js @@ -1,5 +1,21 @@ const template = document.querySelector("#template").content; const boxes = document.querySelector("#boxes"); +const count = document.querySelector("#request-count"); +let counts = 0; + +if ("serviceWorker" in navigator) { + navigator.serviceWorker.register("sw.js"); +} + +navigator.serviceWorker.addEventListener("message", (e) => { + console.log(e.data); + counter(); +}); + +function counter() { + counts++; + count.innerHTML = counts; +} for (const fileType of ["text/css", "text/html", "application/json"]) { // Clone the template for each box diff --git a/lesson-06/service-wookiee/sw.js b/lesson-06/service-wookiee/sw.js new file mode 100644 index 0000000..4e147a7 --- /dev/null +++ b/lesson-06/service-wookiee/sw.js @@ -0,0 +1,40 @@ +// self.addEventListener("install", async (e) => { +// console.log("installed"); +// }); + +self.addEventListener("fetch", async (e) => { + // console.log("fetched " + e.clientId); + // console.log(await self.clients.get(e.clientId)); + let client = await clients.get(e.clientId); + + if (client) { + client.postMessage("test"); + } +}); + +self.addEventListener("fetch", (e) => { + const url = new URL(e.request.url); + let arr = url.pathname.split("/"); + if (arr[arr.length - 1] == "fake.css") { + let res = new Response("/*CSS*/", { + headers: { + "content-type": "application/css", + }, + }); + e.respondWith(res); + } else if (arr[arr.length - 1] == "fake.html") { + let res = new Response("/*HTML*/", { + headers: { + "content-type": "application/html", + }, + }); + e.respondWith(res); + } else if (arr[arr.length - 1] == "fake.json") { + let res = new Response("/*JSON*/", { + headers: { + "content-type": "application/json", + }, + }); + e.respondWith(res); + } +}); diff --git a/lesson-06/worker-example/index.html b/lesson-06/worker-example/index.html index 3da08e9..7e57b82 100644 --- a/lesson-06/worker-example/index.html +++ b/lesson-06/worker-example/index.html @@ -1,37 +1,20 @@ - -
- - - - + + + + +