Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions lesson-06/service-wookiee/main.js
Original file line number Diff line number Diff line change
@@ -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);
Expand Down
44 changes: 44 additions & 0 deletions lesson-06/service-wookiee/sw.js
Original file line number Diff line number Diff line change
@@ -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;
}
});