标签: workbox

如何使工作箱缓存跨源响应?

根据workbox doc,应配置跨域请求以确保正则表达式匹配 URL 的开头。但是,它不起作用。

Service Worker 代码如下所示。

importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js');

workbox.routing.registerRoute(
  /.*\.(png|jpg|jpeg|svg|gif)/,
  workbox.strategies.cacheFirst()
);

workbox.routing.registerRoute(
  new RegExp('^https://a248.e.akamai.net/.*'),
  workbox.strategies.cacheFirst()
);
Run Code Online (Sandbox Code Playgroud)

在页面中,来自相同来源资源的响应被缓存,但来自的响应https://a248.e.akami.net没有。

我的配置有问题吗?或者这是一个工作箱 3.0.0 错误?

progressive-web-apps workbox

5
推荐指数
1
解决办法
2817
查看次数

通过 service-worker 的请求被执行两次

我已经完成了一个简单的 service-worker 来延迟我的 JS 应用程序失败的请求(按照这个示例)并且它运行良好。但是当请求成功时我仍然有一个问题:请求完成了两次。一次是正常的,一次是由于fetch()我的电话而由服务人员进行的。

这是一个真正的问题,因为当客户端想要保存数据时,它们会被保存两次......

这是代码:

const queue = new workbox.backgroundSync.Queue('deferredRequestsQueue');
const requestsToDefer = [
  { urlPattern: /\/sf\/observation$/, method: 'POST' }
]
function isRequestAllowedToBeDeferred (request) {
  for (let i = 0; i < requestsToDefer.length; i++) {
    if (request.method && request.method.toLowerCase() === requestsToDefer[i].method.toLowerCase()
      && requestsToDefer[i].urlPattern.test(request.url)) {
      return true
    }
  }
  return false
}

self.addEventListener('fetch', (event) => {
  if (isRequestAllowedToBeDeferred(event.request)) {
    const requestClone = event.request.clone()
    const promiseChain = fetch(requestClone)
      .catch((err) => {
        console.log(`Request added to queue: ${event.request.url}`) …
Run Code Online (Sandbox Code Playgroud)

javascript fetch service-worker workbox

5
推荐指数
1
解决办法
1941
查看次数

skipWaiting() 没有安装卡在等待阶段的新 Service Worker

我正在创建一个 PWA,我想在更新的 Service Worker 可用时提示用户,但无论我是打电话skipWaiting()还是skipWaiting在开发控制台中手动按下,它都会陷入等待阶段。

只有当我首先停止现有的 Service Worker 时,才会安装新的 Service Worker。

我也尝试通过self.skipWaiting()在安装阶段直接调用来强制安装,但我更新后的 Service Worker 仍然陷入等待阶段。

这是我的设置。

sw.js

// when installing hydrate caches and notify user that reload if required (if any)
self.addEventListener('install', async () => {
    // self.skipWaiting();
    await hydrateCache();
});

self.addEventListener('message', (message) => {
    if (message.data === 'skipWaiting') {
        debugger;
        self.skipWaiting();
    }
});
Run Code Online (Sandbox Code Playgroud)

索引.html

navigator.serviceWorker.register('sw.js')
  .then(function (reg) {
     reg.onupdatefound = function() {
       var newServiceWorker = reg.installing;

       if (reg.waiting && confirm('Updates are available, Would …
Run Code Online (Sandbox Code Playgroud)

updating reactjs service-worker progressive-web-apps workbox

5
推荐指数
0
解决办法
1453
查看次数

PWA:未检测到匹配的 Service Worker。您可能需要重新加载页面

我收到此警告:

在此处输入图片说明

未检测到匹配的 Service Worker。您可能需要重新加载页面,或者检查当前页面的 service worker 是否也控制了清单中 URL 的开头。

我的服务人员正在工作的东西。

在此处输入图片说明

我什至尝试使用其他两个 URL,它们都使用 HTTP。


现在我将向您展示代码,我正在使用:

site.webmanifest

{
    ...
    "start_url": "/",
    "display": "standalone"
    ...
}
Run Code Online (Sandbox Code Playgroud)

为了创建我的 service-worker,我使用了 webpack 插件:WorkboxPlugin 结合 Laravel Mix:

webpack.mix.js

mix.webpackConfig({
    plugins: [
        build.jigsaw,
        build.browserSync(),
        build.watch(['source/**/*.md', 'source/**/*.php', 'source/**/*.scss', '!source/**/_tmp/*']),
        new WorkboxPlugin.GenerateSW({
            // these options encourage the ServiceWorkers to get in there fast
            // and not allow any straggling "old" SWs to hang around
            clientsClaim: true,
            skipWaiting: true,
        }),
    ],
    output: {
        publicPath: '/assets/build/', // fixes the output bug
    }, …
Run Code Online (Sandbox Code Playgroud)

service-worker progressive-web-apps workbox workbox-webpack-plugin

5
推荐指数
1
解决办法
1万
查看次数

为渐进式 Web 应用缓存设置最小网络类型 (WLAN)

我通过使用外部 API 的 Vue CLI 创建了一个 PWA。API 响应应该被缓存以供离线访问。

从文档https://cli.vuejs.org/core-plugins/pwa.html#configuration我在根目录中创建了一个vue.config.js文件

module.exports = {
  publicPath: '/pwa',
  pwa: {
    appleMobileWebAppCapable: 'yes',
    workboxPluginMode: 'GenerateSW',
    workboxOptions: {
      runtimeCaching: [
        {
          urlPattern: new RegExp('^https://example.com/'),
          handler: 'networkFirst', // Network first, Cache fallback
          options: {
            networkTimeoutSeconds: 5,
            cacheName: 'api-cache',
            cacheableResponse: {
              statuses: [0, 200],
            },
          },
        },
      ],
    },
  },
};
Run Code Online (Sandbox Code Playgroud)

该项目运行良好,但我想避免在非常糟糕的连接上从 API 加载数据。

我只想在 WLAN 网络连接上加载数据。有没有办法扩展配置并设置要检测的网络类型?该配置应称为

首先使用网络但仅使用 WLAN,否则使用缓存作为后备

javascript vue.js progressive-web-apps workbox

5
推荐指数
0
解决办法
63
查看次数

Workbox 5 语法错误 - 未捕获的类型错误:workbox.expiration.CacheableResponsePlugin 不是构造函数

我正在尝试为一个小型静态站点设置一个简单的 Service Worker,但出现 Service Worker 控制台错误:

sw.js:59 Uncaught TypeError: workbox.expiration.CacheableResponsePlugin is not a constructor

这是在线 new workbox.expiration.CacheableResponsePlugin

任何有关如何解决此问题的建议将不胜感激。

  workbox.routing.registerRoute(
    /\.(?:html)$/,
    new workbox.strategies.NetworkFirst({
      cacheName: 'html-cache',
      plugins: [
        new workbox.expiration.CacheableResponsePlugin({
          statuses: [0, 200],
        }),

        new workbox.expiration.ExpirationPlugin({
          maxEntries: 50,
          maxAgeSeconds: 5 * 60,
        })
      ]
    })
  )
Run Code Online (Sandbox Code Playgroud)

workbox

5
推荐指数
1
解决办法
2192
查看次数

向现有工作箱工作器注册 Firebase 服务工作器

我将 Google 的Workbox用于一些离线功能并在我的 angular 9 应用程序中进行缓存。对于推送消息,我们使用 Google 的Firebase

自从将 Web 应用程序更新为 Vue.js 后,我在访问网站时收到错误消息:

未捕获的 FirebaseError: Messaging: 我们无法注册默认的 Service Worker。未能注册为范围ServiceWorker(” https://my-domain.com/firebase-cloud-messaging-push-scope与脚本‘)(’ https://my-domain.com/firebase-messaging-sw。 js '):脚本具有不受支持的 MIME 类型 ('text/html')。(消息/失败的服务工作人员注册)。

是的,根目录下没有firebase-messaging-sw.js
一切都应该由 Workbox 处理。

我按照文档使用现有的服务工作者进行注册useServiceWorker(),但这会导致上述错误。

import * as firebase from 'firebase/app';
import 'firebase/messaging';
import { Workbox } from 'workbox-window';
import { environment } from './environments/environment';

...

if ('serviceWorker' in navigator && environment.production) {
  const scope = window.location.origin + window.location.pathname.split('/').slice(0, 3).join('/');
  const wb = new Workbox('/my-worker.js', …
Run Code Online (Sandbox Code Playgroud)

firebase vue.js service-worker angular workbox

5
推荐指数
0
解决办法
744
查看次数

带有工作箱的服务工作者 - 未捕获的语法错误:意外的标记“&lt;”..跳过等待

我已经用 CRA 创建了 React 应用程序。我想要定制软件。我正在使用workbox-build 和injectManifest 来创建我的SW。但我仍然坚持等待激活 =/ 和 Uncaught SyntaxError: Unexpected token '<'。或者..

如果我使用 sw-template2.js .. 我可以跳过等待.. 但我仍然收到 Uncaught SyntaxError: Unexpected token '<' 和白页,我需要手动刷新页面才能查看内容。有什么建议如何使用该软件顺利更新我的页面吗?

我的registerServiceWorker.js:

// In production, we register a service worker to serve assets from local cache.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs service-worker workbox

5
推荐指数
0
解决办法
1148
查看次数

无法在“缓存”上执行“放置”:workbox 和 nuxt

我使用的是 Nuxtjs 2.15.7,最近在我的控制台中收到此错误

在此输入图像描述

在此输入图像描述

当我搜索时,只需要@nuxt/pwa 发布. 但我的项目中没有pwa模块!

这是我的 package.json

{
  "name": "my-app",
  "version": "2.0.0",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "dev:host": "nuxt --hostname 0.0.0.0 --port 8000",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate"
  },
  "dependencies": {
    "@nuxtjs/auth": "^4.9.1",
    "@nuxtjs/axios": "^5.13.1",
    "@nuxtjs/device": "^2.1.0",
    "@nuxtjs/google-gtag": "^1.0.4",
    "@nuxtjs/gtm": "^2.4.0",
    "cookie-universal-nuxt": "^2.1.4",
    "core-js": "^3.15.1",
    "nuxt": "^2.15.7",
    "swiper": "^5.4.5",
    "v-viewer": "^1.5.1",
    "vee-validate": "^3.3.7",
    "vue-awesome-swiper": "^4.1.1",
    "vue-cropperjs": "^4.1.0",
    "vue-easy-dnd": "^1.12.2",
    "vue-persian-datetime-picker": "^2.2.0",
    "vue-product-zoomer": "^3.0.1",
    "vue-sweetalert2": "^4.2.1",
    "vue2-editor": "^2.10.2",
    "vuedraggable": "^2.24.0"
  },
  "devDependencies": { …
Run Code Online (Sandbox Code Playgroud)

javascript web-worker vue.js nuxt.js workbox

5
推荐指数
1
解决办法
1569
查看次数

Safari 浏览器始终会看到未更改的 Service Worker 的更新

我构建了一个 VueJS PWA 并用于register-service-worker管理服务工作者。我已经构建了该应用程序,因此当访问新路线时,它会手动检查服务工作人员的更新。如果有更新,它会显示提醒用户刷新。

但是,我在 Safari(MacOS 和 iOS)中遇到问题。虽然更新代码工作正常,但在 Safari 中访问 Web 应用程序时,每次路线更改时似乎都会不断触发“可用更新”警报,并且刷新似乎无法解决问题。就好像 Service Worker 没有在本地更新一样,即使 Web 应用程序显示了最新的更改。

这是手动检查路线更改的代码:

router.beforeEach((to, from, next) => {

    navigator.serviceWorker.getRegistration(`${process.env.BASE_URL}service-worker.js`).then(reg => {
        // check for updates to the service working on change of route
        reg.update();
    });
});
Run Code Online (Sandbox Code Playgroud)

registerServiceWorker.js然后,我在updated触发自定义事件的部分中进行了应用程序可以侦听的服务工作人员的更新:

/* eslint-disable no-console */

import { register } from 'register-service-worker'

if (process.env.NODE_ENV === 'production') {
  register(`${process.env.BASE_URL}service-worker.js`, {
    ready () {
      console.log(
        'App is being served from cache by a service worker.\n' 
      )
    }, …
Run Code Online (Sandbox Code Playgroud)

javascript vue.js service-worker progressive-web-apps workbox

5
推荐指数
0
解决办法
403
查看次数