访问服务工作者使用Webpack + Workbox从App构建中跳过

问题描述 投票:0回答:2

我有一个用Aurelia构建的PWA,用Webpack编译,使用生成sw.js服务工作文件的Workbox插件。我正在尝试制作“新版本可用”用户通知,以便用户在点击应用内的链接时可以激活新版本。

我在后台成功下载并安装了新版本,甚至检测到新版本已准备就绪。但是,当我尝试调用skipWaiting()方法强制刷新新版本的页面时,它失败了,因为显然我没有正确的范围或对象。

主要问题可能是我无法编辑实际的sw.js,因为它是自动生成的。这些例子都建议使用self.skipWaiting();,但我不知道如何访问该对象。

webpack.config.js

new WorkboxPlugin({
  globDirectory: './dist',
  globPatterns: ['**/*.{html,js,css,woff,woff2,ttf,svg,eot,jpg}'],
  swDest: './dist/sw.js',
  clientsClaim: true,
  skipWaiting: false, // because I want to notify the user and wait for response
}),

index.ejs

<script>
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/sw.js')
      .then(reg => {
        // make the registration available globally, for access within app
        window.myServiceWorkerReg = reg;
        // Check for update on loading the app (is this necessary?)
        return reg.update();
      })
      .catch(console.error);
  }
</script>

app.js

activate() {
  // listener for service worker update
  this.swReg = window.myServiceWorkerReg;
  console.warn('[app.js] ACTIVATE.', this.swReg);

  this.swReg.addEventListener('updatefound', () => {
    // updated service worker found in reg.installing!
    console.warn('[app.js] UPDATE FOUND.', this.swReg);

    const newWorker = this.swReg.installing;
    newWorker.addEventListener('statechange', () => {
      // has the service worker state changed?
      console.warn('[app.js]  STATE HAS CHANGED.', newWorker, newWorker.state);

      if (newWorker.state === 'installed') {
        // New service worker ready.

        // Notify user; callback for user request to load new app
        myUserMessage({ clickToActivate: () => {
          // reload fresh copy (do not cache)
          console.warn('[app.js] Post Action: skipWaiting.');
          // this.swReg.postMessage({ action: 'skipWaiting' });

          // THIS IS THE LINE THAT FAILS
          this.swReg.skipWaiting();
        }});
      }
    });
  });
}

一切都很好,除了最后一行(this.swReg.skipWaiting();)。有没有其他人使用过webpack + workbox插件,并且因为用户交互而得到了skipWaiting?

service-worker workbox-webpack-plugin aurelia-webpack
2个回答
1
投票

你无法在页面上调用它(app.js)。您在Service Worker脚本(service-worker.js)上调用self.skipWaiting。

https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/skipWaiting


1
投票

我终于开始工作了。一个问题是我使用的是旧版本的workbox-webpack-plugin。当前版本(4.2)包括服务工作者中的监听器,当向工作人员发送消息时可以触发self.skipWaiting(),如下所示:

newWorker.postMessage({ type: 'SKIP_WAITING' });

但是你必须确保配置有skipWaiting: false;并且你使用的是最新版本。

这些说明非常好:

https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin

https://developers.google.com/web/tools/workbox/guides/advanced-recipes#offer_a_page_reload_for_users

但是,我调整了我的应用程序和index.ejs文件中的服务工作者实例之间的工作。

webpack.config.js

new GenerateSW({
  globPatterns: ['dist/**/*.{html,js,css,woff,woff2,ttf,svg,eot,jpg}'],
  swDest: 'sw.js',
  clientsClaim: true,
  skipWaiting: false,
})),

index.ejs

<script>
  if ('serviceWorker' in navigator) {
    // register the service worker
    navigator.serviceWorker.register('/sw.js')
      .then(reg => {
        window.myWorkerReg = reg;
        // Check for update on loading the app (is this necessary?)
        return reg.update();
      })
      .catch(console.error);
    // The event listener that is fired when the service worker updates
    navigator.serviceWorker.addEventListener('controllerchange', function () {
      // when the service worker controller is changed, reload the page
      if (window.swRefreshing) return;
      window.location.reload();
      window.swRefreshing = true;
    });

  }
</script>

app.js

activate() {
  // listener for service worker update
  this.swReg = window.myWorkerReg;
  if (this.swReg) {
    // if there is already a new service worker ready to install, prompt user
    if (this.swReg.waiting) {
      this.promptUpdateServiceWorker(this.swReg.waiting);
    }
    // add listener to detect when a new service worker is downloaded
    this.swReg.addEventListener('updatefound', () => {
      // updated service worker is being installed
      const newWorker = this.swReg.installing;
      // add listener to detect when installation is finished
      newWorker.addEventListener('statechange', () => {
        if (newWorker.state === 'installed') {
          // New service worker ready to activate; prompt user
          this.promptUpdateServiceWorker(newWorker);
        }
      });
    });
  }
}

// listener for buildVersion
buildVersionChanged(buildVersion) {
  // through proprietary code, we've detected a new version could be downloaded now
  window.myWorkerReg.update();
}

// New service worker ready.  Show the notification
promptUpdateServiceWorker(newWorker) {
  // actual code for UI prompt will vary; this is pseudocode
  uiPrompt('New_version_ready').then((response) => {
    if (response.approved) {
      // reload fresh copy (do not cache)
      newWorker.postMessage({ type: 'SKIP_WAITING' });
    }
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.