The Web component provided by ArkWeb supports web page access 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.
An application can use onLoadIntercept() to intercept web page redirection, or use onInterceptRequest() and WebSchemeHandler to intercept network requests initiated by the Web component. The three interception solutions differ in principles and application scenarios. The following describes the details.
Scenario | Page Redirection Control | Network Request Interception | |
|---|---|---|---|
Solution | onLoadIntercept | onInterceptRequest | WebSchemeHandler |
Typical application scenario |
| In addition to the application scenarios of onInterceptRequest, the following scenarios are supported:
| |
Interception timing | Before the Web component loads the URL | 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 | |
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. | 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. | |
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:
Usage policy: Compared with the other two interception solutions, onLoadIntercept primarily intercepts page redirection rather than replacing request content.
onInterceptRequest
Feature: It intercepts URL loading and network requests of Web components.
Core usage:
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. Compared with WebSchemeHandler, onInterceptRequest offers a more lightweight solution and is therefore suitable for scenarios where network requests need to be intercepted and specific responses need to be returned to Web components.
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: In addition to all capabilities of onInterceptRequest, WebSchemeHandler offers more flexible streaming processing capabilities. You can use ByteBuffer to provide request content step by step and obtain the uploaded request content, such as data from POST requests. Therefore, WebSchemeHandler is more suitable for complex service scenarios where network requests need to be intercepted, additional request content needs to be retrieved, or stream processing is required.
Before loading a URL, the Web component triggers the onLoadIntercept() callback to determine whether to intercept the request. This callback can be used to implement request redirection or page whitelist configuration.

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

How to Implement
Obtain the request URL in the onLoadIntercept() callback of the Web component. If the URL meets redirection conditions, call WebviewController.loadUrl() to load the redirection page.
How to Develop
/**
* 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();
// ...
} /**
* 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();
} /**
* 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;
}
} Page whitelist configuration is used to restrict access sources so that only trusted sources can access the system, preventing unauthorized access and network attacks.
Running Effect

How to Implement
Obtain the request URL in the onLoadIntercept() callback of the Web component. If the URL is not in the whitelist, the browser is redirected to the requested page.
How to Develop
Web({ src: this.loadingUrl, controller: this.controller })
.onLoadIntercept((event) => {
// Update whitelist URLs before intercepting
this.viewModel?.setWhitelistUrls(this.whitelistUrlArr.map(url => url.toString()));
// ...
}) /**
* Updates the whitelist 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(/\/+$/, '');
} /**
* Processes the load intercept event
* Returns true if loading should be blocked, false to allow
*/
processLoadIntercept(event: OnLoadInterceptEvent): boolean {
const requestUrl = event.data.getRequestUrl();
// ...
} /**
* Checks if a URL is in the whitelist
*/
isUrlInWhitelist(requestUrl: string): boolean {
const requestDomain = this.extractDomain(requestUrl);
if (!requestDomain) {
return false;
}
return this.whitelistDomains.includes(requestDomain);
} /**
* Processes the load intercept event
* Returns true if loading should be blocked, false to allow
*/
processLoadIntercept(event: OnLoadInterceptEvent): boolean {
// ...
// Check if URL is in whitelist
if (this.isUrlInWhitelist(requestUrl)) {
this.allowAllForCurrentLoad = true;
return false; // Allow loading and subsequent requests
}
// URL not in whitelist, show dialog
this.showDialog(requestUrl);
return true; // Block loading
} /**
* 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 custom response data. This callback can be used to implement local resource replacement or custom resource loading strategy.

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.
Running Effect

How to Implement
Obtain 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
// 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;
} /**
* 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();
// ...
} /**
* 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;
} /**
* 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.
Running Effect


How to Implement
Obtain network image request information in the onInterceptRequest() callback of the Web component to check whether the current network is Wi-Fi. If it is not Wi-Fi, set the local placeholder to WebResourceResponse as the request response.
How to Develop
/**
* 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;
}
} /**
* 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();
// ...
} /**
* 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;
} /**
* 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;
} Set 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, you can configure common request headers.

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.
Running Effect

How to Implement
Configure a WebSchemeHandler for the current Web component through WebviewController. In the WebSchemeHandler.onRequestStart() callback, intercept network requests, add common request headers to the requests, and forward the requests to the server via RCP.
How to Develop
// Bind interceptor to HTTP
controller.setWebSchemeHandler('http', this.schemeHandler); // Set up request interceptor
this.schemeHandler.onRequestStart((request: webview.WebSchemeHandlerRequest,
resourceHandler: webview.WebResourceHandler) => {
// Process request
const handled = this.model.processRequest(request, resourceHandler);
return handled;
}); /**
* 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) {
// ...
}
} /**
* 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) {
// ...
}
} /**
* 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) {
// ...
}
} /**
* 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 the response data after intercepting network requests. For details, see the onInterceptRequest() sample code.
No. The Web component currently only provides interception methods for network requests and cannot intercept request responses. However, you can customize responses via the onInterceptRequest() callback or WebSchemeHandler.