自定义工作脚本位置

自定义工作位置

¥Custom worker location

默认情况下,调用 worker.start() 将注册位于 /mockServiceWorker.js 的 Service Worker 脚本。你可以使用 serviceWorker.url 选项自定义工作脚本的位置:

¥By default, calling worker.start() will register the Service Worker script located at /mockServiceWorker.js. You can customize the location of the worker script using the serviceWorker.url option:

await worker.start({
  serviceWorker: {
    // This is useful if your application follows
    // a strict directory structure.
    url: '/assets/mockServiceWorker.js',
  },
})

自定义工作范围

¥Custom worker scope

有多种方法允许工作线程控制其位置之外的页面。请注意,所有这些方法都意味着你可以访问开发服务器,对于大多数现代框架,你在某种程度上都可以这样做。这些建议可能会或可能不会起作用,具体取决于你使用的框架的功能。

¥There are multiple ways to allow the worker to control pages outside of its location. Note that all of these methods imply you have access to the development server, which with most modern frameworks you do to some extent. These suggestions may or may not work depending on the capabilities of the framework that you’re using.

选项 1:代理工作请求

¥Option 1: Proxy worker request

你可以创建从 /mockServiceWorker.js 到服务器上任何实际工作脚本位置的代理。在这种情况下,你可以使用默认的 worker.start() 调用,而无需自定义工作程序脚本位置选项。

¥You can create a proxy from /mockServiceWorker.js to any actual worker script location on the server. In that case, you can use the default worker.start() call without the custom worker script location options.

如果你的应用由 Express 提供服务,以下是创建此类代理请求的示例:

¥Here’s an example of creating such a proxy request if your application is served by Express:

// This proxy request allows the browser to register the
// Service Worker from the root while proxying the worker
// script file from a nested location in "/assets/".
app.get('/mockServiceWorker.js', (req, res) => {
  res.redirect('/assets/mockServiceWorker.js')
})

请查阅你的框架设置以了解有关创建代理路由的更多信息。

¥Please consult your framework’s setup to learn more about creating proxy routes.

选项 2:Service-Worker-Allowed 响应标头

¥Option 2: Service-Worker-Allowed response header

你可以通过在响应中向请求的工作脚本发送 Service-Worker-Allowed 标头来告诉浏览器忽略默认的工作范围限制。

¥You can tell the browser to ignore the default worker scope limitation by sending the Service-Worker-Allowed header in the response to the requested worker script.

app.get('/assets/mockServiceWorker.js', (req, res, next) => {
  // Allow the worker to control all the pages of the app.
  res.setHeader('Service-Worker-Allowed', '/')
  next()
})

Service-Worker-Allowed 标头必须存在于对工作者脚本的响应中:

¥The Service-Worker-Allowed header must be present on the response to the worker script:

GET /assets/mockServiceWorker.js HTTP/1.0
content-type: application/javascript; charset=utf-8;
service-worker-allowed: /

<CONTENTS OF THE FILE>