The web components provided by ArkWeb (ArkWeb) support the function of embedding web pages in applications. In practice, excessive static resources such as images and videos on web pages can cause quick traffic consumption. In addition, embedded malicious scripts slow down web page loading, affecting user experience. To address this, you can use the interception capability of the Web component to replace frequently accessed static resources with local resource copies and intercept malicious script loading based on the blocklist mechanism, thereby improving web page loading efficiency and optimizing user experience.
ArkWeb provides multiple interception capabilities that allow you to monitor, modify, and record network requests and responses, helping you customize service features and improving performance. These capabilities differ in interception timing, scope, and effect, and therefore apply to different development scenarios. This section outlines three interception solutions based on the Web component and provides typical application scenarios to help you select and use ArkWeb interception capabilities.
Applications can intercept page redirection of Web components through the onLoadIntercept() API, or intercept network requests initiated by Web components through the onInterceptRequest() API and WebSchemeHandler mechanism. The three interception solutions differ in principles and application scenarios. The following describes the details.
Table 1 Three web interception solutions
| Scenario | Page Redirection Control | Network Request Interception | Network Request Interception |
|---|---|---|---|
| Solution | onLoadIntercept | onInterceptRequest | WebSchemeHandler |
| Application Scenario | · Redirecting and Starting Between Web Pages and Applications | • Custom Resource Loading Strategy • Malicious request prompt | In addition to the application scenarios of onInterceptRequest, the following scenarios are supported: • Common Request Header Configuration • Cross-origin request • POST request interception |
| Interception timing | Before the Web component loads the URL | Before the request is initiated | Before the request is initiated |
| Interception scope | Requests for the main URL of the page (including the navigation behavior of iframe on the page, excluding requests for sub-resources) | Requests for the main URL of the page and sub-resources | Requests for the main URL of the page and sub-resources |
| Data access capability | You can obtain the URL of the request and whether the request is sent to the main frame. For details, see WebResourceRequest. | You can obtain the URL of the request and whether the request is sent to the main frame. For details, see WebResourceRequest. | In addition to the request URL and whether the request is sent to the main frame, the POST request body and buffer data can be obtained. For details, see WebSchemeHandlerRequest. |
| Interception effect | You can intercept or permit the current request initiated by the Web component. | You can intercept the current request and return a custom response, or permit the current request and return the original response. | You can intercept the current request and return a custom response, or permit the current request and return the original response. |
Different features of the three interception solutions correspond to different application scenarios. The following describes how to use the three solutions. You can select a proper interception solution as needed.
onLoadIntercept
Feature: It intercepts the URL loading behavior of Web components and controls page redirection.
Core usage:
Redirecting and Starting Between Web Pages and Applications: It intercepts requests from specific addresses, starts specified apps, or redirects to other pages. For example, it can intercept payment-related link redirection to payment apps, or intercept address link redirection to map apps.
Request redirection: It intercepts requests from specific addresses and redirects the access to a new target address. For example, it can redirect users to the correct page when the domain name is changed or during login.
Page trustlist configuration: Based on the preconfigured blocklist/trustlist, it blocks or allows specified URL requests, ensuring that requests from web components are within the trusted range. This function is used to prevent users from accessing dangerous web pages.
Usage policy: Compared with the other two interception solutions, onLoadIntercept is mainly used to intercept page redirection behavior instead of replacing request content. Therefore, this solution can be used when page redirection needs to be interrupted.
onInterceptRequest
Feature: It intercepts URL loading and network requests of Web components.
Core usage:
Local resource replacement: It caches frequently used static resources locally and return local responses when these resources are accessed, improving page loading speed and response performance.
Custom resource loading strategy: It intercepts specific resource requests (such as images and videos) and loads high-definition resources over Wi-Fi and compressed resources over mobile networks, balancing data usage and user experience.
Malicious request prompt: It intercepts known malicious requests and returns empty data or alert messages as request responses to prevent the loading of malicious scripts.
Usage policy: onInterceptRequest supports the replacement of request content through file handles, resources, ByteBuffer, or string. You need to provide complete request content at a time. This solution can be used in scenarios where network requests need to be intercepted and specific responses need to be returned to Web components. Compared with the WebSchemeHandler-based interception solution, this solution is more lightweight.
WebSchemeHandler
Feature: It intercepts URL loading and network requests of Web components.
Core usage:
In addition to supporting all core capabilities of onInterceptRequest, it also provides the following features:
Usage policy: Compared with the onInterceptRequest-based interception solution, WebSchemeHandler not only provides all its functions but also offers more flexible streaming processing capabilities. It allows you to gradually provide request content through ByteBuffer and obtain the uploaded content of the request, such as the data in a POST request. This solution is recommended in complex service scenarios where network requests need to be intercepted, more request content needs to be obtained, or streaming processing is required.
Before loading a URL, the Web component triggers the onLoadIntercept() callback to determine whether to intercept the request. Based on this callback, you can implement the request redirection or page trustlist configuration function.
Figure 1 Request interception using onLoadIntercept()

Request redirection is used to automatically redirect users to the correct page in scenarios such as website modification or login status management.
Effect
Figure 2 Request redirection

How to implement
Obtain the requested URL from the onLoadIntercept() callback of the Web component. If the URL meets the redirection conditions, load the redirection page through WebviewController.loadUrl().
How to develop
Obtains the URL of a request.
/**
* Processes the load intercept event
* Returns true if loading should be blocked (redirect performed), false to allow
*/
processLoadIntercept(event: OnLoadInterceptEvent): boolean {
const requestUrl = event.data.getRequestUrl();
// ...
} Check whether the URL meets redirection conditions.
/**
* Checks if the URL needs to be intercepted and redirected
*/
shouldInterceptUrl(requestUrl: string): boolean {
if (!this.redirectUrl) {
return false;
}
const normalizedRequest = this.normalizeUrl(requestUrl);
const normalizedRedirect = this.normalizeUrl(this.redirectUrl);
const isRedirectTarget = normalizedRequest === normalizedRedirect;
return !isRedirectTarget;
}
/**
* Normalizes the URL
*/
private normalizeUrl(url: string): string {
return url
.replace(/^(?:[a-zA-Z]+:)?\/\//, '')
.replace(/\/+$/, '')
.trim();
} If the redirection conditions are met, load the redirection page through WebviewController.loadUrl().
/**
* Processes the load intercept event
* Returns true if loading should be blocked (redirect performed), false to allow
*/
processLoadIntercept(event: OnLoadInterceptEvent): boolean {
// ...
if (this.shouldInterceptUrl(requestUrl)) {
// Perform redirect
const redirected = this.performRedirect();
return redirected; // Block original URL if redirect successful
}
return false; // Allow loading
}
/**
* Performs the redirect operation
*/
performRedirect(): boolean {
try {
this.controller.loadUrl(this.redirectUrl);
// ...
return true;
} catch (error) {
// ...
return false;
}
} The typical application of page trustlist configuration is to restrict access sources and allow only trusted sources to access the system, preventing unauthorized access and network attacks.
Effect
Page 3 Page trustlist configuration

How to implement
Obtain the requested URL from the onLoadIntercept() callback of the Web component. If the URL is not in the trustlist, the browser is opened to display the requested page.
How to develop
Configure the page trustlist link.
Web({ src: this.loadingUrl, controller: this.controller })
.onLoadIntercept((event) => {
// Update trustlist URLs before intercepting
this.viewModel?.setWhitelistUrls(this.whitelistUrlArr.map(url => url.toString()));
// ...
}) /**
* Updates the trustlist URLs
*/
setWhitelistUrls(urls: string[]): void {
this.whitelistDomains = urls
.map(url => this.extractDomain(url))
.filter(domain => domain.length > 0);
}
/**
* Extract the domain name from a URL
*/
private extractDomain(url: string): string {
let normalized = url.trim().toLowerCase();
// ...
normalized = normalized
.replace(/^(?:[a-z0-9+.-]+:)?\/\//, '') // strip protocol-like prefixes
.split(/[/?#]/)[0]; // drop everything after domain
return normalized.replace(/:+$/, '').replace(/\/+$/, '');
} Obtains the URL of a request.
/**
* Processes the load intercept event
* Returns true if loading should be blocked, false to allow
*/
processLoadIntercept(event: OnLoadInterceptEvent): boolean {
const requestUrl = event.data.getRequestUrl();
// ...
} Check whether the URL is in the trustlist.
/**
* Checks if a URL is in the trustlist
*/
isUrlInWhitelist(requestUrl: string): boolean {
const requestDomain = this.extractDomain(requestUrl);
if (!requestDomain) {
return false;
}
return this.whitelistDomains.includes(requestDomain);
} If the link is not in the trustlist, a dialog box is displayed, asking you whether to open the link in a browser.
/**
* Processes the load intercept event
* Returns true if loading should be blocked, false to allow
*/
processLoadIntercept(event: OnLoadInterceptEvent): boolean {
// ...
// Check if URL is in trustlist
if (this.isUrlInWhitelist(requestUrl)) {
this.allowAllForCurrentLoad = true;
return false; // Allow loading and subsequent requests
}
// URL not in trustlist, show dialog
this.showDialog(requestUrl);
return true; // Block loading
} Click to load the requested page in the browser.
/**
* Open URL in external browser
*/
private openInBrowser(url: string): void {
// ...
const want: Want = {
uri: url,
action: 'ohos.want.action.viewData',
entities: ['entity.system.browsable'],
parameters: {
'ohos.ability.params.showDefaultPicker': true
}
};
// ...
const context: common.UIAbilityContext = this.uiContext.getHostContext()! as common.UIAbilityContext;
context.startAbility(want)
.then(() => {
if (this.config?.onOk) {
this.config?.onOk(this.targetUrl)
}
// ...
})
.catch((err: BusinessError) => {
// ...
});
} Before loading a URL, the Web component triggers the onInterceptRequest() callback to determine whether to intercept the request and return the custom response data. Based on this callback, you can implement local resource replacement or custom resource loading strategy.
Figure 4 Request interception using onInterceptRequest()

Local resource replacement is used to cache some frequently used and slightly changed remote static resources locally to improve page loading speed and response performance.
Effect
Figure 5 Local resource replacement

How to implement
Obtain the network request information in the onInterceptRequest() callback of the Web component, obtain the corresponding local resource based on the mapping between the network request resource and the local resource, and set the local resource to WebResourceResponse as the request response.
How to develop
Configure the mapping between the network request resource and local resource, and the mapping between the local resource and MIME type.
// Map between domain names and local files
schemeMap = new Map([
['https://www.example.com/', 'index.html'],
['https://www.example.com/mountain.png', 'mountain.png']
]);
// Map between local files and format mimeType
mimeTypeMap = new Map([
['index.html', 'text/html'],
['mountain.png', 'image/png']
]);
Web({ src: this.requestUrl, controller: this.controller })
.onInterceptRequest((event) => {
// Update scheme map before intercepting
this.viewModel?.updateMappings(this.schemeMap, this.mimeTypeMap);
// ...
}) /**
* Updates the scheme and mime type mappings
*/
updateMappings(schemeMap: Map<string, string>, mimeTypeMap: Map<string, string>): void {
this.schemeMap = schemeMap;
this.mimeTypeMap = mimeTypeMap;
} Obtains the URL of a request.
/**
* Processes the intercepted request and returns local resource response if applicable
* Returns null if request should be allowed through
*/
processRequest(event: OnInterceptRequestEvent | null): WebResourceResponse | null {
// ...
const requestUrl = event.request.getRequestUrl();
// ...
} Obtain the local resource based on the mapping.
/**
* Processes the intercepted request and returns local resource response if applicable
* Returns null if request should be allowed through
*/
processRequest(event: OnInterceptRequestEvent | null): WebResourceResponse | null {
// ...
const key = this.getUrlSchemeFromMap(requestUrl);
if (key.length === 0) {
return null; // No match, allow original request
}
const rawfileName = this.schemeMap.get(key);
if (!rawfileName) {
return null; // Invalid mapping, allow original request
}
const mimeType = this.mimeTypeMap.get(rawfileName);
if (!mimeType) {
return null; // Invalid mapping, allow original request
}
// ...
}
/**
* Gets the matching URL scheme key from the map
*/
getUrlSchemeFromMap(prefix: string): string {
let matchedKey: string = '';
let maxLength: number = 0;
const urlOrigin = this.getUrlOrigin(prefix);
const urlFileName = this.getFileName(prefix);
// Find the longest matching key to prioritize specific paths over general ones
for (let key of this.schemeMap.keys()) {
// 1. Direct prefix match
if (prefix.startsWith(key) && key.length > maxLength) {
matchedKey = key;
maxLength = key.length;
continue;
}
// 2. Same-domain file name match
const keyFileName = this.getFileName(key);
if (keyFileName.length === 0) {
continue;
}
if (key.startsWith(urlOrigin) && keyFileName === urlFileName && key.length > maxLength) {
matchedKey = key;
maxLength = key.length;
}
}
return matchedKey;
} Constructs a WebResourceResponse, sets, and returns a local resource as the request response.
/**
* Processes the intercepted request and returns local resource response if applicable
* Returns null if request should be allowed through
*/
processRequest(event: OnInterceptRequestEvent | null): WebResourceResponse | null {
// ...
// Create response with local file
return this.createLocalResourceResponse(rawfileName, mimeType);
}
/**
* Creates a response with local file data
*/
createLocalResourceResponse(rawfileName: string, mimeType: string): WebResourceResponse {
const response = new WebResourceResponse();
response.setResponseHeader([{
headerKey: 'Connection',
headerValue: 'keep-alive'
}]);
response.setResponseData($rawfile(rawfileName));
response.setResponseEncoding('utf-8');
response.setResponseMimeType(mimeType);
response.setResponseCode(200);
response.setReasonMessage('OK');
response.setResponseIsReady(true);
return response;
} Custom resource loading strategy is used to load high-definition images over Wi-Fi networks and load compressed images or local placeholders over non-Wi-Fi networks, balancing data consumption and experience optimization.
Effect
Figure 6 Image loading over Wi-Fi networks

Figure 7 Local placeholder loading over non-Wi-Fi networks

How to implement
Obtain the network request information from the onInterceptRequest() callback of the Web component. For image resource requests, check whether the current network environment is a Wi-Fi network. If it is not Wi-Fi, set the local placeholder to WebResourceResponse as the request response.
How to develop
Check the current network environment. If the network is Wi-Fi, return the original request response.
/**
* Processes the intercepted request and returns appropriate response
* Returns null if request should be allowed through
*/
processRequest(event: OnInterceptRequestEvent | null): WebResourceResponse | null {
// ...
// If WiFi network, allow original network request
if (this.isWifiNetwork()) {
return null;
}
// ...
}
/**
* Checks if currently connected to a Wi-Fi network
*/
isWifiNetwork(): boolean {
try {
const netHandle = connection.getDefaultNetSync();
const netData = connection.getNetCapabilitiesSync(netHandle);
return netData.bearerTypes.includes(connection.NetBearType.BEARER_WIFI);
} catch (error) {
// ...
return false;
}
} Obtains the URL of a request.
/**
* Processes the intercepted request and returns appropriate response
* Returns null if request should be allowed through
*/
processRequest(event: OnInterceptRequestEvent | null): WebResourceResponse | null {
// ...
const requestUrl = event.request.getRequestUrl();
// ...
} Check the request type. If the request is not an image resource request, return the original request response.
/**
* Processes the intercepted request and returns appropriate response
* Returns null if request should be allowed through
*/
processRequest(event: OnInterceptRequestEvent | null): WebResourceResponse | null {
// ...
// Only intercept image requests
if (!this.isImageRequestUrl(requestUrl)) {
return null; // Not an image, allow original request
}
// ...
}
/**
* Checks if a URL request is for an image
*/
isImageRequestUrl(url: string): boolean {
for (let format of this.imageFormatList) {
if (url.endsWith(format)) {
return true;
}
}
return false;
} Constructs a WebResourceResponse, sets, and returns a local placeholder image as the request response for image resource requests on non-Wi-Fi networks.
/**
* Processes the intercepted request and returns appropriate response
* Returns null if request should be allowed through
*/
processRequest(event: OnInterceptRequestEvent | null): WebResourceResponse | null {
// ...
// Replace with placeholder image
return this.createPlaceholderResponse();
}
/**
* Creates a placeholder image response for non-WiFi networks
*/
createPlaceholderResponse(): WebResourceResponse {
const response = new WebResourceResponse();
response.setResponseHeader([{
headerKey: 'Connection',
headerValue: 'keep-alive'
}]);
response.setResponseData($rawfile(CommonConstants.IMAGE_NO_WLAN));
response.setResponseEncoding('utf-8');
response.setResponseMimeType('image/png');
response.setResponseCode(200);
response.setReasonMessage('OK');
response.setResponseIsReady(true);
return response;
} You can set a WebSchemeHandler for the current web component to intercept requests of a specified protocol, obtain request information, and return custom response data. Based on the WebSchemeHandler mechanism, scenarios such as common request header configuration can be implemented.
Figure 8 Request interception using WebSchemeHandler

Common request headers are used to carry authentication information during network access, so that the server can identify the user identity and verify the access permission.
Effect
Figure 9 Common request header configuration

How to implement
After setting WebSchemeHandler to the current Web component through WebviewController, intercept the network request in the WebSchemeHandler.onRequestStart() callback, add a common request header to the request, and then forward the request to the server through rcp.
How to develop
Use WebviewController to set WebSchemeHandler for the Web component.
// Bind interceptor to HTTP
controller.setWebSchemeHandler('http', this.schemeHandler); Intercept network requests in the WebSchemeHandler.onRequestStart() callback.
// Set up request interceptor
this.schemeHandler.onRequestStart((request: webview.WebSchemeHandlerRequest,
resourceHandler: webview.WebResourceHandler) => {
// Process request
const handled = this.model.processRequest(request, resourceHandler);
return handled;
}); Add custom common request headers to the network request and create an HTTP session through rcp.createSession().
/**
* Creates an RCP session for the next outbound request.
*/
private createSession(headers: Record<string, string>): void {
try {
// Create RCP session
const sessionConfig: rcp.SessionConfiguration = {
headers: headers
};
this.session = rcp.createSession(sessionConfig);
} catch (error) {
// ...
}
} Use rcp to forward the request to the server and obtain the response.
/**
* Sends GET or HEAD requests via the RCP session.
*/
private forwardGetRequest(
targetUrl: string,
headers: Record<string, string>,
resourceHandler: webview.WebResourceHandler,
): void {
try {
// ...
this.createSession(headers);
this.session?.get(targetUrl).then((response: rcp.Response) => {
// ...
this.handleResponse(response, resourceHandler);
this.session?.close();
}).catch((error: BusinessError) => {
// ...
});
} catch (error) {
// ...
}
} Call didReceiveResponse() and didReceiveResponseBody() to pass the constructed response header and body to the intercepted request.
/**
* Maps the RCP response to a WebSchemeHandlerResponse.
*/
private handleResponse(
response: rcp.Response,
resourceHandler: webview.WebResourceHandler,
): void {
try {
const webResponse = new webview.WebSchemeHandlerResponse();
webResponse.setStatus(response.statusCode || 200);
webResponse.setStatusText('OK');
// ...
webResponse.setMimeType(mimeType);
webResponse.setEncoding(encoding);
webResponse.setNetErrorCode(WebNetErrorList.NET_OK);
// Set CORS headers
webResponse.setHeaderByName('Access-Control-Allow-Origin', '*', true);
webResponse.setHeaderByName('Access-Control-Allow-Credentials', 'true', true);
webResponse.setHeaderByName('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS', true);
webResponse.setHeaderByName('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Custom-Header', true);
// ...
resourceHandler.didReceiveResponse(webResponse);
resourceHandler.didReceiveResponseBody(response.body);
// ...
} catch (error) {
// ...
}
} Call didFinish() to notify the Web component that the intercepted request has been completed.
/**
* Maps the RCP response to a WebSchemeHandlerResponse.
*/
private handleResponse(
response: rcp.Response,
resourceHandler: webview.WebResourceHandler,
): void {
try {
// ...
resourceHandler.didFinish();
} catch (error) {
// ...
}
} No. The Web component currently only provides interception methods for network requests, and the router.push() method of front-end pages does not trigger new network requests, so its requests cannot be intercepted.
No. The Web component cannot asynchronously determine whether to intercept network requests, but can asynchronously process response data after intercepting network requests. For details, see onInterceptRequest() Sample Code.
No. The Web component currently only provides interception methods for network requests and cannot intercept request responses. However, you can customize the response using the onInterceptRequest() callback or WebSchemeHandler mechanism.