DEV Community

Cover image for Intercept the network Intercept the network requests initiated by Web components
liu yang
liu yang

Posted on

Intercept the network Intercept the network requests initiated by Web components

Setting Up Network Interceptors for Web Components in HarmonyOS Next

Setting Up Network Interceptors

To set up a network interceptor for a specific Web component or ServiceWorker, you can use the ArkWeb_SchemeHandler. This handler is triggered when the Web kernel issues a request for the specified scheme. The network interceptor must be set up after the Web component has been initialized.

Callbacks

  • ArkWeb_OnRequestStart: Triggered when a request starts.
  • ArkWeb_OnRequestStop: Triggered when a request ends.

Example: Intercepting the First Request

To intercept the first request made by a Web component, you can initialize the Web component using initializeWebEngine and then set up the interceptor.

// Create an ArkWeb_SchemeHandler object.
ArkWeb_SchemeHandler *schemeHandler;
OH_ArkWeb_CreateSchemeHandler(&schemeHandler);

// Set the ArkWeb_OnRequestStart and ArkWeb_OnRequestStop callbacks for the ArkWeb_SchemeHandler.
OH_ArkWebSchemeHandler_SetOnRequestStart(schemeHandler, OnURLRequestStart);
OH_ArkWebSchemeHandler_SetOnRequestStop(schemeHandler, OnURLRequestStop);

// Intercept requests with the "https" scheme from the Web component with webTag "scheme-handler".
OH_ArkWeb_SetSchemeHandler("https", "scheme-handler", schemeHandler);
OH_ArkWebServiceWorker_SetSchemeHandler("https", schemeHandler);
Enter fullscreen mode Exit fullscreen mode

Intercepting Non-Built-in Schemes

You can also intercept requests for non-built-in schemes.

// Create an ArkWeb_SchemeHandler object.
ArkWeb_SchemeHandler *schemeHandler;
OH_ArkWeb_CreateSchemeHandler(&schemeHandler);

// Set the ArkWeb_OnRequestStart and ArkWeb_OnRequestStop callbacks for the ArkWeb_SchemeHandler.
OH_ArkWebSchemeHandler_SetOnRequestStart(schemeHandler, OnURLRequestStart);
OH_ArkWebSchemeHandler_SetOnRequestStop(schemeHandler, OnURLRequestStop);

// Intercept requests with the "custom" scheme from the Web component with webTag "scheme-handler".
OH_ArkWeb_SetSchemeHandler("custom", "scheme-handler", schemeHandler);
OH_ArkWebServiceWorker_SetSchemeHandler("custom", schemeHandler);
Enter fullscreen mode Exit fullscreen mode

Registering Custom Schemes

To intercept requests for custom schemes, you must register the custom scheme with the Web kernel before initializing the Web component. Registration after initialization will fail.

// Register the "custom" scheme with the Web component, specifying that it follows standard scheme rules and allows cross-origin requests.
OH_ArkWeb_RegisterCustomSchemes("custom", ARKWEB_SCHEME_OPTION_STANDARD | ARKWEB_SCHEME_OPTION_CORS_ENABLED);

// Register the "custom-local" scheme with the Web component, specifying that it follows the same rules as the "file" scheme.
OH_ArkWeb_RegisterCustomSchemes("custom-local", ARKWEB_SCHEME_OPTION_LOCAL);

// Register the "custom-csp-bypassing" scheme with the Web component, specifying that it follows standard scheme rules and allows bypassing CSP checks.
OH_ArkWeb_RegisterCustomSchemes("custom-csp-bypassing", ARKWEB_SCHEME_OPTION_CSP_BYPASSING | ARKWEB_SCHEME_OPTION_STANDARD);

// Register the "custom-isolated" scheme with the Web component, specifying that requests for this scheme must be initiated from a webpage loaded with the same scheme.
OH_ArkWeb_RegisterCustomSchemes("custom-isolated", ARKWEB_SCHEME_OPTION_DISPLAY_ISOLATED);
Enter fullscreen mode Exit fullscreen mode

Since scheme registration must occur before Web component initialization, and network interceptors must be set up after initialization, it is recommended to call the C++ interface to register schemes in the onCreate method of EntryAbility.

Example: Initializing and Setting Up the Interceptor

export default class EntryAbility extends UIAbility {
    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
        // Register the custom schemes.
        testNapi.registerCustomSchemes();
        // Initialize the Web component engine, which initializes the Browser process and creates the BrowserContext.
        webview.WebviewController.initializeWebEngine();
        // Create and set up the ArkWeb_SchemeHandler.
        testNapi.setSchemeHandler();
    }
    ...
};
Enter fullscreen mode Exit fullscreen mode

Retrieving Intercepted Request Information

Use the OH_ArkWebResourceRequest_* interfaces to retrieve information about the intercepted request. You can obtain the URL, method, referrer, headers, and resource type.

char* url;
OH_ArkWebResourceRequest_GetUrl(resourceRequest_, &url);
OH_ArkWeb_ReleaseString(url);

char* method;
OH_ArkWebResourceRequest_GetMethod(resourceRequest_, &method);
OH_ArkWeb_ReleaseString(method);

int32_t resourceType = OH_ArkWebResourceRequest_GetResourceType(resourceRequest_);

char* frameUrl;
OH_ArkWebResourceRequest_GetFrameUrl(resourceRequest_, &frameUrl);
OH_ArkWeb_ReleaseString(frameUrl);
...
Enter fullscreen mode Exit fullscreen mode

Handling PUT/POST Request Upload Data

You can retrieve upload data for PUT/POST requests. The data types supported include BYTES, FILE, BLOB, and CHUNKED.

// Retrieve the upload data for the intercepted request.
OH_ArkWebResourceRequest_GetHttpBodyStream(resourceRequest(), &stream_);
// Set the read callback for uploading data.
OH_ArkWebHttpBodyStream_SetReadCallback(stream_, ReadCallback);
// Initialize the ArkWeb_HttpBodyStream; other OH_ArkWebHttpBodyStream* functions must be called after initialization.
OH_ArkWebHttpBodyStream_Init(stream_, InitCallback);
Enter fullscreen mode Exit fullscreen mode

Providing a Custom Response Body for Intercepted Requests

The network interceptor for Web components supports providing a custom response body for intercepted requests in a streaming manner on the worker thread. You can also end the intercepted request with a specific network error code (arkweb_net_error_list.h).

// Create a response for the intercepted request.
ArkWeb_Response *response;
OH_ArkWeb_CreateResponse(&response);

// Set the HTTP status code to 200.
OH_ArkWebResponse_SetStatus(response, 200);
// Set the charset of the response body.
OH_ArkWebResponse_SetCharset(response, "UTF-8");
// Set the size of the response body.
OH_ArkWebResponse_SetHeaderByName(response, "content-length", "1024", false);
// Pass the created response header to the Web component.
OH_ArkWebResourceHandler_DidReceiveResponse(resourceHandler, response);

// This function can be called multiple times to pass data to the Web component in chunks.
OH_ArkWebResourceHandler_DidReceiveData(resourceHandler, buffer, bufLen);

// Indicate the end of the response body. If you want the request to fail, you can call OH_ArkWebResourceHandler_DidFailWithError(resourceHandler_, errorCode);
// to pass an error code to the Web component and end the request.
OH_ArkWebResourceHandler_DidFinish(resourceHandler);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)