FetchEvent - Web API 接口参考 编辑

这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。

使用ServiceWorker技术时,页面的提取动作会在ServiceWorker作用域(ServiceWorkerGlobalScope)中触发fetch事件.

使用 ServiceWorkerGlobalScope.onfetch或addEventListener监听.
该事件回调会注入FetchEvent参数.它携带了有关请求和结果响应的信息以及方法FetchEvent.respondWith() ,允许我们向受控页面提供任意响应.

构造函数

FetchEvent.FetchEvent()
Creates a new FetchEvent object.

属性

Inherits properties from its ancestor, Event.

FetchEvent.isReload 只读
Returns a Boolean that is true if the event was dispatched with the user's intention for the page to reload, and false otherwise. Typically, pressing the refresh button in a browser is a reload, while clicking a link and pressing the back button is not.
FetchEvent.request 只读
Returns the Request that triggered the event handler.
FetchEvent.clientId 只读
Returns the id of the client that the current service worker is controlling.

Deprecated properties

FetchEvent.client 只读
Returns the Client that the current service worker is controlling.

方法

Inherits methods from its parent, ExtendableEvent.

FetchEvent.respondWith()
Resolves by returning a Response or a network error  to Fetch.
ExtendableEvent.waitUntil()

Extends the lifetime of the event.  It is intended to be called in the install EventHandler for the installing worker and on the active EventHandler for the active worker.

示例

This code snippet is from the service worker fetch sample (run the fetch sample live). In an earlier part of the code,  an InstallEvent controls caching of a number of resources. The ServiceWorkerGlobalScope.onfetch event handler then listens for the fetch event. When fired, FetchEvent.respondWith() returns a promise back to the controlled page. This promise resolves to the first matching URL request in the Cache object. If no match is found (i.e. that resource wasn't cached in the install phase), the code fetches a response from the network.

The code also handles exceptions thrown from the ServiceWorkerGlobalScope.fetch() operation. Note that a HTTP error response (e.g., 404) doesn't trigger an exception. It returns a normal response object that has the appropriate error code set.

self.addEventListener('fetch', function(event) {
  console.log('Handling fetch event for', event.request.url);

  event.respondWith(
    caches.match(event.request).then(function(response) {
      if (response) {
        console.log('Found response in cache:', response);

        return response;
      }
      console.log('No response found in cache. About to fetch from network...');

      return fetch(event.request).then(function(response) {
        console.log('Response from network is:', response);

        return response;
      }).catch(function(error) {
        console.error('Fetching failed:', error);

        throw error;
      });
    })
  );
});

规范

SpecificationStatusComment
Service Workers
FetchEvent
Working DraftInitial definition.

浏览器兼容性

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support40.044.0 (44.0)[1]未实现24未实现
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support未实现?44.0 (44.0)(Yes)未实现?未实现44.0

[1] Service workers (and Push) have been disabled in the Firefox 45 and 52 Extended Support Releases (ESR.)

请参见

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

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

发布评论

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

词条统计

浏览:96 次

字数:12540

最后编辑:7 年前

编辑次数:0 次

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