diff --git a/lesson-06/service-wookiee/main.js b/lesson-06/service-wookiee/main.js index d3c8b4e..ef9c810 100644 --- a/lesson-06/service-wookiee/main.js +++ b/lesson-06/service-wookiee/main.js @@ -1,6 +1,31 @@ const template = document.querySelector("#template").content; const boxes = document.querySelector("#boxes"); +if ("serviceWorker" in navigator) { + window.addEventListener("load", function () { + navigator.serviceWorker.register("/sw.js").then( + function (registration) { + // Registration was successful + console.log( + "ServiceWorker registration successful with scope: ", + registration.scope + ); + }, + function (err) { + // registration failed :( + console.log("ServiceWorker registration failed: ", err); + } + ); + }); +} + +let counts = 0; + +navigator.serviceWorker.addEventListener("message", (e) => { + counts++; + document.querySelector("#request-count").innerHTML = counts; +}); + for (const fileType of ["text/css", "text/html", "application/json"]) { // Clone the template for each box const box = template.cloneNode(true); diff --git a/lesson-06/service-wookiee/sw.js b/lesson-06/service-wookiee/sw.js new file mode 100644 index 0000000..156685a --- /dev/null +++ b/lesson-06/service-wookiee/sw.js @@ -0,0 +1,44 @@ +self.addEventListener("install", async (e) => { + console.log("installed"); +}); + +self.addEventListener("fetch", async (e) => { + let client = await clients.get(e.clientId); + if (client) { + client.postMessage("test"); + } +}); + +self.addEventListener("fetch", async (e) => { + console.log(e.request.url); + switch (e.request.url.split("/").pop()) { + case "fake.css": + e.respondWith( + new Response("css", { + status: 200, + statusText: `You tried to fetch ${e.request.destination}`, + }) + ); + break; + case "fake.html": + e.respondWith( + new Response("htnl", { + status: 200, + statusText: `You tried to fetch ${e.request.destination}`, + }) + ); + break; + case "fake.json": + e.respondWith( + new Response("json", { + status: 200, + statusText: `You tried to fetch ${e.request.destination}`, + }) + ); + break; + + default: + "Request failed"; + break; + } +});