openharmony 鸿蒙 arkts-apis-webview-WebResourceHandler

2026-08-25 浏览 (1)

Class (WebResourceHandler)

Implements a WebResourceHandler object, which can return custom response headers and response bodies to the Web component.

NOTE

  • 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.

  • The initial APIs of this class are supported since API version 12.

  • The sample effect is subject to the actual device.

Modules to Import

import { webview } from '@kit.ArkWeb';

didReceiveResponse12+

didReceiveResponse(response: WebSchemeHandlerResponse): void

Sends a response header to the intercepted request.

System capability: SystemCapability.Web.Webview.Core

Parameters

NameTypeMandatoryDescription
responseWebSchemeHandlerResponseYesResponse to send.

Error codes

For details about the error codes, see Webview Error Codes and Universal Error Codes.

Error CodeError Message
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified.
17100021The resource handler is invalid.

Example

For details about the example, see OnRequestStart.

didReceiveResponseBody12+

didReceiveResponseBody(data: ArrayBuffer): void

Sends a response body to the intercepted request.

System capability: SystemCapability.Web.Webview.Core

Parameters

NameTypeMandatoryDescription
dataArrayBufferYesResponse body.

Error codes

For details about the error codes, see Webview Error Codes and Universal Error Codes.

Error CodeError Message
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified.
17100021The resource handler is invalid.

Example

For details about the example, see OnRequestStart.

didFinish12+

didFinish(): void

Notifies the Web component that this request is completed and that no more data is available. Before calling this API, you need to call didReceiveResponse to send a response header for this request.

System capability: SystemCapability.Web.Webview.Core

Error codes

For details about the error codes, see Webview Error Codes.

Error CodeError Message
17100021The resource handler is invalid.

Example

For details about the example, see OnRequestStart.

didFail12+

didFail(code: WebNetErrorList): void

Notifies the ArkWeb kernel that this request fails. Before calling this API, call didReceiveResponse to send a response header to this request.

System capability: SystemCapability.Web.Webview.Core

Parameters

NameTypeMandatoryDescription
codeWebNetErrorListYesNetwork error code.

Error codes

For details about the error codes, see Webview Error Codes and Universal Error Codes.

Error CodeError Message
401Parameter error. Possible causes: 1. Incorrect parameter types.
17100021The resource handler is invalid.

Example

For details about the example, see OnRequestStart.

didFail20+

didFail(code: WebNetErrorList, completeIfNoResponse: boolean): void

Notifies the ArkWeb engine that the intercepted request should fail. If completeIfNoResponse is set to false, call didReceiveResponse first to transfer the constructed response header to the intercepted request. If completeIfNoResponse is set to true and didReceiveResponse is not called before this method is called, a response header containing the network error code -104 is automatically generated. For details, see WebNetErrorList.

System capability: SystemCapability.Web.Webview.Core

Parameters

NameTypeMandatoryDescription
codeWebNetErrorListYesNetwork error code.
completeIfNoResponsebooleanYesWhether to complete the network request if didReceiveResponse has not been called before this API is called. The value true indicates that when didReceiveResponse 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 to be called and the response to be passed, and will not complete the network request directly.

Error codes

For details about the error codes, see Webview Error Codes.

Error CodeError Message
17100101The errorCode is either ARKWEB_NET_OK or outside the range of error codes in WebNetErrorList.
17100021The resource handler is invalid.

Example

// xxx.ets
import { webview, WebNetErrorList } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct WebComponent {
  controller: webview.WebviewController = new webview.WebviewController();
  schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler();

  build() {
    Column() {
      Web({ src: 'https://www.example.com', controller: this.controller })
        .onControllerAttached(() => {
          try {
            this.schemeHandler.onRequestStart((request: webview.WebSchemeHandlerRequest, resourceHandler: webview.WebResourceHandler) => {
              console.info("[schemeHandler] onRequestStart");
              try {
                console.info("[schemeHandler] onRequestStart url:" + request.getRequestUrl());
                console.info("[schemeHandler] onRequestStart method:" + request.getRequestMethod());
                console.info("[schemeHandler] onRequestStart referrer:" + request.getReferrer());
                console.info("[schemeHandler] onRequestStart isMainFrame:" + request.isMainFrame());
                console.info("[schemeHandler] onRequestStart hasGesture:" + request.hasGesture());
                console.info("[schemeHandler] onRequestStart header size:" + request.getHeader().length);
                console.info("[schemeHandler] onRequestStart resource type:" + request.getRequestResourceType());
                console.info("[schemeHandler] onRequestStart frame url:" + request.getFrameUrl());
                let header = request.getHeader();
                for (let i = 0; i < header.length; i++) {
                  console.info("[schemeHandler] onRequestStart header:" + header[i].headerKey + " " + header[i].headerValue);
                }
                let stream = request.getHttpBodyStream();
                if (stream) {
                  console.info("[schemeHandler] onRequestStart has http body stream");
                } else {
                  console.info("[schemeHandler] onRequestStart has no http body stream");
                }
              } catch (error) {
                console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
              }

              if (request.getRequestUrl().endsWith("example.com")) {
                return false;
              }

              try {
                // Call didFail(WebNetErrorList.ERR_FAILED, true) to automatically construct a network request error ERR_CONNECTION_FAILED.
                resourceHandler.didFail(WebNetErrorList.ERR_FAILED, true);
              } catch (error) {
                // When error.code is 17100101(The errorCode is either ARKWEB_NET_OK or outside the range of error codes in WebNetErrorList)
                // and the code value of didFail(code: WebNetErrorList, completeIfNoResponse: boolean) is not null, the API is still called.
                console.error(`[schemeHandler] ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
              }
              return true;
            })

            this.schemeHandler.onRequestStop((request: webview.WebSchemeHandlerRequest) => {
              console.info("[schemeHandler] onRequestStop");
            });

            this.controller.setWebSchemeHandler('https', this.schemeHandler);
          } catch (error) {
            console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
          }
        })
        .javaScriptAccess(true)
        .domStorageAccess(true)
    }
  }
}

你可能感兴趣的鸿蒙文章

openharmony 鸿蒙 arkts-apis-webview-WebviewController

openharmony 鸿蒙 arkts-apis-webview-t

openharmony 鸿蒙 arkts-apis-webview

openharmony 鸿蒙 capi-arkweb-type-h

openharmony 鸿蒙 arkts-basic-components-web-FullScreenExitHandler

openharmony 鸿蒙 arkts-apis-webview-WebDownloadManager

openharmony 鸿蒙 arkts-basic-components-web-VerifyPinHandler

openharmony 鸿蒙 capi-web-arkweb-webmessage8h

openharmony 鸿蒙 arkts-apis-webview-NativeMediaPlayerHandler

openharmony 鸿蒙 capi-web-arkweb-proxymethodwithresult

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/4Q1aSn85