-
Notifications
You must be signed in to change notification settings - Fork 2
/
sw.js
1 lines (1 loc) · 4.53 KB
/
sw.js
1
importScripts("https://jsd.onmicrosoft.cn/npm/workbox-sw/build/workbox-sw.js"),importScripts("https://cdn.webpushr.com/sw-server.min.js"),workbox?console.log("Workbox 加载成功🎉"):console.log("Workbox 加载失败😬"),self.addEventListener("install",(async()=>{await self.skipWaiting(),console.log("Service Worker 开始安装🎊")})),self.addEventListener("activate",(async()=>{await self.clients.claim(),console.log("Service Worker 安装完成,开始启动✨"),self.clients.matchAll().then((e=>{e.forEach((e=>e.postMessage({type:"refresh"})))}))})),self.addEventListener("online",(()=>{console.log("网络已恢复,通知客户端刷新页面"),self.clients.matchAll().then((e=>{e.forEach((e=>e.postMessage({type:"refresh"})))}))})),self.__WB_DISABLE_DEV_LOGS=!0,workbox.precaching.cleanupOutdatedCaches(),workbox.core.setCacheNameDetails({prefix:"CC的部落格",suffix:"缓存",precache:"预先",runtime:"运行时",googleAnalytics:"离线谷歌分析"}),workbox.precaching.precacheAndRoute([{revision:"79d3c511db787e0cfc6ce459ad471990",url:"./offline/index.html"}],{ignoreUrlParametersMatching:[/.*/],directoryIndex:null}),workbox.navigationPreload.enable();const currentDomain=self.location.hostname,MIN=60,HOUR=3600,DAY=86400,WEEK=7*DAY,MONTH=30*DAY,YEAR=365*DAY,mainCdnUrl="https://jsd.onmicrosoft.cn",fallbackCdnUrls=["https://jsd.onmicrosoft.cn","https://ccknbc.cdn.xzzo.cn","https://cdn.jsdmirror.cn","https://cdn.jsdmirror.com","https://fastly.jsdelivr.net","https://gcore.jsdelivr.net"],invalidCdnUrls=["https://cdn.jsdelivr.net","https://cdn1.tianli0.top","https://cdn.jsdelivr.ren","https://cdn.chuqis.com","https://cdn2.chuqis.com","https://jsd.cdn.zzko.cn","https://jsdelivr.goodboyboy.top"],referrerDomains=["cdn.nlark.com","pic1.afdiancdn.com","f.video.weibocdn.com"],mainSiteUrl="https://blog.ccknbc.cc",backupSiteUrls=["https://vercel.blog.ccknbc.cc","https://cloudflare.blog.ccknbc.cc","https://netlify.blog.ccknbc.cc","https://github.blog.ccknbc.cc","https://gitlab.blog.ccknbc.cc","https://ccknbc.bitbucket.io"];function isCdnUrl(e,t){return t.some((t=>e.startsWith(t)))}async function handleCdnRequest(e,t){let n=[];for(const r of t)if(!n.includes(r)){const t=new Request(r+e.url.substring(e.url.indexOf("/",8)));try{const e=await fetch(t,{cache:"reload"});if(e.ok)return e;n.push(r)}catch(e){n.push(r)}}throw new Error("所有备用 CDN 镜像请求失败")}function handleEmptyReferrer(e){return fetch(e,{referrerPolicy:"no-referrer"})}async function handleMainSiteRequest(e){let t=[];for(const n of backupSiteUrls)if(!t.includes(n)){const r=new Request(n+e.url.substring(e.url.indexOf("/",8)));try{const s=await fetch(r,{cache:"reload"});if(s.ok){const t=new Response(s.body,{status:s.status,statusText:s.statusText,headers:s.headers});return t.url=e.url,t}t.push(n)}catch(e){t.push(n)}}throw new Error("所有备用站点请求失败")}self.addEventListener("fetch",(e=>{const t=e.request,n=new URL(t.url),r=n.hostname;n.href.startsWith(mainSiteUrl)?e.respondWith(fetch(t).then((e=>{if(e.ok)return e;throw new Error("主站请求失败")})).catch((()=>handleMainSiteRequest(t)))):n.href.startsWith(mainCdnUrl)?e.respondWith(fetch(t).then((e=>{if(e.ok)return e;throw new Error("主要CDN请求失败")})).catch((()=>handleCdnRequest(t,fallbackCdnUrls)))):isCdnUrl(n.href,invalidCdnUrls)||isCdnUrl(n.href,fallbackCdnUrls)?e.respondWith(handleCdnRequest(t,fallbackCdnUrls)):referrerDomains.includes(r)&&e.respondWith(handleEmptyReferrer(t))}));const Offline=new workbox.routing.Route((({request:e})=>"navigate"===e.mode),new workbox.strategies.NetworkOnly({plugins:[new workbox.precaching.PrecacheFallbackPlugin({fallbackURL:"/offline/index.html"})]}));workbox.routing.registerRoute(Offline),workbox.routing.registerRoute((({request:e})=>!e.url.includes(currentDomain)&&("style"===e.destination||"script"===e.destination||"font"===e.destination||"worker"===e.destination||e.url.endsWith("woff2"))),new workbox.strategies.StaleWhileRevalidate({cacheName:"备用CDN资源",plugins:[new workbox.expiration.ExpirationPlugin({maxEntries:200,maxAgeSeconds:MONTH,purgeOnQuotaError:!0}),new workbox.cacheableResponse.CacheableResponsePlugin({statuses:[0,200]})]})),workbox.routing.registerRoute((({request:e})=>e.url.includes(currentDomain)&&("style"===e.destination||"script"===e.destination||"worker"===e.destination||e.url.endsWith("/favicon.ico"))),new workbox.strategies.StaleWhileRevalidate({cacheName:"静态资源",plugins:[new workbox.expiration.ExpirationPlugin({maxEntries:10,maxAgeSeconds:MONTH,purgeOnQuotaError:!0}),new workbox.cacheableResponse.CacheableResponsePlugin({statuses:[0,200]})]}));