我正在使用 Create React App 实用程序创建一个 React App,我想覆盖它提供的默认服务工作线程。
由于我不想弹出我的应用程序,我使用该workbox-build包来创建我的服务工作者(我还使用 yarn 来安装该workbox-sw包)。
我的服务工作者代码如下:
/* eslint-disable no-restricted-globals */
import * as core from 'workbox-core';
import * as routing from 'workbox-routing';
import * as strategies from 'workbox-strategies';
import * as precaching from 'workbox-precaching';
self.addEventListener('message', event => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
core.clientsClaim();
routing.registerRoute(
new RegExp('^https://fonts.googleapis.com'),
new strategies.StaleWhileRevalidate({
cacheName: 'google-fonts-stylesheets-v1',
})
);
precaching.precacheAndRoute([]);
routing.registerNavigationRoute(
precaching.getCacheKeyForURL('/index.html'), {
blacklist: [/^\/_/, /\/[^/?]+\.[^/]+$/],
}
);
Run Code Online (Sandbox Code Playgroud)
我的workbox-build脚本是:
const …Run Code Online (Sandbox Code Playgroud) 很简单,我想在调试时禁用浏览器控制台中出现的重复工作箱消息的显示。例如,我不需要看到:
WorkBox: Using NetworkFirst to respond to '/fonts/KFOlCnqEu92Fr1MmEU9fBBc-.woff'
Run Code Online (Sandbox Code Playgroud)
它弄乱了我的 FireFox 控制台,这是我非常不喜欢的东西。如果你喜欢它,好吧,请不要试图改变我对这些无用(对我而言)消息的好处的看法。你知道怎么关掉吗?为了提供信息,我使用 Quasar 和 Vue 来创建 SPA - 甚至不是 PWA。谢谢。
我有一个完全静态的站点 - index.html和一些CSS/JS/PNG文件.我想使用服务工作者来缓存所有这些.似乎Workbox应该让这很容易.这是我的sw.js:
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.5.0/workbox-sw.js');
workbox.precaching.precacheAndRoute([]);
workbox.routing.registerNavigationRoute('/index.html');
Run Code Online (Sandbox Code Playgroud)
这是我的构建脚本:
const workboxBuild = require("workbox-build");
// NOTE: This should be run *AFTER* all your assets are built
const buildSW = async () => {
console.log("Generating sw.js...")
const {count, size, warnings} = await workboxBuild.injectManifest({
swSrc: "src/sw.js",
swDest: "build/sw.js",
globDirectory: "build",
globPatterns: [
"**/*.{js,css,html,png}",
]
})
warnings.forEach(console.warn);
console.log(`${count} files will be precached, totaling ${size} bytes.`);
}
buildSW();
Run Code Online (Sandbox Code Playgroud)
这一切似乎都很好.构建脚本运行,服务工作程序被激活,即使我处于脱机状态,我的站点也会继续工作.太棒了!
然后我对index.html进行了一些修改.我重装了我的页面.我在控制台中看到此消息,表明它已缓存我的index.html,尽管它仍在浏览器中显示旧的:
Precaching 1 file. 35 files are already cached.
Run Code Online (Sandbox Code Playgroud)
我相信这是正确的,它在显示缓存的一个后缓存新的index.html.那么接下来重装它应该显示新的index.html,对吗?
错误!再次重新加载,旧的index.html仍然显示.重复这几次,没有变化.要实际看到新的index.html,正常的重新加载永远不会工作,我需要做ctrl + shift + R.
这不可能是它应该如何工作,对吧?我必须遗漏一些明显的东西,但是我的代码非常简单,几乎从工作箱网站上的示例中提取出来,我看不出我搞砸了.
编辑:我在GitHub上 …
我正在尝试为我的应用程序构建 PWA;并且花了将近 48 小时试图弄清楚如何在 Laravel Mix 中使用 Workbox。具有讽刺意味的是,谷歌说 Workbox 旨在让事情变得简单!
呸!
好的,到目前为止我已经想通了——
我将需要使用 ,InjectManifest Plugin因为我想在我的 Service Worker 中集成推送通知服务
我不知道如何specifiy这些路径swSrc和swDest。
什么代码应该进入我的webpack.mix.js,我是否应该在我的resources/js文件夹中有一个临时的 service-worker 来在文件夹中创建一个新的 service worker public/。
有人可以帮忙吗?
PS:我几乎阅读了所有博客和帮助文章;但没有人谈论可靠地将 Workbox 与 Laravel 混合使用。真的很感激这里的一些帮助。
laravel progressive-web-apps laravel-mix workbox workbox-webpack-plugin
我从 webpack-workbox-plugin v4 迁移到 v5,但是当我尝试构建时,出现错误:
ERROR in Can't find self.__WB_MANIFEST in your SW source.
Child InjectManifest:
Asset Size Chunks Chunk Names
sw.js 1.5 KiB 0 [emitted] InjectManifest
Child html-webpack-plugin for "index.html":
1 asset
Run Code Online (Sandbox Code Playgroud)
是否__WB_MANIFEST会像 v4 一样创建 precach-manifest 文件并自动导入?
Webpack配置:
new WorkboxPlugin.InjectManifest({
swSrc: 'sw.js',
chunks: ['*.chunk.js'],
exclude: [/\.(?:png|jpg|jpeg|svg)$/, /\.map$/, /manifest\.json$/, /service-worker\.js$/, /sw\.js$/],
include: [path.resolve(process.cwd(), 'build')],
}),
Run Code Online (Sandbox Code Playgroud)
我的 sw.js:
importScripts('./ChabokSDKWorker.js', 'https://storage.googleapis.com/workbox-cdn/releases/5.0.0/workbox-sw.js');
/* eslint-disable no-undef */
if (workbox) {
workbox.core.skipWaiting();
workbox.core.clientsClaim();
workbox.precaching.cleanupOutdatedCaches();
// eslint-disable-next-line no-restricted-globals,no-underscore-dangle
workbox.precaching.precacheAndRoute(self.__WB_MANIFEST);
// java-script files cache
workbox.routing.registerRoute( …Run Code Online (Sandbox Code Playgroud) 我正在使用工作箱运行时缓存来缓存外部调用(materialize.css就是其中之一).在我的网络选项卡中,它显示请求来自serviceWorker(看起来很好):
但在缓存存储上,我的运行时缓存看起来是空
您可以在chromes的应用程序选项卡上看到我的服务工作者,这是网站:https://quack.surge.sh/
服务工作者代码:
const workboxSW = new self.WorkboxSW();
workboxSW.precache(fileManifest);
workboxSW.router.registerNavigationRoute("/index.html");workboxSW.router.registerRoute(/^https:\/\/res.cloudinary.com\/dc3dnmmpx\/image\/upload\/.*/, workboxSW.strategies.cacheFirst({}), 'GET');
workboxSW.router.registerRoute('https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css', workboxSW.strategies.cacheFirst({}), 'GET');
workboxSW.router.registerRoute('https://res.cloudinary.com/dc3dnmmpx/image/upload/(.*)', workboxSW.strategies.cacheFirst({}), 'GET');
Run Code Online (Sandbox Code Playgroud)
这是预期的行为吗?我对服务工作者很陌生,我不确定什么是正确的结果.
javascript caching service-worker progressive-web-apps workbox
我已经使用 Vue-cli 3 创建了一个 Vue 应用程序,并且我一直在尝试将 FCM 合并到其中。但是,我已经研究了两天,但仍然无法使其正常工作。
首先,这是我的
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase- app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
var config = {
messagingSenderId: "69625964474"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload)
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
}
return self.registration.showNotification(notificationTitle, notificationOptions)
});
Run Code Online (Sandbox Code Playgroud)
``
sorta 工作的一种解决方案是我将此文件移动到文件public夹中并App.vue使用
const registration = await navigator.serviceWorker.register(`${process.env.BASE_URL}firebase-messaging-sw.js`)
messaging.useServiceWorker(registration)
Run Code Online (Sandbox Code Playgroud)
但是,那么我将有两个 service worker(另一个来自 Vue 本身)。
我尝试vue.config.js通过添加以下配置来修改而不是尝试使用 Workbox: …
Android 和桌面版 Chrome 支持“beforeinstallpromp”事件,该事件可以显示添加到主屏幕横幅。我尝试在 iOS 中为我的 PWA 使用相同的 javascript 代码,但它不起作用。
/**
* Clear caches
*/
function pwaClearCaches()
{
//Clear caches
caches.keys().then(function(names) {
for (let name of names) {
caches.delete(name);
}
});
}
var pwa_app_installed = false; //PWA is already installed
var deferredPrompt; //Link to show dialog event
$(document).ready(function(){
if (window.location.protocol === 'http:') { //???? ??? HTTP ????????, ? ?? HTTPS
console.log(lang.t('You need HTTPS for work'));
}
if ('serviceWorker' in navigator) {
/**
* ????????????? ?? ???????????? ?????? ??????, ????? ????? …Run Code Online (Sandbox Code Playgroud)我想制作一个可离线使用的单页应用程序。所以我想在我的 Vue web 应用程序中使用 PWA Service Worker 并使用 typescript 和 workbox。我按照https://vite-plugin-pwa.netlify.app/guide/inject-manifest.html#typescript-support中的示例进行操作。
在构建打字稿时,我遇到很多TS2403错误,例如:
node_modules/typescript/lib/lib.webworker.d.ts:5720:13 - error TS2403: Subsequent variable declarations must have the same type. Variable 'onoffline' must be of type '((this: Window, ev: Event) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null'.
// ...
Found 21 errors in 2 files.
Errors Files
3 node_modules/typescript/lib/lib.dom.d.ts:25
18 node_modules/typescript/lib/lib.webworker.d.ts:25
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! vite-project@0.0.0 build: …Run Code Online (Sandbox Code Playgroud) 我在安装事件中使用服务工作者和预缓存资产。
我还有fetch侦听器,它在运行时动态拦截请求和缓存。我知道人们说将 indexeddb 用于动态内容,例如 json 数据和可能的图像。
问题:为什么即使它是请求/响应存储,也为该 json 数据使用缓存 API 不是一个好习惯?
我问这个的原因是因为我尝试了以下操作:我index.html and main.js在install事件中预先缓存,并且在main.js我的axios请求中返回一些 json 并将其放入index.html. 如果我使用动态缓存,这意味着当对该 json api 端点发出请求时,它首先进入我的服务工作者,它获取响应并将其放入cache. 然后我测试了一下,当在离线模式下刷新页面时,我仍然得到相同的结果(json 数据相应地放在 index.html 中)。
所以我猜即使缓存 API 存储请求/响应,它仍然可以完美地用于 json 端点 api url。
知道为什么在使用服务工作者时更喜欢 indexeddb 而不是缓存 API 吗?
workbox ×10
javascript ×6
vue.js ×2
caching ×1
console ×1
dom-events ×1
ios ×1
laravel ×1
laravel-mix ×1
quasar ×1
reactjs ×1
typescript ×1
vite ×1
vue-cli ×1
vuejs2 ×1
vuejs3 ×1
webpack ×1