FetchEvent - Web APIs 编辑

This is the event type for fetch events dispatched on the service worker global scope. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the event.respondWith() method, which allows us to provide a response to this fetch.

Constructor

FetchEvent()
Creates a new FetchEvent object. This constructor is not typically used. The browser creates these objects itself and provides them to fetch event callbacks.

Properties

Inherits properties from its ancestor, Event.

FetchEvent.clientId Read only
The id of the same-origin client that initiated the fetch.
FetchEvent.preloadResponse Read only
A Promise for a Response, or undefined if this fetch is not a navigation, or navigation preload is not enabled.
FetchEvent.replacesClientId Read only
The id of the client that is being replaced during a page navigation.
FetchEvent.resultingClientId Read only
The id of the client that replaces the previous client during a page navigation.
FetchEvent.request Read only
The Request the browser intends to make.

Methods

Inherits methods from its parent, ExtendableEvent.

FetchEvent.respondWith()
Prevent the browser's default fetch handling, and provide (a promise for) a response yourself.
ExtendableEvent.waitUntil()

Extends the lifetime of the event. Used to notify the browser of tasks that extend beyond the returning of a response, such as streaming and caching.

Examples

This fetch event uses the browser default for non-GET requests. For GET requests it tries to return a match in the cache, and falls back to the network. If it finds a match in the cache, it asynchronously updates the cache for next time.

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 function() {
    // 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);
  }());
});

Specifications

SpecificationStatusComment
Service Workers
The definition of 'FetchEvent()' in that specification.
Working DraftInitial definition.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:173 次

字数:5712

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文