大网数据广告活动
Web 标准与前端开发

FetchEvent

· 52CE 我爱测

这是会在 ServiceWorkerGlobalScope中触发 `fetch` 事件的事件类型。它包含关于 fetch 的信息,包括 request 和接收方如何处理响应。它提供 FetchEvent.respondWith 方法,允许我们为此 fetch 提供一个响应。

Service Workers API

这是会在 ServiceWorkerGlobalScope中触发 fetch 事件的事件类型。它包含关于 fetch 的信息,包括 request 和接收方如何处理响应。它提供 FetchEvent.respondWith 方法,允许我们为此 fetch 提供一个响应。

构造函数

  • FetchEvent.FetchEvent()
    • : 创建一个新的 FetchEvent 对象。这个构造函数不是很常用。浏览器自己会创建这些对象,并为它们提供 fetch 事件的回调。

属性

从它的祖先 Event 继承属性。

  • FetchEvent.clientId
    • : 发起 fetch 的同源Client的 Client.id。
  • FetchEvent.preloadResponse
    • : 一个兑现为 Response 的 Promise,如果该 fetch 没有导航或者 navigation preload 未启用,则是 undefined。
  • FetchEvent.replacesClientId
    • : 页面导航期间正被替换的Client的 Client.id。
  • FetchEvent.resultingClientId
    • : 页面导航期间用于替换的Client的 Client.id。
  • FetchEvent.request
    • : 浏览器想要发送的 Request。

方法

从它的父元素 ExtendableEvent 继承方法。

  • FetchEvent.respondWith()
    • : 阻止浏览器的默认 fetch 操作,并且由你自己提供一个响应(可以是一个 promise)。
  • ExtendableEvent.waitUntil()
    • : 延长事件的生命周期。用于通知浏览器延长超出响应回复时间的任务,例如流和缓存。

示例

fetch 事件对非 GET 请求使用浏览器默认值。对于 GET 请求它试图在缓存中匹配,如果缓存中没有匹配,则回落到网络请求。如果在缓存中匹配成功,它将异步更新缓存,以供下次使用。

self.addEventListener("fetch", (event) => {
  // Let the browser do its default thing
  // for non-GET requests.
  if (event.request.method !== "GET") return;

  // Prevent the default, and handle the request ourselves.
  event.respondWith(
    (async () => {
      // Try to get the response from a cache.
      const cache = await caches.open("dynamic-v1");
      const cachedResponse = await cache.match(event.request);

      if (cachedResponse) {
        // If we found a match in the cache, return it, but also
        // update the entry in the cache in the background.
        event.waitUntil(cache.add(event.request));
        return cachedResponse;
      }

      // If we didn't find a match in the cache, use the network.
      return fetch(event.request);
    })(),
  );
});

规范

浏览器兼容性

参见

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。