• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Class (WebResourceHandler)
2
3Implements a **WebResourceHandler** object, which can return custom response headers and response bodies to the **Web** component.
4
5> **NOTE**
6>
7> - The initial APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
8>
9> - The initial APIs of this class are supported since API version 12.
10>
11> - You can preview how this component looks on a real device, but not in DevEco Studio Previewer.
12
13## didReceiveResponse<sup>12+</sup>
14
15didReceiveResponse(response: WebSchemeHandlerResponse): void
16
17Sends a response header to the intercepted request.
18
19**System capability**: SystemCapability.Web.Webview.Core
20
21**Parameters**
22
23| Name         | Type   |  Mandatory | Description                                           |
24| ---------------| ------- | ---- | ------------- |
25| response      | [WebSchemeHandlerResponse](./arkts-apis-webview-WebSchemeHandlerResponse.md)  | Yes  | Response to send.|
26
27**Error codes**
28
29For details about the error codes, see [Webview Error Codes](errorcode-webview.md).
30
31| Error Code| Error Message                             |
32| -------- | ------------------------------------- |
33|  401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified.    |
34| 17100021 | The resource handler is invalid. |
35
36**Example**
37
38For details about the example, see [OnRequestStart](./arkts-apis-webview-WebSchemeHandler.md#onrequeststart12).
39
40## didReceiveResponseBody<sup>12+</sup>
41
42didReceiveResponseBody(data: ArrayBuffer): void
43
44Sends a response body to the intercepted request.
45
46**System capability**: SystemCapability.Web.Webview.Core
47
48**Parameters**
49
50| Name         | Type   |  Mandatory | Description                                           |
51| ---------------| ------- | ---- | ------------- |
52| data      | ArrayBuffer  | Yes  | Response body.|
53
54**Error codes**
55
56For details about the error codes, see [Webview Error Codes](errorcode-webview.md).
57
58| Error Code| Error Message                             |
59| -------- | ------------------------------------- |
60|  401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified.    |
61| 17100021 | The resource handler is invalid. |
62
63**Example**
64
65For details about the example, see [OnRequestStart](./arkts-apis-webview-WebSchemeHandler.md#onrequeststart12).
66
67## didFinish<sup>12+</sup>
68
69didFinish(): void
70
71Notifies the **Web** component that this request is completed and that no more data is available. Before calling this API, you need to call [didReceiveResponse](#didreceiveresponse12) to send a response header for this request.
72
73**System capability**: SystemCapability.Web.Webview.Core
74
75**Error codes**
76
77For details about the error codes, see [Webview Error Codes](errorcode-webview.md).
78
79| Error Code| Error Message                             |
80| -------- | ------------------------------------- |
81| 17100021 | The resource handler is invalid. |
82
83**Example**
84
85For details about the example, see [OnRequestStart](./arkts-apis-webview-WebSchemeHandler.md#onrequeststart12).
86
87## didFail<sup>12+</sup>
88
89didFail(code: WebNetErrorList): void
90
91Notifies the ArkWeb kernel that this request fails. Before calling this API, call [didReceiveResponse](#didreceiveresponse12) to send a response header to this request.
92
93**System capability**: SystemCapability.Web.Webview.Core
94
95**Parameters**
96
97| Name  | Type   |  Mandatory | Description                      |
98| --------| ------- | ---- | ---------------------------|
99|  code | [WebNetErrorList](arkts-apis-netErrorList.md#webneterrorlist) | Yes  | Network error code.|
100
101**Error codes**
102
103For details about the error codes, see [Webview Error Codes](errorcode-webview.md).
104
105| Error Code| Error Message                             |
106| -------- | ------------------------------------- |
107| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. |
108| 17100021 | The resource handler is invalid. |
109
110**System capability**: SystemCapability.Web.Webview.Core
111
112**Example**
113
114For details about the example, see [OnRequestStart](./arkts-apis-webview-WebSchemeHandler.md#onrequeststart12).
115
116## didFail<sup>20+</sup>
117
118didFail(code: WebNetErrorList, completeIfNoResponse: boolean): void
119
120Notifies the ArkWeb engine that the intercepted request should fail. If **completeIfNoResponse** is set to **false**, call [didReceiveResponse](#didreceiveresponse12) first to transfer the constructed response header to the intercepted request. If **completeIfNoResponse** is set to **true** and [didReceiveResponse](#didreceiveresponse12) is not called before this method is called, a response header containing the network error code -104 is automatically generated. For details, see [WebNetErrorList](arkts-apis-netErrorList.md#webneterrorlist).
121
122**System capability**: SystemCapability.Web.Webview.Core
123
124**Parameters**
125
126| Name  | Type   |  Mandatory | Description                      |
127| --------| ------- | ---- | ---------------------------|
128|  code | [WebNetErrorList](arkts-apis-netErrorList.md#webneterrorlist) | Yes  | Network error code.|
129|  completeIfNoResponse | boolean | Yes  | Whether to complete the network request if [didReceiveResponse](#didreceiveresponse12) has not been called before this API is called. The value **true** indicates that when [didReceiveResponse](#didreceiveresponse12) has not been called, a response header containing the network error code -104 is automatically generated to complete the network request. The value **false** indicates that the application will wait for [didReceiveResponse](#didreceiveresponse12) to be called and the response to be passed, and will not complete the network request directly.|
130
131**Error codes**
132
133For details about the error codes, see [Webview Error Codes](errorcode-webview.md).
134
135| Error Code| Error Message                             |
136| -------- | ------------------------------------- |
137| 17100101 | The errorCode is either ARKWEB_NET_OK or outside the range of error codes in WebNetErrorList. |
138| 17100021 | The resource handler is invalid. |
139
140**Example**
141
142```ts
143// xxx.ets
144import { webview, WebNetErrorList } from '@kit.ArkWeb';
145import { BusinessError } from '@kit.BasicServicesKit';
146
147@Entry
148@Component
149struct WebComponent {
150  controller: webview.WebviewController = new webview.WebviewController();
151  schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler();
152
153  build() {
154    Column() {
155      Web({ src: 'https://www.example.com', controller: this.controller })
156        .onControllerAttached(() => {
157          try {
158            this.schemeHandler.onRequestStart((request: webview.WebSchemeHandlerRequest, resourceHandler: webview.WebResourceHandler) => {
159              console.log("[schemeHandler] onRequestStart");
160              try {
161                console.log("[schemeHandler] onRequestStart url:" + request.getRequestUrl());
162                console.log("[schemeHandler] onRequestStart method:" + request.getRequestMethod());
163                console.log("[schemeHandler] onRequestStart referrer:" + request.getReferrer());
164                console.log("[schemeHandler] onRequestStart isMainFrame:" + request.isMainFrame());
165                console.log("[schemeHandler] onRequestStart hasGesture:" + request.hasGesture());
166                console.log("[schemeHandler] onRequestStart header size:" + request.getHeader().length);
167                console.log("[schemeHandler] onRequestStart resource type:" + request.getRequestResourceType());
168                console.log("[schemeHandler] onRequestStart frame url:" + request.getFrameUrl());
169                let header = request.getHeader();
170                for (let i = 0; i < header.length; i++) {
171                  console.log("[schemeHandler] onRequestStart header:" + header[i].headerKey + " " + header[i].headerValue);
172                }
173                let stream = request.getHttpBodyStream();
174                if (stream) {
175                  console.log("[schemeHandler] onRequestStart has http body stream");
176                } else {
177                  console.log("[schemeHandler] onRequestStart has no http body stream");
178                }
179              } catch (error) {
180                console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
181              }
182
183              if (request.getRequestUrl().endsWith("example.com")) {
184                return false;
185              }
186
187              try {
188                // Call didFail(WebNetErrorList.ERR_FAILED, true) to automatically construct a network request error ERR_CONNECTION_FAILED.
189                resourceHandler.didFail(WebNetErrorList.ERR_FAILED, true);
190              } catch (error) {
191                console.error(`[schemeHandler] ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
192              }
193              return true;
194            })
195
196            this.schemeHandler.onRequestStop((request: webview.WebSchemeHandlerRequest) => {
197              console.log("[schemeHandler] onRequestStop");
198            });
199
200            this.controller.setWebSchemeHandler('https', this.schemeHandler);
201          } catch (error) {
202            console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
203          }
204        })
205        .javaScriptAccess(true)
206        .domStorageAccess(true)
207    }
208  }
209}
210```
211