From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- files/zh-cn/web/api/fetchevent/index.html | 164 +++++++++++++++++++++ .../web/api/fetchevent/respondwith/index.html | 141 ++++++++++++++++++ 2 files changed, 305 insertions(+) create mode 100644 files/zh-cn/web/api/fetchevent/index.html create mode 100644 files/zh-cn/web/api/fetchevent/respondwith/index.html (limited to 'files/zh-cn/web/api/fetchevent') diff --git a/files/zh-cn/web/api/fetchevent/index.html b/files/zh-cn/web/api/fetchevent/index.html new file mode 100644 index 0000000000..2b33e9de41 --- /dev/null +++ b/files/zh-cn/web/api/fetchevent/index.html @@ -0,0 +1,164 @@ +--- +title: FetchEvent +slug: Web/API/FetchEvent +translation_of: Web/API/FetchEvent +--- +

{{APIRef("Service Workers API")}}{{ SeeCompatTable() }}

+ +

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

+ +

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

+ +

构造函数

+ +
+
{{domxref("FetchEvent.FetchEvent()")}}
+
Creates a new FetchEvent object.
+
+ +

属性

+ +

Inherits properties from its ancestor, {{domxref("Event")}}.

+ +
+
{{domxref("FetchEvent.isReload")}} {{readonlyInline}}
+
Returns a {{jsxref("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.
+
{{domxref("FetchEvent.request")}} {{readonlyInline}}
+
Returns the {{domxref("Request")}} that triggered the event handler.
+
{{domxref("FetchEvent.clientId")}} {{readonlyInline}}
+
Returns the id of the client that the current service worker is controlling.
+
+ +

Deprecated properties

+ +
+
{{domxref("FetchEvent.client")}} {{readonlyInline}}
+
Returns the {{domxref("Client")}} that the current service worker is controlling.
+
+ +

方法

+ +

Inherits methods from its parent, {{domxref("ExtendableEvent")}}.

+ +
+
{{domxref("FetchEvent.respondWith()")}}
+
Resolves by returning a {{domxref("Response")}} or a network error  to Fetch.
+
{{domxref("ExtendableEvent.waitUntil", "ExtendableEvent.waitUntil()")}}
+
+

Extends the lifetime of the event.  It is intended to be called in the {{event("install")}} {{domxref("EventHandler")}} for the {{domxref("ServiceWorkerRegistration.installing", "installing")}} worker and on the {{event("active")}} {{domxref("EventHandler")}} for the {{domxref("ServiceWorkerRegistration.active", "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 {{domxref("InstallEvent")}} controls caching of a number of resources. The {{domxref("ServiceWorkerGlobalScope.onfetch")}} event handler then listens for the {{event("fetch")}} event. When fired, {{domxref("FetchEvent.respondWith()")}} returns a promise back to the controlled page. This promise resolves to the first matching URL request in the {{domxref("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 {{domxref("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
{{SpecName('Service Workers', '#fetch-event-section', 'FetchEvent')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatUnknown}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(44.0)}}
+
+ +

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

+ +

请参见

+ + diff --git a/files/zh-cn/web/api/fetchevent/respondwith/index.html b/files/zh-cn/web/api/fetchevent/respondwith/index.html new file mode 100644 index 0000000000..0840832a0f --- /dev/null +++ b/files/zh-cn/web/api/fetchevent/respondwith/index.html @@ -0,0 +1,141 @@ +--- +title: FetchEvent.respondWith() +slug: Web/API/FetchEvent/respondWith +translation_of: Web/API/FetchEvent/respondWith +--- +

{{APIRef("Service Workers API")}}{{SeeCompatTable}}

+ +

{{domxref("FetchEvent")}} 接口的 respondWith() 方法旨在包裹代码,这些代码为来自受控页面的request生成自定义的response。这些代码通过返回一个 {{domxref("Response")}} 、 network error 或者 Fetch的方式resolve。

+ +

有关跨域内容污染的渲染端安全检测与 {{domxref("Response")}} 体的透明度(或者不透明度)相关联,而不是URL。如果request是一个顶级的导航,而返回值是一个类型属性不透明的 {{domxref("Response")}}(即不透明响应体),一个 network error 将被返回给 Fetch。所有成功(非网络错误)响应的最终URL是请求的URL。

+ +

语法

+ +
FetchEvent.respondWith(
+  //Promise that resolves to a Response or a network error.
+​)
+ +

返回值

+ +

Void.

+ +

参数

+ +

任何自定义的响应生成代码。

+ +

示例

+ +

该代码片段来自 service worker fetch sample (run the fetch sample live)。 {{domxref("ServiceWorkerGlobalScope.onfetch")}} 事件处理程序侦听 {{event("fetch")}} 事件。当触发时,{{domxref("FetchEvent.respondWith", "FetchEvent.respondWith(any value)")}} 返回一个promise给受控页面。该promise在 {{domxref("Cache")}} 对象中查询第一个匹配URL请求。如果没有发现匹配项,该代码将转而从网络获取响应。

+ +

该代码也处理从 {{domxref("ServiceWorkerGlobalScope.fetch")}} 操作中抛出的异常。请注意,HTTP错误响应(例如404)不会触发异常。 它将返回具有相应错误代码集的正常响应对象。

+ +
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
{{SpecName('Service Workers', '#fetch-event-respondwith-method', 'respondWith()')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatUnknown}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(44.0)}}
+
+ +

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

+ +

请参见

+ + -- cgit v1.2.3-54-g00ecf