Skip to content

Commit

Permalink
test: custom service worker
Browse files Browse the repository at this point in the history
  • Loading branch information
qq815776412 committed May 28, 2024
1 parent f90f05e commit 29b2543
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
2 changes: 1 addition & 1 deletion packages/frontend/quasar.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ module.exports = configure(function (ctx) {
},

pwa: {
workboxPluginMode: 'GenerateSW', // 'GenerateSW' or 'InjectManifest'
workboxPluginMode: 'InjectManifest', // 'GenerateSW' or 'InjectManifest'
workboxOptions: {}, // only for GenerateSW

manifest: {
Expand Down
43 changes: 41 additions & 2 deletions packages/frontend/src-pwa/custom-service-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,45 @@ declare const self: ServiceWorkerGlobalScope &
typeof globalThis & { skipWaiting: () => void };

import { precacheAndRoute } from 'workbox-precaching';

// import { clientsClaim } from 'workbox-core';
import { registerRoute } from 'workbox-routing';
import { NetworkOnly } from 'workbox-strategies';
// 放在顶部,sw获得控制权,不然是下次打开页面获得
// clientsClaim();
// // 跳过等待
// self.skipWaiting();
// Use with precache injection
precacheAndRoute(self.__WB_MANIFEST);
precacheAndRoute(
self.__WB_MANIFEST.filter((entry) => {
if (typeof entry == 'string') {
return true;
}
return !entry.url.endsWith('.html');
})
);

self.addEventListener('install', () => {
console.log('Service Worker installing.');
});

self.addEventListener('activate', () => {
console.log('Service Worker activating.');
});

self.addEventListener('fetch', (event) => {
console.log('Fetching:', event);
});

// 自定义缓存策略
// 例如:网络优先策略
registerRoute(
({ request }) => {
console.log('Request mode:', request);
return request.mode === 'navigate';
}, // 这是 Workbox 推荐的检查 document 请求的方式
new NetworkOnly({
plugins: [
// 你可以在这里添加其他插件,例如请求失败时的回退机制等
]
})
);

0 comments on commit 29b2543

Please sign in to comment.