gpt4 book ai didi

javascript - 如何使用 Service Worker 从一开始就处理获取事件?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:41:27 26 4
gpt4 key购买 nike

我正在尝试构建一个基本的服务 worker 来处理从我的网站发送的所有 AJAX 请求。

Service worker 订阅了 fetch 事件。我可以处理所有发送的请求,但它在第一次安装 service worker 时不起作用。

一旦安装了 service worker,如果我刷新网页,fetch 事件处理程序就会工作。

我希望我的服务 worker 从一开始就获取所有请求。可能吗?

这是我的代码:

index.html

<!DOCTYPE html>
<html>
<body>
<h2>Service Worker Demo Page</h2>
<script type="text/javascript">

if (navigator.serviceWorker) {

navigator.serviceWorker.register('./sw.js')
.then(function (registration) {
console.debug('Registration within scope %s. More details %O', registration.scope, registration);
return fetch('https://www.google.com');
})
.then(console.info)
.catch(console.warn);

}

</script>

</body>

sw.js

self.addEventListener('fetch', function (e) {
console.info('%s request to %s. More details: %o'
, e.request.method
, e.request.url
, e
);
});

最佳答案

的默认行为是在其 service worker 激活之前必须刷新网页。因此,您(用户)的“一开始”与 Service Worker 的“一开始”是不一样的。

但是,您可以使用 clients.claim() 覆盖此默认行为。了解一下 on MDN :

// sw.js
self.addEventListener('activate', function(event) {
event.waitUntil(self.clients.claim());
});

请注意,对于您的用例,您应该确保在触发任何获取事件之前注册并激活软件。

______

"Service Worker Lifecycle" 中阅读更多关于 Service Worker 生命周期的信息博客文章。以下是一些相关的要点...

  • A service worker won't receive events like fetch and push until it successfully finishes installing and becomes "active".
  • By default, a page's fetches won't go through a service worker unless the page request itself went through a service worker. So you'll need to refresh the page to see the effects of the service worker. clients.claim() can override this default, and take control of non-controlled pages.

关于javascript - 如何使用 Service Worker 从一开始就处理获取事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41224615/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com