DEV Community

HarmonyOS
HarmonyOS

Posted on

Web Resource Interception and Customizing Page Responses

Read the original article:Web Resource Interception and Customizing Page Responses

Context

Web resource interception and request management are crucial capabilities in modern webview development, particularly on platforms like HarmonyOS. By utilizing the framework's Web class from ArkWeb Kit, developers gain granular control over how web assets—such as images, scripts, stylesheets, and initial documents—are fetched and loaded within an H5 (HTML5) application running inside a native container. This capability allows for advanced features like offline support, local caching, content filtering, and injecting custom content.

Description

The primary mechanism for customizing page request responses is overriding the onInterceptRequest(callback: Callback<OnInterceptRequestEvent, WebResourceResponse>): WebAttribute; method, which is part of the Web. This callback is invoked every time the web component is about to load any resource (including the main page, embedded images, CSS, or scripts).

When onInterceptRequest is triggered, it provides the application with a OnInterceptRequestEvent object that details the specific resource being requested (URL, request method, headers, etc.). The application then has the option to return a custom WebResourceResponse object. By returning a valid WebResourceResponse, the developer effectively intercepts the network call and responds directly with local or modified data, preventing the request from ever reaching the remote server.

Solution

The solution involves three main steps: loading webpage using Web, overriding the onInterceptRequest method, and constructing a WebResourceResponse that substitutes the network resource with local content.

The following code demonstrates how to intercept a request for a specific resource URL and replace its response with data from a local asset file, thus customizing the page's output.

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

const URL = 'https://developer.huawei.com/consumer/en/doc/harmonyos-guides/web-resource-interception-request-mgmt';

@Entry
@Component
struct Index {
  @State controller: webview.WebviewController = new webview.WebviewController()
  responseResource: WebResourceResponse = new WebResourceResponse();
  @State webData: string = '<!DOCTYPE html>\n' +
    '<html>\n' +
    '<head>\n' +
    '<title>intercept test</title>\n' +
    '</head>\n' +
    '<body style="position: absolute;\n' +
    'top: 50%;\n' +
    'left: 50%;\n' +
    'transform: translateX(-50%) translateY(-50%);">\n' +
    '<h1>THIS WEBPAGE HAS BEEN CHANGED</h1>\n' +
    '</body>\n' +
    '</html>'


  build() {
    Column() {
      Web({ src: URL, controller: this.controller })
        .onInterceptRequest((event) => {
          if (event) {
            const requestUrl = event.request.getRequestUrl();
            // Intercept the web page request.
            if (requestUrl !== URL) {
              return null;
            }
          }
          // Construct a custom response.
          this.responseResource.setResponseData(this.webData);
          this.responseResource.setResponseEncoding('utf-8');
          this.responseResource.setResponseMimeType('text/html');
          this.responseResource.setResponseCode(200);
          this.responseResource.setReasonMessage('OK');
          return this.responseResource;
        })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
    .alignItems(HorizontalAlign.Center)
  }
}
Enter fullscreen mode Exit fullscreen mode

Result:

forum.png

Key Takeaways

  • Granular Control: The onInterceptRequest method gives developers fine-grained control over all resource requests, not just the primary HTML page.
  • Customization Object: The core of the solution is the WebResourceResponse object, which requires essential fields like mimeType, encoding, and the actual resource data (represented as a stream).
  • Network Bypass: Returning a non-null WebResourceResponse intercepts the network request entirely, allowing the application to serve content from local assets, databases, or dynamically generated data.
  • Default Behavior: If onInterceptRequest returns null or is not overridden, the web component proceeds with the default behavior, which is typically fetching the resource from the network.
  • Use Case: This technique is essential for implementing features like offline access, injecting custom client-side analytics scripts, or overriding slow-loading external resources with efficient local placeholders.

Written by Taskhyn Maksim

Top comments (0)