乐闻世界logo
搜索文章和话题

Can I have multiple service workers both intercept the same fetch request?

1个答案

1

In browsers, typically only one service worker can be activated per domain to intercept and handle requests. If multiple service workers are registered, a new service worker will take over the pages previously controlled by the old worker once it becomes inactive or is unloaded. This is because service workers are designed to allow a single worker to control all events, preventing multiple workers from responding differently to the same request.

Each service worker has a specific scope, which defines the pages it can control. If multiple service workers have overlapping scopes, the most recently registered worker will begin controlling those pages during the next page load, replacing the old worker.

However, you can register multiple service workers with different scopes, each controlling resources within its own scope. In this case, different service workers can be activated simultaneously based on their scopes, but each can only intercept requests within its own scope.

Example

  • sw1.js controls the /app1/ directory
  • sw2.js controls the /app2/ directory

If a user accesses /app1/index.html, only sw1.js can intercept this request. Similarly, accessing /app2/index.html will be intercepted by sw2.js only.

Therefore, although multiple service workers can be activated simultaneously, each handles requests within its own scope. They will not intercept the same request within the same scope simultaneously.

2024年6月29日 12:07 回复

你的答案