Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- "use strict";
- // check logs at: chrome://serviceworker-internals/
- const CACHE = "my-cache-1";
- // self: ServiceWorkerGlobalScope
- self.addEventListener("activate", ev => {
- // required for fetch hook??
- ev.waitUntil(clients.claim());
- }, false);
- self.addEventListener("fetch", ev => {
- console.log(`fetch ${ev.request.url}`);
- ev.respondWith(caches.open(CACHE).then(cache => {
- console.log("cache opened");
- return cache.match(ev.request).then(res => {
- console.log(`Cache ${res ? "" : "not"} found: ${ev.request.url}`);
- // response would be null, if throught to fetch() when null
- return res ? res : fetch(ev.request);
- });
- }));
- }, false);
- self.addEventListener("message", ev => {
- doAction(ev.data).catch(console.error);
- }, false);
- function doAction({action, url, as}) {
- console.log(action, url, "as", as);
- switch (action) {
- case "cache": return doCache(url, as);
- case "remove": return doRemove(url, as);
- default: return Promise.reject(Error(`invalid action: ${action}`));;
- }
- }
- function doCache(url, as) {
- const req = new Request(url, {mode: "no-cors"});
- return caches.open(CACHE).
- then(cache => Promise.all([
- fetch(req).then(res => cache.put(url, res)),
- fetch(req).then(res => cache.put(as, res)),
- ]));
- }
- function doRemove(url, as) {
- return caches.open(CACHE).
- then(cache => Promise.all([cache.delete(url), cache.delete(as)]));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement