Intelligent Assistant
Chat with our virtual assistant to get answers promptly.
The supported universal attributes include aspectRatio, backdropBlur, backgroundColor, bindContentCover, bindContextMenu, bindMenu, bindSheet, borderColor, borderRadius, borderStyle, borderWidth, clip, constraintSize, defaultFocus, focusable, tabIndex, groupDefaultFocus, displayPriority, enabled, flexBasis, flexShrink, layoutWeight, id, gridOffset, gridSpan, useSizeType, height, touchable, margin, markAnchor, offset, width, zIndex, visibility, scale, translate, responseRegion, size, opacity, shadow, sharedTransition, transition, position, and direction.
This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The sample effect is subject to the actual device.
Web component attributes are used to configure the web page loading behavior, security policies, runtime environment, and interaction capabilities of the Web component through chain calls in the ArkUI declarative syntax. They serve as the primary entry point for customizing Web component behavior. For general style and layout attributes (such as size, margin, background, and visibility), see Size Settings. This chapter describes only attributes specific to the Web component. For runtime dynamic control capabilities (such as loading URLs, navigating forward/backward, registering/unregistering JS objects, running JavaScript, and injecting CSS), use them together with WebviewController.
domStorageAccess(domStorageAccess: boolean)
Sets whether to enable the DOM Storage API permission. If this attribute is not explicitly called, the DOM Storage API permission is disabled by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| domStorageAccess | boolean | Yes | Set whether to enable the document object model storage interface (DOM Storage API) permission. true indicates enabling, and false indicates disabling. When undefined or null is passed in, the value is false. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .domStorageAccess(true)
- }
- }
- }
fileAccess(fileAccess: boolean)
Sets whether to enable access to the file system in the application. This setting does not affect the access to the files specified through $rawfile(filepath/filename). For API version 11 and earlier versions, access to the file system in the application is enabled by default if this attribute is not explicitly called. Since API version 12, access to the file system in the application is disabled by default if this attribute is not explicitly called.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| fileAccess | boolean | Yes | Whether to enable access to the file system in the app. The value true means to enable, and false means to disable. In addition, when fileAccess is false, resources in the read-only resource directory /data/storage/el1/bundle/entry/resources/resfile can still be accessed through the file protocol, which is not controlled by fileAccess. In API version 11 and earlier, the value is true when undefined or null is passed. In API version 12 and later, the value is false when undefined or null is passed. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .fileAccess(true)
- }
- }
- }
imageAccess(imageAccess: boolean)
Sets whether to allow automatic loading of image resources. If this attribute is not explicitly called, automatic loading is allowed by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| imageAccess | boolean | Yes | Set whether to allow automatic loading of image resources. true indicates allowing, and false indicates disallowing. The value is false when undefined or null is passed in. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .imageAccess(true)
- }
- }
- }
javaScriptProxy(javaScriptProxy: JavaScriptProxy)
Registers the ArkTS object in javaScriptProxy with the Web component. The object will be registered in all frames of the web page, including all iframes, using the name specified in JavaScriptProxy. This enables JavaScript to call methods of the ArkTS object in javaScriptProxy.
The javaScriptProxy API must be used together with deleteJavaScriptRegister9+ to prevent memory leaks.
All parameters of the javaScriptProxy object cannot be updated.
When registering a javaScriptProxy object, at least one of the synchronous or asynchronous method lists must be non-empty. Both types of methods can be registered simultaneously.
This API supports registering only one object. To register multiple objects, use registerJavaScriptProxy9+.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| javaScriptProxy | JavaScriptProxy | Yes | Object to be registered. Methods can be declared, but attributes cannot. When undefined or null is passed in, the ArkTS object in javaScriptProxy is not registered with the Web component. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
- import { BusinessError } from '@kit.BasicServicesKit';
-
- class TestObj {
- constructor() {
- }
-
- test(data1: string, data2: string, data3: string): string {
- console.info("data1:" + data1);
- console.info("data2:" + data2);
- console.info("data3:" + data3);
- return "AceString";
- }
-
- asyncTest(data: string): void {
- console.info("async data:" + data);
- }
-
- toString(): void {
- console.info('toString' + "interface instead.");
- }
- }
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- testObj = new TestObj();
- build() {
- Column() {
- Button('deleteJavaScriptRegister')
- .onClick(() => {
- try {
- this.controller.deleteJavaScriptRegister("objName");
- } catch (error) {
- console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
- }
- })
- Web({ src: 'www.example.com', controller: this.controller })
- .javaScriptAccess(true)
- .javaScriptProxy({
- object: this.testObj,
- name: "objName",
- methodList: ["test", "toString"],
- asyncMethodList: ["asyncTest"],
- controller: this.controller,
- })
- }
- }
- }
javaScriptAccess(javaScriptAccess: boolean)
Sets whether to allow execution of JavaScript scripts. If this attribute is not explicitly called, execution is allowed by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| javaScriptAccess | boolean | Yes | Whether to allow JavaScript scripts to be executed. true indicates allowing, and false indicates disallowing. The value is false when undefined or null is passed in. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .javaScriptAccess(true)
- }
- }
- }
overScrollMode(mode: OverScrollMode)
Sets the over-scroll mode of the Web component. When enabled, if the user scrolls to the edge of the root web page, the Web component bounces back with an elastic animation, and inner pages on the root page do not trigger the bounce effect. If this attribute is not explicitly called, the over-scroll mode is disabled by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| mode | OverScrollMode | Yes | Whether to enable the overscroll mode. When undefined or null is passed in, the value is OverScrollMode.NEVER. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State mode: OverScrollMode = OverScrollMode.ALWAYS;
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .overScrollMode(this.mode)
- }
- }
- }
mixedMode(mixedMode: MixedMode)
Sets the behavior when a secure source attempts to load resources from an insecure source. When this attribute is not explicitly called, the default value is MixedMode.None, which means that secure sources are not allowed to load content from insecure sources.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| mixedMode | MixedMode | Yes | Mixed content mode to be set. If undefined or null is passed in, the value MixedMode.All is used. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State mode: MixedMode = MixedMode.All;
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .mixedMode(this.mode)
- }
- }
- }
onlineImageAccess(onlineImageAccess: boolean)
Sets whether to allow loading of image resources from the network (resources accessed via HTTP and HTTPS). If this attribute is not explicitly called, loading is allowed by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| onlineImageAccess | boolean | Yes | Set whether to allow loading image resources from the network. true indicates allowing, and false indicates disallowing. The value is false when undefined or null is passed in. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .onlineImageAccess(true)
- }
- }
- }
zoomAccess(zoomAccess: boolean)
Sets whether to support zoom gestures. If this attribute is not explicitly called, zoom gestures are supported by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| zoomAccess | boolean | Yes | Set whether to support gesture-based scaling. true indicates support, and false indicates no support. The value is false when undefined or null is passed in. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .zoomAccess(true)
- }
- }
- }
overviewModeAccess(overviewModeAccess: boolean)
Sets whether to load web pages by using the overview mode. That is, zoom out the content to fit the screen width. When this attribute is not explicitly called, web pages can be loaded in overview mode by default.
System capability: SystemCapability.Web.Webview.Core
Device behavior: This API has no effect on the PCs/2-in-1 devices and works on other devices.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| overviewModeAccess | boolean | Yes | Set whether to use the overview mode to load the web page. true indicates using it, and false indicates not using it. The value is false when undefined or null is passed in. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .overviewModeAccess(true)
- }
- }
- }
databaseAccess(databaseAccess: boolean)
Sets whether to enable the Web SQL Database storage API permission. If this permission is not explicitly called, it is disabled by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| databaseAccess | boolean | Yes | Whether to enable Web SQL Database storage API permission. true means enabling the detection, and false means disabling it. If undefined or null is passed in, the value is false. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .databaseAccess(true)
- }
- }
- }
geolocationAccess(geolocationAccess: boolean)
Sets whether to enable the geolocation permission. If this attribute is not explicitly called, the permission is enabled by default. For details about how to use this feature, see Managing Location Permissions.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| geolocationAccess | boolean | Yes | Set whether to enable the geolocation permission. true indicates enabling, and false indicates disabling. The value is false when undefined or null is passed in. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .geolocationAccess(true)
- }
- }
- }
mediaPlayGestureAccess(access: boolean)
Sets whether autoplay of audible videos requires a user tap. Muted video playback is not affected by this API. If this attribute is not explicitly set, a user tap is required by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| access | boolean | Yes | Sets whether autoplay of audio/video requires a manual click by the user. true indicates that a manual click by the user is required, and false indicates that it is not required and autoplay is allowed. When undefined or null is passed in, the value is false. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State access: boolean = true;
-
- build() {
- Column() {
- Web({ src: $rawfile('index.html'), controller: this.controller })
- .mediaPlayGestureAccess(this.access)
- }
- }
- }
HTML file to be loaded:
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <title>Video Playback Page</title>
- </head>
- <body>
- <h1>Video Playback</h1>
- <video id="testVideo" controls autoplay>
- // Configure the autoplay attribute in the video tag to allow automatic video playback.
- // Save an MP4 media file in the rawfile directory of resources and name it example.mp4.
- <source src="example.mp4" type="video/mp4">
- </video>
- </body>
- </html>
multiWindowAccess(multiWindow: boolean)
Sets whether to enable the multi-window permission. If this attribute is not explicitly called, the permission is disabled by default.
Enabling the multi-window permission requires implementation of the onWindowNew event. For the sample code, see onWindowNew.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| multiWindow | boolean | Yes | Set whether to enable the multi-window permission. true indicates enabling, and false indicates disabling. |
horizontalScrollBarAccess(horizontalScrollBar: boolean)
Sets whether to display the horizontal scrollbar, including the system default scrollbar and user-defined scrollbars. If this attribute is not explicitly called, the scrollbar is displayed by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| horizontalScrollBar | boolean | Yes | Set whether to display the horizontal scroll bar. true indicates displaying, and false indicates not displaying. When undefined or null is passed in, the value is false. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
- import { BusinessError } from '@kit.BasicServicesKit';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State isShow: boolean = true;
- @State btnMsg: string = 'Hide scrollbar';
-
- build() {
- Column() {
- // If an @State decorated variable is used to control the horizontal scrollbar visibility, controller.refresh() must be called for the settings to take effect.
- Button('refresh')
- .onClick(() => {
- if (this.isShow) {
- this.isShow = false;
- this.btnMsg = 'Show scrollbar';
- } else {
- this.isShow = true;
- this.btnMsg = 'Hide scrollbar';
- }
- try {
- this.controller.refresh();
- } catch (error) {
- console.error(`Failed to refresh Web. Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}`);
- }
- }).height('10%').width('40%')
- Web({ src: $rawfile('index.html'), controller: this.controller }).height('90%')
- .horizontalScrollBarAccess(this.isShow)
- }
- }
- }
HTML file to be loaded:
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" id="viewport" content="width=device-width,initial-scale=1.0">
- <title>Demo</title>
- <style>
- body {
- width:3000px;
- height:6000px;
- padding-right:170px;
- padding-left:170px;
- border:5px solid blueviolet;
- }
- </style>
- </head>
- <body>
- Scroll Test
- </body>
- </html>
verticalScrollBarAccess(verticalScrollBar: boolean)
Sets whether to display the vertical scrollbar, including the system default scrollbar and user-defined scrollbars. If this attribute is not explicitly called, the scrollbar is displayed by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| verticalScrollBar | boolean | Yes | Set whether to display the vertical scroll bar. true indicates displaying, and false indicates not displaying. The value is false when undefined or null is passed in. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
- import { BusinessError } from '@kit.BasicServicesKit';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State isShow: boolean = true;
- @State btnMsg: string = 'Hide scrollbar';
-
- build() {
- Column() {
- // If an @State decorated variable is used to control the vertical scrollbar visibility, controller.refresh() must be called for the settings to take effect.
- Button(this.btnMsg)
- .onClick(() => {
- if (this.isShow) {
- this.isShow = false;
- this.btnMsg = 'Show scrollbar';
- } else {
- this.isShow = true;
- this.btnMsg = 'Hide scrollbar';
- }
- try {
- this.controller.refresh();
- } catch (error) {
- console.error(`Failed to refresh Web. Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}`);
- }
- }).height('10%').width('40%')
- Web({ src: $rawfile('index.html'), controller: this.controller }).height('90%')
- .verticalScrollBarAccess(this.isShow)
- }
- }
- }
HTML file to be loaded:
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" id="viewport" content="width=device-width,initial-scale=1.0">
- <title>Demo</title>
- <style>
- body {
- width:3000px;
- height:6000px;
- padding-right:170px;
- padding-left:170px;
- border:5px solid blueviolet;
- }
- </style>
- </head>
- <body>
- Scroll Test
- </body>
- </html>
cacheMode(cacheMode: CacheMode)
Sets the cache mode. When this attribute is not explicitly called, the default value CacheMode.Default is used.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| cacheMode | CacheMode | Yes | Cache mode to set. When undefined or null is passed in, the value is CacheMode.Default. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State mode: CacheMode = CacheMode.None;
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .cacheMode(this.mode)
- }
- }
- }
copyOptions(value: CopyOptions)
Sets the clipboard copy scope option. If this attribute is not explicitly called, pasting across all apps on the current device is supported by default after copying.
When this attribute is set to CopyOptions.None, the enablePreviewMenu configuration item in dataDetectorConfig does not take effect. When enableDataDetector is set to true and this attribute is set to CopyOptions.LocalDevice, the AI menu feature is activated.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | CopyOptions | Yes | Pasteboard copy options. When undefined or null is passed in, the value is CopyOptions.None. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .copyOptions(CopyOptions.None)
- }
- }
- }
textZoomRatio(textZoomRatio: number)
Sets the text zoom ratio of the page. When this attribute is not explicitly called, the default zoom ratio is 100%.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| textZoomRatio | number | Yes | Text zoom percentage of the page to be set. 100 indicates the original size, a value greater than 100 indicates zooming in, and a value less than 100 indicates zooming out. The value is an integer in the range (0, 2147483647]. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State ratio: number = 150;
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .textZoomRatio(this.ratio)
- }
- }
- }
initialScale(percent: number)
Sets the zoom percentage of the entire page. If this attribute is not explicitly called, the default value is 100.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| percent | number | Yes | Scale factor of the entire page. Value range: (0, 1000] When undefined or null is passed in, the attribute setting does not take effect. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State percent: number = 100;
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .initialScale(this.percent)
- }
- }
- }
blockNetwork(block: boolean)
Sets whether to block online downloads. When this attribute is not explicitly called, online resources can be loaded by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| block | boolean | Yes | Whether to allow online downloads. The value true means to block online downloads, and false means the opposite. If undefined or null is passed in, the value is false. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State block: boolean = true;
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .blockNetwork(this.block)
- }
- }
- }
defaultFixedFontSize(size: number)
Sets the default fixed font size for the web page. For HTML elements that use the monospace font and do not specify font-size, the font size is rendered based on this value.
When this attribute is not explicitly called, the default fixed font size is 13.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| size | number | Yes | Default fixed font size to set, in px. Value range: [-2^31, 2^31-1]. In actual rendering, values greater than 72 px are handled as 72 px, and values less than 1 px are handled as 1 px. When null or undefined is passed in, the value is 13. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State fontSize: number = 16;
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .defaultFixedFontSize(this.fontSize)
- }
- }
- }
defaultFontSize(size: number)
Sets the default font size for the web page. For HTML elements that use non-monospace fonts and do not specify font-size, the font size is rendered based on this value.
When this attribute is not explicitly called, the default font size of the web page is 16.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| size | number | Yes | Default font size to set, in px. Value range: [-2^31, 2^31-1]. In actual rendering, values greater than 72 px are handled as 72 px, and values less than 1 px are handled as 1 px. When null or undefined is passed in, the value is 16. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State fontSize: number = 13;
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .defaultFontSize(this.fontSize)
- }
- }
- }
minFontSize(size: number)
Sets the minimum font size for the web page. If the font size of HTML elements is smaller than the value set by this API, the font size is rendered based on the value set by this API.
When no attribute is explicitly called, the default minimum font size of the web page is 8.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| size | number | Yes | Minimum font size to set, in px. Value range: [-2^31, 2^31-1]. In actual rendering, values greater than 72 px are handled as 72 px, and values less than 1 px are handled as 1 px. When null or undefined is passed in, the value is 8. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State fontSize: number = 13;
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .minFontSize(this.fontSize)
- }
- }
- }
minLogicalFontSize(size: number)
Sets the minimum logical font size for the web page.
For HTML elements whose font size is not specified:
When this attribute is not explicitly called, the default minimum logical font size of the web page is 8.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| size | number | Yes | Sets the minimum logical font size for web pages, in px. The value ranges from [-2^31, 2^31-1]. During actual rendering, values greater than 72 px are rendered as 72 px, and values less than 1 px are rendered as 1 px. Defaults to 8 when null or undefined is passed in. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State fontSize: number = 13;
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .minLogicalFontSize(this.fontSize)
- }
- }
- }
webFixedFont(family: string)
Sets the fixed font family of the web page to render HTML elements that use the monospace font.
When this attribute is not explicitly called, the default fixed font family of the web page is monospace.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| family | string | Yes | Fixed font family for web pages. The value is a font name string, for example, "monospace" or "Arial". The value monospace is used when null or undefined is passed. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State family: string = "monospace";
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .webFixedFont(this.family)
- }
- }
- }
webSansSerifFont(family: string)
Sets the sans-serif font family of the web page to render HTML elements that use the sans-serif font.
When this attribute is not explicitly called, the sans-serif font family of the web page is sans-serif by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| family | string | Yes | Sans-serif font family to set. When null or undefined is passed in, the sans-serif font family is sans-serif. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State family: string = "sans-serif";
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .webSansSerifFont(this.family)
- }
- }
- }
webSerifFont(family: string)
Sets the serif font family of the web page to render HTML elements that use the serif font.
When this attribute is not explicitly called, the default serif font family of the web page is serif.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| family | string | Yes | Serif font family to set. When null or undefined is passed in, the sans-serif font family is serif. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State family: string = "serif";
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .webSerifFont(this.family)
- }
- }
- }
webStandardFont(family: string)
Sets the standard font family of the web page to render HTML elements whose font style is not specified.
When this attribute is not explicitly called, the default standard font family of the web page is sans-serif.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| family | string | Yes | Standard font family to set. When null or undefined is passed in, the sans-serif font family is sans-serif. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State family: string = "sans-serif";
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .webStandardFont(this.family)
- }
- }
- }
webFantasyFont(family: string)
Sets the fantasy font family of the web page to render HTML elements that use the fantasy font.
When this attribute is not explicitly called, the default fantasy font family of the web page is fantasy.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| family | string | Yes | Fantasy font family to set. When null or undefined is passed in, the value is fantasy. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State family: string = "fantasy";
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .webFantasyFont(this.family)
- }
- }
- }
webCursiveFont(family: string)
Sets the cursive font family of the web page to render HTML elements that use the cursive font.
When this attribute is not explicitly called, the default cursive font family of the web page is cursive.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| family | string | Yes | Cursive font family to set. When null or undefined is passed in, the value is cursive. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State family: string = "cursive";
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .webCursiveFont(this.family)
- }
- }
- }
darkMode(mode: WebDarkMode)
Sets the dark mode of the Web component. If this attribute is not explicitly called, dark mode is disabled by default.
When dark mode is enabled, the Web component enables the dark style defined in the media query prefers-color-scheme of the web page. If it is not defined, the web page remains unchanged. To enable forcible dark mode, use this API with forceDarkAccess. For details about how to use dark mode, see Setting Dark Mode.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| mode | WebDarkMode | Yes | Dark mode for the web page, which can be set to Off, On, or Auto. When null or undefined is passed, the value is WebDarkMode.Off. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State mode: WebDarkMode = WebDarkMode.On;
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .darkMode(this.mode)
- }
- }
- }
forceDarkAccess(access: boolean)
Sets whether to enable forcible dark mode for the web page. This API is applicable only when darkMode is enabled. When this attribute is not explicitly called, forcible dark mode is disabled for the web page by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| access | boolean | Yes | Whether to enable forced dark mode for web pages. The value true means to enable it, and false means not to enable it. If null or undefined is passed, the default value false is used. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State mode: WebDarkMode = WebDarkMode.On;
- @State access: boolean = true;
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .darkMode(this.mode)
- .forceDarkAccess(this.access)
- }
- }
- }
pinchSmooth(isEnabled: boolean)
Sets whether to enable pinch smooth mode for the web page. When this attribute is not explicitly called, pinch smooth mode is disabled by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| isEnabled | boolean | Yes | Whether to enable pinch smooth mode for the web page. The value true means to enable pinch smooth mode, and false means the opposite. If undefined or null is passed in, the value is false. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .pinchSmooth(true)
- }
- }
- }
allowWindowOpenMethod(flag: boolean)
Sets whether to allow a new window to automatically open through JavaScript.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| flag | boolean | Yes | Whether to allow a new window to automatically open through JavaScript. The value true means to allow a new window to automatically open through JavaScript, and false means only to allow a new window to automatically open through JavaScript using user behaviors. The user behavior here refers to a user requests to open a new window (window.open) within 5 seconds after operating the Web component. The default value of flag is subject to the settings of the persist.web.allowWindowOpenMethod.enabled system attribute. If this attribute is set to true, the default value of flag is true. If this attribute is not set, the default value of flag is false. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- // There are two Web components on the same page. When the WebComponent object opens a new window, the NewWebViewComp object is displayed.
- @CustomDialog
- struct NewWebViewComp {
- controller?: CustomDialogController;
- webviewController1: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: "", controller: this.webviewController1 })
- .javaScriptAccess(true)
- .multiWindowAccess(false)
- .onWindowExit(() => {
- console.info("NewWebViewComp onWindowExit");
- if (this.controller) {
- this.controller.close();
- }
- })
- .onActivateContent(() => {
- // This Web needs to be displayed in the foreground. It is recommended that the application perform tab or window switching here.
- console.info("NewWebViewComp onActivateContent")
- })
- }
- }
- }
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- dialogController: CustomDialogController | null = null;
-
- build() {
- Column() {
- Web({ src: $rawfile("index.html"), controller: this.controller })
- .javaScriptAccess(true)
- // MultiWindowAccess needs to be enabled.
- .multiWindowAccess(true)
- .allowWindowOpenMethod(true)
- .onWindowNew((event) => {
- if (this.dialogController) {
- this.dialogController.close()
- }
- let popController: webview.WebviewController = new webview.WebviewController();
- // Return the WebviewController corresponding to the new window to the Web kernel.
- // If the event.handler.setWebController interface is not called, the rendering process will be blocked.
- // If no new window is created, set it to null when calling the event.handler.setWebController interface to notify the Web that no new window has been created.
- event.handler.setWebController(popController);
- this.dialogController = new CustomDialogController({
- builder: NewWebViewComp({ webviewController1: popController }),
- // Set isModal to false to prevent the new window from being destroyed, so that the onActivateContent callback can be triggered.
- isModal: false
- })
- this.dialogController.open();
- })
- }
- }
- }
Example of the HTML file
- <!-- index.html -->
- <!DOCTYPE html>
- <html>
- <body>
- <div>
- <button type="button" onclick="delayOpenwindow(5000)">delayOpenwindow_5s</button>
- </div>
-
- <script>
- function openwindowAll(){
- open("https://www.example.com","_blank","height=400,width=600,top=100,left=100,scrollbars=no")
- }
- function delayOpenwindow(t){
- setTimeout(openwindowAll, t);
- }
- </script>
- </body>
- </html>
mediaOptions(options: WebMediaOptions)
Sets the web-based media playback policy, including the validity period for automatically resuming a paused web audio, and whether the audio of multiple Web instances in an application is exclusive. When this attribute is not explicitly set, the web audio cannot be automatically resumed after regaining the focus by default, and the audio of multiple Web instances in an application is exclusive.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| options | WebMediaOptions | Yes | Web-based media playback policy. After the parameter settings are updated, the playback must be started again for the settings to take effect. When undefined or null is passed in, {resumeInterval: 0, audioExclusive: true} is used. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State options: WebMediaOptions = {resumeInterval: 10, audioExclusive: true};
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .mediaOptions(this.options)
- }
- }
- }
javaScriptOnDocumentStart(scripts: Array<ScriptItem>)
Injects a JavaScript script into the Web component. When the specified page or document starts to be loaded, the script is executed on any page whose source matches scriptRules. When this attribute is not explicitly called, JavaScript scripts are not injected into the Web component by default.
The script is injected after the root element (HTML Element) of the web document is created but before any other content is loaded.
The scripts are executed in lexicographic order, not in the order of the array. If the original array order is required, use the runJavaScriptOnDocumentStart API instead.
When scripts with identical content are injected multiple times, they are silently deduplicated without display or notification, and the scriptRules from the first injection are used.
This API does not support UrlRegexRule.
You are advised to use runJavaScriptOnDocumentStart instead.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| scripts | Array<ScriptItem> | Yes | Script item array to be injected. When undefined or null is passed in, JavaScript scripts are not injected into Web components. |
Example of the .ets file
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct Index {
- controller: webview.WebviewController = new webview.WebviewController();
- private localStorage: string =
- "if (typeof(Storage) !== 'undefined') {" +
- " localStorage.setItem('color', 'Red');" +
- "}";
- @State scripts: Array<ScriptItem> = [
- { script: this.localStorage, scriptRules: ["*"] }
- ];
-
- build() {
- Column({ space: 20 }) {
- Web({ src: $rawfile('index.html'), controller: this.controller })
- .javaScriptAccess(true)
- .domStorageAccess(true)
- .backgroundColor(Color.Grey)
- .javaScriptOnDocumentStart(this.scripts)
- .width('100%')
- .height('100%')
- }
- }
- }
Example of the HTML file
- <!-- index.html -->
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- </head>
- <body style="font-size: 30px;" onload='bodyOnLoadLocalStorage()'>
- Hello world!
- <div id="result"></div>
- </body>
- <script type="text/javascript">
- function bodyOnLoadLocalStorage() {
- if (typeof(Storage) !== 'undefined') {
- document.getElementById('result').innerHTML = localStorage.getItem('color');
- } else {
- document.getElementById('result').innerHTML = 'Your browser does not support localStorage.';
- }
- }
- </script>
- </html>
javaScriptOnDocumentEnd(scripts: Array<ScriptItem>)
Injects a JavaScript script into the Web component. When the specified page or document has been loaded, the script is executed on any page whose source matches scriptRules. When this attribute is not explicitly called, JavaScript scripts are not injected into the Web component by default.
The script runs after any JavaScript code on the page, and the DOM tree has already been loaded and rendered at that point.
The scripts are executed in lexicographic order, not in the order of the array.
When scripts with identical content are injected multiple times, they are silently deduplicated without display or notification, and the scriptRules from the first injection are used.
This API does not support UrlRegexRule.
You are advised to use runJavaScriptOnDocumentEnd instead.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| scripts | Array<ScriptItem> | Yes | Script item array to be injected. When undefined or null is passed in, JavaScript scripts are not injected into Web components. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct Index {
- controller: webview.WebviewController = new webview.WebviewController();
- private jsStr: string =
- "window.document.getElementById(\"result\").innerHTML = 'this is msg from javaScriptOnDocumentEnd'";
- @State scripts: Array<ScriptItem> = [
- { script: this.jsStr, scriptRules: ["*"] }
- ];
-
- build() {
- Column({ space: 20 }) {
- Web({ src: $rawfile('index.html'), controller: this.controller })
- .javaScriptAccess(true)
- .domStorageAccess(true)
- .backgroundColor(Color.Grey)
- .javaScriptOnDocumentEnd(this.scripts)
- .width('100%')
- .height('100%')
- }
- }
- }
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- </head>
- <body style="font-size: 30px;">
- Hello world!
- <div id="result">test msg</div>
- </body>
- </html>
runJavaScriptOnDocumentStart(scripts: Array<ScriptItem>)
Injects a JavaScript script into the Web component. When the specified page or document starts to be loaded, the script is executed on any page whose source matches scriptRules. When this attribute is not explicitly called, JavaScript scripts are not injected into the Web component by default.
The script is injected after the root element (HTML Element) of the web document is created but before any other content is loaded.
The scripts are executed in the order of the array.
When scripts with identical content are injected multiple times, they are silently deduplicated without display or notification, and the scriptRules from the first injection are used.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| scripts | Array<ScriptItem> | Yes | Script item array to be injected. When undefined or null is passed in, JavaScript scripts are not injected into Web components. |
Example of the .ets file
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct Index {
- controller: webview.WebviewController = new webview.WebviewController();
- private localStorage: string =
- "if (typeof(Storage) !== 'undefined') {" +
- " localStorage.setItem('color', 'Red');" +
- "}";
- private localStorage2: string =
- "console.info('runJavaScriptOnDocumentStart urlRegexRules Matching succeeded.')";
- @State scripts: Array<ScriptItem> = [
- { script: this.localStorage, scriptRules: ["*"] },
- { script: this.localStorage2, scriptRules: [], urlRegexRules: [{secondLevelDomain: "", rule: ".*index.html"}] }
- ];
-
- build() {
- Column({ space: 20 }) {
- Web({ src: $rawfile('index.html'), controller: this.controller })
- .javaScriptAccess(true)
- .domStorageAccess(true)
- .backgroundColor(Color.Grey)
- .runJavaScriptOnDocumentStart(this.scripts)
- .width('100%')
- .height('100%')
- }
- }
- }
Example of the HTML file
- <!-- index.html -->
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- </head>
- <body style="font-size: 30px;" onload='bodyOnLoadLocalStorage()'>
- Hello world!
- <div id="result"></div>
- </body>
- <script type="text/javascript">
- function bodyOnLoadLocalStorage() {
- if (typeof(Storage) !== 'undefined') {
- document.getElementById('result').innerHTML = localStorage.getItem('color');
- } else {
- document.getElementById('result').innerHTML = 'Your browser does not support localStorage.';
- }
- }
- </script>
- </html>
runJavaScriptOnDocumentEnd(scripts: Array<ScriptItem>)
Injects a JavaScript script into the Web component. When the specified page or document has been loaded, the script is executed on any page whose source matches scriptRules. When this attribute is not explicitly called, JavaScript scripts are not injected into the Web component by default.
The script runs after any JavaScript code on the page, and the DOM tree has already been loaded and rendered at that point.
The scripts are executed in the order of the array.
When scripts with identical content are injected multiple times, they are silently deduplicated without display or notification, and the scriptRules from the first injection are used.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| scripts | Array<ScriptItem> | Yes | Script item array to be injected. When undefined or null is passed in, JavaScript scripts are not injected into Web components. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct Index {
- controller: webview.WebviewController = new webview.WebviewController();
- private jsStr: string =
- "window.document.getElementById(\"result\").innerHTML = 'this is msg from runJavaScriptOnDocumentEnd'";
- private jsStr2: string = "console.info('runJavaScriptOnDocumentEnd urlRegexRules Matching succeeded.')";
- @State scripts: Array<ScriptItem> = [
- { script: this.jsStr, scriptRules: ["*"] },
- { script: this.jsStr2, scriptRules: [], urlRegexRules: [{secondLevelDomain: "", rule: ".*index.html"}] }
- ];
-
- build() {
- Column({ space: 20 }) {
- Web({ src: $rawfile('index.html'), controller: this.controller })
- .javaScriptAccess(true)
- .domStorageAccess(true)
- .backgroundColor(Color.Grey)
- .runJavaScriptOnDocumentEnd(this.scripts)
- .width('100%')
- .height('100%')
- }
- }
- }
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- </head>
- <body style="font-size: 30px;">
- Hello world!
- <div id="result">test msg</div>
- </body>
- </html>
runJavaScriptOnHeadEnd(scripts: Array<ScriptItem>)
Injects a JavaScript script into the Web component. When the head tag of the DOM tree is parsed, the script is executed on any page whose source matches scriptRules. When this attribute is not explicitly called, JavaScript scripts are not injected into the Web component by default.
This script is executed in the array order.
If a script with the same content is injected for multiple times, the script is silently deduplicated, not displayed, and no notification is displayed. The scriptRules of the first injection is used.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| scripts | Array<ScriptItem> | Yes | Script item array to be injected. When undefined or null is passed in, JavaScript scripts are not injected into Web components. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct Index {
- controller: webview.WebviewController = new webview.WebviewController();
- private jsStr: string =
- "window.document.getElementById(\"result\").innerHTML = 'this is msg from runJavaScriptOnHeadEnd'";
- private jsStr2: string = "console.info('runJavaScriptOnHeadEnd urlRegexRules Matching succeeded.')";
- @State scripts: Array<ScriptItem> = [
- { script: this.jsStr, scriptRules: ["*"] },
- { script: this.jsStr2, scriptRules: [], urlRegexRules: [{secondLevelDomain: "", rule: ".*index.html"}] }
- ];
-
- build() {
- Column({ space: 20 }) {
- Web({ src: $rawfile('index.html'), controller: this.controller })
- .javaScriptAccess(true)
- .domStorageAccess(true)
- .backgroundColor(Color.Grey)
- .runJavaScriptOnHeadEnd(this.scripts)
- .width('100%')
- .height('100%')
- }
- }
- }
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- </head>
- <body style="font-size: 30px;">
- Hello world!
- <div id="result">test msg</div>
- </body>
- </html>
layoutMode(mode: WebLayoutMode)
Sets the layout mode of the Web component. If this attribute is not explicitly called, the Web layout follows the system mode (WebLayoutMode.NONE) by default. For common issues, see Web Component Size Adapting to Page Content Layout.
Currently, only two Web layout modes are supported:
The adaptive layout of the Web component height based on the frontend page has the following limitations:
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| mode | WebLayoutMode | Yes | Set the web layout mode to follow the system or use adaptive layout. When null or undefined is passed in, the value is WebLayoutMode.NONE |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- mode: WebLayoutMode = WebLayoutMode.FIT_CONTENT;
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller, renderMode: RenderMode.SYNC_RENDER })
- .layoutMode(this.mode)
- }
- }
- }
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- layoutMode: WebLayoutMode = WebLayoutMode.FIT_CONTENT;
- @State overScrollMode: OverScrollMode = OverScrollMode.NEVER;
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller, renderMode: RenderMode.SYNC_RENDER })
- .layoutMode(this.layoutMode)
- .overScrollMode(this.overScrollMode)
- }
- }
- }
nestedScroll(value: NestedScrollOptions | NestedScrollOptionsExt)
Sets nested scrolling options.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | NestedScrollOptions| NestedScrollOptionsExt14+ | Yes | Nested scrolling options. When the value is of the NestedScrollOptions type (forward and backward), the default nested scrolling mode of the scrollForward and scrollBackward options is NestedScrollMode.SELF_FIRST. When the value is of the NestedScrollOptionsExt type (up, down, left, and right), the default nested scrolling mode of the scrollUp, scrollDown, scrollLeft, and scrollRight options is NestedScrollMode.SELF_FIRST. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .nestedScroll({
- scrollForward: NestedScrollMode.SELF_FIRST,
- scrollBackward: NestedScrollMode.SELF_FIRST,
- })
- }
- }
- }
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController()
- build() {
- Scroll(){
- Column() {
- Text("Nested Web")
- .height("25%")
- .width("100%")
- .fontSize(30)
- .backgroundColor(Color.Yellow)
- Web({ src: $rawfile('index.html'),
- controller: this.controller })
- .nestedScroll({
- scrollUp: NestedScrollMode.SELF_FIRST,
- scrollDown: NestedScrollMode.PARENT_FIRST,
- scrollLeft: NestedScrollMode.SELF_FIRST,
- scrollRight: NestedScrollMode.SELF_FIRST,
- })
- }
- }
- }
- }
HTML file to be loaded:
- <!-- index.html -->
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" id="viewport" content="width=device-width, initial-scale=1.0">
- <style>
- .blue {
- background-color: lightblue;
- }
- .green {
- background-color: lightgreen;
- }
- .blue, .green {
- font-size:16px;
- height:200px;
- text-align: center; /* Horizontally centered */
- line-height: 200px; /* Vertically centered (the height matches the container height) */
- }
- </style>
- </head>
- <body>
- <div class="blue" >webArea</div>
- <div class="green">webArea</div>
- <div class="blue">webArea</div>
- <div class="green">webArea</div>
- <div class="blue">webArea</div>
- <div class="green">webArea</div>
- <div class="blue">webArea</div>
- </body>
- </html>
enableScrollDirectionalLock(value: boolean, type: ScrollDirectionalLockType)
Sets the scroll direction lock for the Web component to prevent simultaneous horizontal and vertical scrolling when the user swipes diagonally, thereby improving the scrolling experience. If this method is not explicitly called, scroll direction lock is supported by default in nested scrolling scenarios. The ALL mode applies to all scenarios where scroll locking is needed, while the NESTED_SCROLL mode applies only to nested scrolling scenarios.
System capability: SystemCapability.Web.Webview.Core
Since: 26.0.0
Model restriction: This API can be used only in the stage model.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | boolean | Yes | Whether to support scroll direction locking. The value true indicates that the scroll direction is locked, and the scroll view locks the scroll axis based on the user's initial scroll direction. The value false indicates that the scroll direction is not locked. |
| type | ScrollDirectionalLockType | Yes | Sets the scenarios in which the Web component expects scroll direction locking. ALL indicates that scroll locking is supported in all scenarios, and NESTED_SCROLL indicates that scroll locking is supported in nested scrolling scenarios. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .width('100%')
- .height('100%')
- // Support locking the scroll direction in all scenarios.
- .enableScrollDirectionalLock(true, ScrollDirectionalLockType.ALL)
- }
- }
- }
bypassVsyncCondition(condition: WebBypassVsyncCondition)
Sets the rendering process to bypass vsync (vertical synchronization) scheduling and directly trigger drawing when the scrollBy API is called to scroll the page. When this attribute is not explicitly called, vsync scheduling is not skipped by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| condition | WebBypassVsyncCondition | Yes | Condition for triggering the rendering process to bypass vsync scheduling. When undefined or null is passed in, the value is NONE. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- condition: WebBypassVsyncCondition = WebBypassVsyncCondition.SCROLLBY_FROM_ZERO_OFFSET;
-
- build() {
- Column() {
- Button('scrollBy')
- .onClick(() => {
- this.controller.scrollBy(0, 5);
- })
- Web({ src: 'www.example.com', controller: this.controller })
- .bypassVsyncCondition(this.condition)
- }
- }
- }
enableNativeEmbedMode(enabled: boolean)
Sets whether to enable the same-layer rendering feature. When this method is not explicitly called, the same-layer rendering feature is disabled by default.
APIs such as registerNativeEmbedRule and nativeEmbedOptions take effect only when this attribute is enabled.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enabled | boolean | Yes | Whether to enable the same-layer rendering feature. The value true means to enable the same-layer rendering feature, and false means the opposite. When undefined or null is passed in, the value is false. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .enableNativeEmbedMode(true)
- }
- }
- }
forceDisplayScrollBar(enabled: boolean)
Sets whether the scroll bar is always visible. Under the always-visible settings, when the page size exceeds one page, the scroll bar appears and remains visible. When this attribute is not explicitly called, the scroll bar is not always visible by default.
When layoutMode is set to WebLayoutMode.FIT_CONTENT, the enabled parameter is set to false.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enabled | boolean | Yes | Whether the scroll bar is always displayed. The value true indicates that the scroll bar is always displayed, and false indicates the opposite. When layoutMode is set to WebLayoutMode.FIT_CONTENT, the enabled parameter is forcibly set to false, and setting it to true does not take effect. If undefined or null is passed in, the attribute setting does not take effect. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: $rawfile('index.html'), controller: this.controller })
- .forceDisplayScrollBar(true)
- }
- }
- }
HTML file to be loaded:
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Demo</title>
- <style>
- body {
- width:2560px;
- height:2560px;
- padding-right:170px;
- padding-left:170px;
- border:5px solid blueviolet;
- }
- </style>
- </head>
- <body>
- Scroll Test
- </body>
- </html>
registerNativeEmbedRule(tag: string, type: string)
Registers the HTML tag name and type for same-layer rendering. The tag name only supports <object> and <embed>. The tag type only supports visible ASCII characters.
If the specified type is the same as the W3C standard <object> or <embed> type, the ArkWeb kernel identifies the type as a non-same-layer tag.
This API is also controlled by enableNativeEmbedMode and does not take effect when same-layer rendering is disabled. When this API is not used, the ArkWeb kernel recognizes the <embed> tags with the "native/" prefix as same-layer tags.
For details, see Using Same-Layer Rendering.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| tag | string | Yes | Tag name. |
| type | string | Yes | Tag type. The ArkWeb kernel uses a prefix to match this parameter. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
- import { NodeController, BuilderNode, NodeRenderType, FrameNode, UIContext } from '@kit.ArkUI';
-
- declare class Params {
- text: string;
- width: number;
- height: number;
- }
-
- declare class NodeControllerParams {
- surfaceId: string;
- renderType: NodeRenderType;
- width: number;
- height: number;
- }
-
- class MyNodeController extends NodeController {
- private rootNode: BuilderNode<[Params]> | undefined | null;
- private surfaceId_: string = "";
- private renderType_: NodeRenderType = NodeRenderType.RENDER_TYPE_DISPLAY;
- private width_: number = 0;
- private height_: number = 0;
-
- setRenderOption(params: NodeControllerParams) {
- this.surfaceId_ = params.surfaceId;
- this.renderType_ = params.renderType;
- this.width_ = params.width;
- this.height_ = params.height;
- }
-
- makeNode(uiContext: UIContext): FrameNode | null {
- this.rootNode = new BuilderNode(uiContext, { surfaceId: this.surfaceId_, type: this.renderType_ });
- this.rootNode.build(wrapBuilder(ButtonBuilder), { text: "myButton", width: this.width_, height: this.height_ });
- return this.rootNode.getFrameNode();
- }
-
- postInputEvent(event: TouchEvent | MouseEvent | undefined): boolean {
- return this.rootNode?.postInputEvent(event) as boolean;
- }
- }
-
- @Component
- struct ButtonComponent {
- @Prop params: Params;
- @State bkColor: Color = Color.Red;
-
- build() {
- Column() {
- Button(this.params.text)
- .height(50)
- .width(200)
- .border({ width: 2, color: Color.Red })
- .backgroundColor(this.bkColor)
- }
- .width(this.params.width)
- .height(this.params.height)
- }
- }
-
- @Builder
- function ButtonBuilder(params: Params) {
- ButtonComponent({ params: params })
- .backgroundColor(Color.Green)
- }
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- private nodeController: MyNodeController = new MyNodeController();
- uiContext: UIContext = this.getUIContext();
-
- build() {
- Column() {
- Stack() {
- NodeContainer(this.nodeController)
- Web({ src: $rawfile('index.html'), controller: this.controller })
- // Enable same-layer rendering.
- .enableNativeEmbedMode(true)
- // Register the same-layer tag of <object> and type of "native."
- .registerNativeEmbedRule("object", "native")
- // Obtain the lifecycle change data of the <object> tag.
- .onNativeEmbedLifecycleChange((object) => {
- if (object.status == NativeEmbedStatus.CREATE) {
- this.nodeController.setRenderOption({
- surfaceId: object.surfaceId as string,
- renderType: NodeRenderType.RENDER_TYPE_TEXTURE,
- width: this.uiContext!.px2vp(object.info?.width),
- height: this.uiContext!.px2vp(object.info?.height)
- });
- this.nodeController.rebuild();
- }
- })
- }
- }
- }
- }
HTML file to be loaded:
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <title>Same-Layer Rendering Test</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- </head>
- <body>
- <div>
- <div id="bodyId">
- <object id="nativeButton" type ="native/button" width="300" height="300" style="background-color:red">
- </object>
- </div>
- </div>
- </body>
- </html>
defaultTextEncodingFormat(textEncodingFormat: string)
Sets the default text encoding format for the web page. When this attribute is not explicitly called, the default text encoding format of the web page is UTF-8.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| textEncodingFormat | string | Yes | Default text encoding format. When null or undefined is passed in, the value is UTF-8. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: $rawfile('index.html'), controller: this.controller })
- // Set the height.
- .height(500)
- .defaultTextEncodingFormat("UTF-8")
- .javaScriptAccess(true)
- }
- }
- }
HTML file to be loaded:
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>My test html5 page</title>
- </head>
- <body>
- <p>Hello world!</p>
- </body>
- </html>
metaViewport(enabled: boolean)
Sets whether the viewport attribute of the meta tag is enabled. When this attribute is not explicitly called, the viewport attribute of the meta tag is supported by default.
System capability: SystemCapability.Web.Webview.Core
Device behavior difference: This API can be called on phones, wearables, and TVs, but does not work on PCs or 2in1 devices. For tablets, the viewport-fit attribute in the meta tag will be parsed no matter whether this parameter is set to true or false. When viewport-fit is set to cover, the size of the safe area can be obtained through the CSS attribute.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enabled | boolean | Yes | Whether the viewport attribute of the meta tag is enabled. The value true indicates that the viewport attribute of the meta tag is enabled and parsed, and the layout is performed based on the viewport attribute. The value false indicates the viewport attribute of the meta tag is disabled and not parsed, and the default layout is used. When null or undefined is passed in, the value is true. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: $rawfile('index.html'), controller: this.controller })
- .metaViewport(true)
- }
- }
- }
HTML file to be loaded:
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- </head>
- <body>
- <p>Hello world!</p>
- </body>
- </html>
textAutosizing(textAutosizing: boolean)
Sets whether to enable automatic font sizing for the Web component. When no attribute is explicitly called, automatic font sizing is enabled for the Web component by default.
After automatic font sizing takes effect, any text smaller than 16 px is enlarged to fall between 16 px and 32 px. This eliminates readability issues on narrow screens (viewport < 980 px) where mobile-specific layouts are absent.
System capability: SystemCapability.Web.Webview.Core
Device behavior: This API has no effect on the PCs/2-in-1 devices and works on other devices.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| textAutosizing | boolean | Yes | Whether to enable automatic text resizing. The value true means to enable automatic text resizing, and false means the opposite. When undefined or null is passed in, the value is true. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .textAutosizing(false)
- }
- }
- }
enableNativeMediaPlayer(config: NativeMediaPlayerConfig)
Sets whether to enable the application to take over web page media playback. When this attribute is not explicitly called, the web page media playback takeover feature is disabled by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| config | NativeMediaPlayerConfig | Yes | Configuration object for the application to take over web page media playback. It contains the following attributes: enable (boolean type, whether to enable this feature, defaults to false), shouldOverlay (boolean type, when the feature is enabled, whether the player view that the application takes over for web page video overlays the web page content, defaults to false). When undefined or null is passed in, the value is {enable: false, shouldOverlay: false}. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .enableNativeMediaPlayer({enable: true, shouldOverlay: false})
- }
- }
- }
onAdsBlocked(callback: OnAdsBlockedCallback)
Called after an ad is blocked on the web page to notify the user of detailed information about the blocked ad. To reduce the frequency of notifications and minimize the impact on the page loading process, only the first notification is made when the page is fully loaded. Subsequent blocking events are reported at intervals of 1 second, and no notifications are sent if there is no ad blocked.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | OnAdsBlockedCallback | Yes | Callback of onAdsBlocked. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- @State totalAdsBlockCounts: number = 0;
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'https://www.example.com', controller: this.controller })
- .onAdsBlocked((details: AdsBlockedDetails) => {
- if (details) {
- console.info(' Blocked ' + details.adsBlocked.length + ' in ' + details.url);
- let adList: Array<string> = Array.from(new Set(details.adsBlocked));
- this.totalAdsBlockCounts += adList.length;
- console.info('Total blocked counts :' + this.totalAdsBlockCounts);
- }
- })
- }
- }
- }
keyboardAvoidMode(mode: WebKeyboardAvoidMode)
Sets the custom soft keyboard avoidance mode.
If the keyboard avoidance mode set in UIContext is KeyboardAvoidMode.RESIZE, this API does not take effect.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| mode | WebKeyboardAvoidMode | Yes | Web soft keyboard avoidance mode. In the nested scrolling scenario, the soft keyboard avoidance mode of the Web component is not recommended, including RESIZE_VISUAL and RESIZE_CONTENT. Default value: WebKeyboardAvoidMode.RESIZE_CONTENT |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State avoidMode: WebKeyboardAvoidMode = WebKeyboardAvoidMode.RESIZE_VISUAL;
-
- build() {
- Column() {
- Web({ src: $rawfile("index.html"), controller: this.controller })
- .keyboardAvoidMode(this.avoidMode)
- }
- }
- }
HTML file to be loaded:
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <title>Test Web Page</title>
- </head>
- <body>
- <input type="text" placeholder="Text">
- </body>
- </html>
editMenuOptions(editMenu: EditMenuOptions)
Sets a custom text selection menu for the Web component.
This API is similar to bindSelectionMenu, with the following differences:
bindSelectionMenu: Fully customizes the menu style and trigger conditions, as defined by the developer.
It is not recommended to use both at the same time. Choose based on the degree of customization required.
You can use this attribute to customize a text menu.
You can use onCreateMenu to modify, add, and delete menu options. If you do not want to display the text menu, return an empty array.
You can use onMenuItemClick to customize the callback for menu options. This function is triggered after a menu option is clicked and determines whether to execute the default callback based on the return value. If true is returned, the system callback is not executed. If false is returned, the system callback is executed.
In onPrepareMenu20+, this callback is triggered after the text selection area changes and before the menu is displayed. You can modify, add, or delete menu options in the callback to dynamically update the menu.
If this method is used together with selectionMenuOptions(deprecated), the selectionMenuOptions (deprecated) method does not take effect.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| editMenu | EditMenuOptions | Yes | Custom text menu options for Web. The number of menu items, the content size of the menu, and the icon size are consistent with the ArkUI Menu component. Among the system-defined ID enumeration values (TextMenuItemId) in the menu, only CUT, COPY, PASTE, SELECT_ALL, TRANSLATE, SEARCH, and AI_WRITER are supported in Web. The textRange parameter in the onMenuItemClick function is meaningless in Web, and the passed-in value is -1. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- let selectText:string = '';
- class TestClass {
- setSelectText(param: String) {
- selectText = param.toString();
- }
- }
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State testObj: TestClass = new TestClass();
-
- onCreateMenu(menuItems: Array<TextMenuItem>): Array<TextMenuItem> {
- let items = menuItems.filter((menuItem) => {
- // Filter the menu items as required.
- return (
- menuItem.id.equals(TextMenuItemId.CUT) ||
- menuItem.id.equals(TextMenuItemId.COPY) ||
- menuItem.id.equals((TextMenuItemId.PASTE)) ||
- menuItem.id.equals((TextMenuItemId.TRANSLATE)) ||
- menuItem.id.equals((TextMenuItemId.SEARCH)) ||
- menuItem.id.equals((TextMenuItemId.AI_WRITER))
- )
- });
- let customItem1: TextMenuItem = {
- content: 'customItem1',
- id: TextMenuItemId.of('customItem1'),
- icon: $r('app.media.icon')
- };
- let customItem2: TextMenuItem = {
- content: $r('app.string.customItem2'),
- id: TextMenuItemId.of('customItem2'),
- icon: $r('app.media.icon')
- };
- items.push(customItem1);// Add an item to the end of the item list.
- items.unshift(customItem2);// Add an item to the beginning of the item list.
-
- return items;
- }
-
- onMenuItemClick(menuItem: TextMenuItem, textRange: TextRange): boolean {
- if (menuItem.id.equals(TextMenuItemId.CUT)) {
- // Custom behavior
- console.info("Intercept ID: CUT")
- // Return true to intercept this menu item and not perform the system default cut operation.
- return true;
- } else if (menuItem.id.equals(TextMenuItemId.COPY)) {
- // Custom behavior
- console.info("Not intercept ID: COPY")
- // Return false to not intercept this menu item and perform the system default copy operation.
- return false;
- } else if (menuItem.id.equals(TextMenuItemId.of('customItem1'))) {
- // Custom behavior
- console.info("Intercept ID: customItem1")
- return true;// Custom menu item. If true is returned, the menu is not closed after being clicked. If false is returned, the menu is closed.
- } else if (menuItem.id.equals((TextMenuItemId.of($r('app.string.customItem2'))))){
- // Custom behavior
- console.info("Intercept ID: app.string.customItem2")
- return true;
- }
- return false;// Return the default value false.
- }
-
- onPrepareMenu = (menuItems: Array<TextMenuItem>) => {
- let item1: TextMenuItem = {
- content: 'prepare1',
- id: TextMenuItemId.of('prepareMenu1'),
- };
- let item2: TextMenuItem = {
- content: 'prepare2' + selectText,
- id: TextMenuItemId.of('prepareMenu2'),
- };
- menuItems.push(item1);// Add an item to the end of the item list.
- menuItems.unshift(item2);// Add an item to the beginning of the item list.
-
- return menuItems;
- }
-
- @State EditMenuOptions: EditMenuOptions =
- { onCreateMenu: this.onCreateMenu, onMenuItemClick: this.onMenuItemClick, onPrepareMenu:this.onPrepareMenu }
-
- build() {
- Column() {
- Web({ src: $rawfile("index.html"), controller: this.controller })
- .editMenuOptions(this.EditMenuOptions)
- .javaScriptProxy({
- object: this.testObj,
- name: "testObjName",
- methodList: ["setSelectText"],
- controller: this.controller,
- })
- }
- }
- }
HTML file to be loaded:
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <title>Test Web Page</title>
- </head>
- <body>
- <h1>editMenuOptions Demo</h1>
- <span>edit menu options</span>
- <script>
- document.addEventListener('selectionchange', () => {
- var selection = window.getSelection();
- if (selection.rangeCount > 0) {
- var selectedText = selection.toString();
- testObjName.setSelectText(selectedText);
- }
- });
- </script>
- </body>
- </html>
enableHapticFeedback(enabled: boolean)
Sets whether to enable haptic feedback for long-pressed text in the Web component. The ohos.permission.VIBRATE permission must be declared. When this attribute is not explicitly called, haptic feedback is enabled by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enabled | boolean | Yes | Whether to enable vibration. true indicates enabling vibration, and false indicates disabling vibration. When undefined or null is passed in, the default value is retained, that is, vibration is enabled. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: $rawfile("index.html"), controller: this.controller })
- .enableHapticFeedback(true)
- }
- }
- }
HTML file to be loaded:
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <title>Test Web Page</title>
- </head>
- <body>
- <h1>enableHapticFeedback Demo</h1>
- <span>enable haptic feedback</span>
- </body>
- </html>
bindSelectionMenu(elementType: WebElementType, content: CustomBuilder, responseType: WebResponseType, options?: SelectionMenuOptionsExt)
Sets the custom selection menu.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| elementType | WebElementType | Yes | Menu type. |
| content | CustomBuilder | Yes | Menu content. |
| responseType | WebResponseType | Yes | Response type of the menu. |
| options | SelectionMenuOptionsExt | No | Options of the menu. The default configuration is used when undefined or null is passed in. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
- import { pasteboard } from '@kit.BasicServicesKit';
- import { BusinessError } from '@kit.BasicServicesKit';
-
- interface PreviewBuilderParam {
- width: number;
- height: number;
- url:Resource | string | undefined;
- }
-
- interface PreviewBuilderParamForImage {
- previewImage: Resource | string | undefined;
- width: number;
- height: number;
- }
-
-
- @Builder function PreviewBuilderGlobalForImage($$: PreviewBuilderParamForImage) {
- Column() {
- Image($$.previewImage)
- .objectFit(ImageFit.Fill)
- .autoResize(true)
- }.width($$.width).height($$.height)
- }
-
- @Entry
- @Component
- struct SelectionMenuLongPress {
- controller: webview.WebviewController = new webview.WebviewController();
- previewController: webview.WebviewController = new webview.WebviewController();
- @Builder PreviewBuilder($$: PreviewBuilderParam){
- Column() {
- Stack(){
- Text("") // Select whether to display the URL.
- .padding(5)
- .width('100%')
- .textAlign(TextAlign.Start)
- .backgroundColor(Color.White)
- .copyOption(CopyOptions.LocalDevice)
- .maxLines(1)
- .textOverflow({overflow:TextOverflow.Ellipsis})
- Progress({ value: this.progressValue, total: 100, type: ProgressType.Linear }) // Display the progress bar.
- .style({ strokeWidth: 3, enableSmoothEffect: true })
- .backgroundColor(Color.White)
- .opacity(this.progressVisible?1:0)
- .backgroundColor(Color.White)
- }.alignContent(Alignment.Bottom)
- Web({src:$$.url,controller: new webview.WebviewController()})
- .javaScriptAccess(true)
- .fileAccess(true)
- .onlineImageAccess(true)
- .imageAccess(true)
- .domStorageAccess(true)
- .onPageBegin(()=>{
- this.progressValue = 0;
- this.progressVisible = true;
- })
- .onProgressChange((event)=>{
- this.progressValue = event.newProgress;
- })
- .onPageEnd(()=>{
- this.progressVisible = false;
- })
- .hitTestBehavior(HitTestMode.None) // Disable the gesture response during web page preview.
- }.width($$.width).height($$.height) // Set the preview width and height.
- }
-
- private result: WebContextMenuResult | undefined = undefined;
- @State previewImage: Resource | string | undefined = undefined;
- @State previewWidth: number = 1;
- @State previewHeight: number = 1;
- @State previewWidthImage: number = 1;
- @State previewHeightImage: number = 1;
- @State linkURL:string = "";
- @State progressValue:number = 0;
- @State progressVisible:boolean = true;
- uiContext: UIContext = this.getUIContext();
- enablePaste = false;
-
- clearSelection() {
- try {
- this.controller.runJavaScript(
- 'clearSelection()',
- (error, result) => {
- if (error) {
- console.error(`run clearSelection JavaScript error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
- return;
- }
- if (result) {
- console.info(`The clearSelection() return value is: ${result}`);
- }
- });
- } catch (error) {
- console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
- }
- }
-
-
- @Builder
- LinkMenuBuilder() {
- Menu() {
- MenuItem({ content: 'Copy Link', })
- .onClick(() => {
- const pasteboardData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, this.linkURL);
- const systemPasteboard = pasteboard.getSystemPasteboard();
- systemPasteboard.setData(pasteboardData);
- })
- MenuItem({content:'Open Link'})
- .onClick(()=>{
- this.controller.loadUrl(this.linkURL);
- })
- }
- }
- @Builder
- ImageMenuBuilder() {
- Menu() {
- MenuItem({ content: 'Copy Image', })
- .onClick(() => {
- this.result?.copyImage();
- this.result?.closeContextMenu();
- })
- }
- }
- @Builder
- TextMenuBuilder() {
- Menu() {
- MenuItem({ content: 'Copy', })
- .onClick(() => {
- try {
- this.controller.runJavaScript(
- 'copySelectedText()',
- (error, result) => {
- if (error) {
- console.error(`run copySelectedText JavaScript error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
- return;
- }
- if (result) {
- console.info(`The copySelectedText() return value is: ${result}`);
- }
- });
- } catch (error) {
- console.error(`Failed to clear selection. Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}`);
- }
- this.clearSelection()
- }).backgroundColor(Color.Pink)
- }
- }
- build() {
- Column() {
- Web({ src: $rawfile("index.html"), controller: this.controller })
- .javaScriptAccess(true)
- .fileAccess(true)
- .onlineImageAccess(true)
- .imageAccess(true)
- .domStorageAccess(true)
- .bindSelectionMenu(WebElementType.TEXT, this.TextMenuBuilder, WebResponseType.LONG_PRESS,
- {
- onAppear: () => {},
- onDisappear: () => {},
- menuType: MenuType.SELECTION_MENU,
- })
- .bindSelectionMenu(WebElementType.LINK, this.LinkMenuBuilder, WebResponseType.LONG_PRESS,
- {
- onAppear: () => {},
- onDisappear: () => {
- this.result?.closeContextMenu();
- },
- preview: this.PreviewBuilder({
- width: 500,
- height: 400,
- url:this.linkURL
- }),
- menuType: MenuType.PREVIEW_MENU
- })
- .bindSelectionMenu(WebElementType.IMAGE, this.ImageMenuBuilder, WebResponseType.LONG_PRESS,
- {
- onAppear: () => {},
- onDisappear: () => {
- this.result?.closeContextMenu();
- },
- preview: PreviewBuilderGlobalForImage({
- previewImage: this.previewImage,
- width: this.previewWidthImage,
- height: this.previewHeightImage,
- }),
- menuType: MenuType.PREVIEW_MENU,
- })
- .zoomAccess(true)
- .onContextMenuShow((event) => {
- if (event) {
- this.result = event.result;
- this.previewWidthImage = this.uiContext!.px2vp(event.param.getPreviewWidth());
- this.previewHeightImage = this.uiContext!.px2vp(event.param.getPreviewHeight());
- if (event.param.getSourceUrl().indexOf("resource://rawfile/") == 0) {
- this.previewImage = $rawfile(event.param.getSourceUrl().substring(19));
- } else {
- this.previewImage = event.param.getSourceUrl();
- }
- this.linkURL = event.param.getLinkUrl()
- // Return true to intercept the system default context menu and use the custom menu.
- return true;
- }
- return false;
- })
- }
-
- }
- // Swipe back
- onBackPress(): boolean | void {
- if (this.controller.accessStep(-1)) {
- this.controller.backward();
- return true;
- } else {
- return false;
- }
- }
- }
HTML file to be loaded:
- <!--index.html-->
- <!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Touch and hold to copy text</title>
- <style>
- .container {
- background-color: white;
- padding: 30px;
- margin: 20px 0;
- }
- .context {
- line-height: 1.8;
- font-size: 18px;
- }
- .context span {
- border-radius: 8px;
- background-color: #f8f9fa;
- }
- .context a {
- color: #3498db;
- text-decoration: none;
- font-size: 18px;
- font-weight: 600;
- padding: 12px 24px;
- border: 2px solid #3498db;
- border-radius: 30px;
- display: inline-block;
- position: relative;
- overflow: hidden;
- margin-bottom: 20px;
- }
- .context img {
- max-width: 100%;
- height: auto;
- display: block;
- margin-bottom: 20px;
- }
- .context:hover img {
- transform: scale(1.05);
- }
- </style>
- </head>
- <body>
- <div class="container">
-
- <div class="context">
- <!--img.png is in the same directory as the html file-->
- <img src="img.png">
- </div>
-
- <div class="context">
- <a href="https://www.example.com">Touch and hold the link to display the menu</a>
- </div>
-
- <div class="context">
- <span>In this digital age, the text copying functionality has grown increasingly important. Whether quoting famous remarks, saving key information, or sharing interesting content, copying text is an integral part of our daily operations.</span>
- </div>
-
- </div>
- <br>
-
- <script>
- function copySelectedText() {
- const selectedText = window.getSelection().toString();
- if (selectedText.length > 0) {
- // Use the Clipboard API to copy text.
- navigator.clipboard.writeText(selectedText)
- .then(() => {
- showNotification();
- })
- .catch(err => {
- console.error('Copy failed:', err);
- });
- }
- }
- function clearSelection() {
- if (window.getSelection) {
- window.getSelection().removeAllRanges();
- }
- }
- </script>
- </body>
- </html>
blurOnKeyboardHideMode(mode: BlurOnKeyboardHideMode)
Sets the blur mode for Web elements when the soft keyboard is dismissed. If this attribute is not explicitly called, the BlurOnKeyboardHideMode.SILENT mode is used by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| mode | BlurOnKeyboardHideMode | Yes | Whether to enable blur mode of the web element when soft keyboard is hidden. The default value is BlurOnKeyboardHideMode.SILENT. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State blurMode: BlurOnKeyboardHideMode = BlurOnKeyboardHideMode.BLUR;
- build() {
- Column() {
- Web({ src: $rawfile("index.html"), controller: this.controller })
- .blurOnKeyboardHideMode(this.blurMode)
- }
- }
- }
HTML file to be loaded:
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <title>Test Web Page</title>
- </head>
- <body>
- <h1>blurOnKeyboardHideMode Demo</h1>
- <input type="text" id="input_a">
- <script>
- const inputElement = document.getElementById('input_a');
- inputElement.addEventListener('blur', function() {
- console.info('Input has lost focus');
- });
- </script>
- </body>
- </html>
enableFollowSystemFontWeight(follow: boolean)
Sets whether the Web component can change the font weight according to the system settings. When this attribute is not explicitly called, the Web component does not change the font weight according to the system settings by default.
Currently, only front-end text elements support this capability. The canvas element and embedded .docx and .pdf texts do not support this capability.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| follow | boolean | Yes | Whether the Web component can change the font weight according to the system settings. The value true means that the Web component can change the font weight according to the system settings, and false means the opposite. When undefined or null is passed in, the value is false. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- build() {
- Column() {
- Web({ src: "www.example.com", controller: this.controller })
- .enableFollowSystemFontWeight(true)
- }
- }
- }
optimizeParserBudget(optimizeParserBudget: boolean)
Sets whether to enable segment-based HTML parsing optimization. If no attribute is explicitly called, the parsing time is used as the segment point by default.
To avoid occupying too many main thread resources and enable progressive loading of web pages, the ArkWeb kernel uses the segment-based parsing policy when parsing the HTML files. By default, the ArkWeb kernel uses the parsing time as the segment point. When the parsing time exceeds the threshold, the parsing is interrupted and then the layout and rendering operations are performed.
After optimization is enabled, the ArkWeb kernel not only checks whether the parsing time exceeds the limit, but also additionally determines whether the number of parsed tokens (the smallest parsing units of an HTML document, such as <div>, attr="xxx", etc.) exceeds the threshold specified by the kernel, and lowers this threshold. When the FCP (First Contentful Paint) of the page is triggered, the default interrupt judgment logic is restored. This makes the parsing operations before FCP more frequent, thereby increasing the possibility that the first-frame content is parsed and enters the rendering phase earlier, while effectively reducing the rendering workload of the first frame, ultimately advancing the FCP time.
When the FCP of a page is triggered, the default segment parsing logic is restored. Therefore, the segment-based HTML parsing optimization takes effect only for the first page loaded by each Web component.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| optimizeParserBudget | boolean | Yes | Whether to enable segment-based HTML parsing optimization. The value true means to use the number of parsed records instead of the parsing time as the segment point for HTML segment parsing, and reduce the upper limit of the number of parsed records in each segment. The value false means to use the parsing time as the segment point for HTML segment parsing. If undefined or null is passed in, the value is false. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController()
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .optimizeParserBudget(true)
- }
- }
- }
enableWebAVSession(enabled: boolean)
Sets whether to support an application to connect to media controller. If this attribute is not explicitly set, the application can connect to media controller by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enabled | boolean | Yes | Whether to support an application to connect to media controller. The value true means to support an application to connect to media controller, and false means the opposite. When undefined or null is passed in, the value is true. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- build() {
- Column() {
- Web({ src: $rawfile('index.html'), controller: this.controller })
- .enableWebAVSession(true)
- }
- }
- }
HTML file to be loaded:
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <title>Video Playback Page</title>
- </head>
- <body>
- <h1>Video Playback</h1>
- <video id="testVideo" controls>
- <!--Save an MP4 media file in the rawfile directory of resources and name it example.mp4.-->
- <source src="example.mp4" type="video/mp4">
- </video>
- </body>
- </html>
nativeEmbedOptions(options?: EmbedOptions)
Sets the same-layer rendering configuration. This attribute takes effect only when enableNativeEmbedMode is enabled and cannot be dynamically modified. If this attribute is not explicitly called, the default value {supportDefaultIntrinsicSize: false} is used.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| options | EmbedOptions | No | Configuration options of the same-layer rendering. If undefined or null is passed in, the value {supportDefaultIntrinsicSize: false} is used. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- options: EmbedOptions = {supportDefaultIntrinsicSize: true};
-
- build() {
- Column() {
- Web({ src: $rawfile("index.html"), controller: this.controller })
- .enableNativeEmbedMode(true)
- .nativeEmbedOptions(this.options)
- }
- }
- }
HTML file to be loaded:
- <!-- index.html -->
- <!DOCTYPE html>
- <html>
- <head>
- <title>Same-Layer Rendered Fixed-Size HTML Test</title>
- </head>
- <body>
- <div>
- <embed id="input" type = "native/view" style = "background-color:red"/>
- </div>
- </body>
- </html>
enableDataDetector(enable: boolean)
Sets whether to recognize special entities of web texts, such as emails, phone numbers, and URLs. This API depends on the text recognition capability at the bottom layer of the device. Otherwise, the setting is invalid. When this attribute is not explicitly called, the detector is disabled by default.
Attributes such as dataDetectorConfig and enableSelectedDataDetector take effect only when this attribute is enabled.
If enableDataDetector is set to true and dataDetectorConfig is not set, all types of entities will be recognized, and the color and decoration attributes of the recognized entities will be changed to the following styles:
- color: '#ff0a59f7',
- decoration:{
- type: TextDecorationType.Underline,
- color: '#ff0a59f7',
- style: TextDecorationStyle.SOLID
- }
When enableDataDetector is set to true and copyOptions is set to CopyOptions.LocalDevice, the AI menu feature is activated. In this case, after text is selected on the web page, the text selection menu can display the corresponding AI menu items, including url (open link), email (create new email), phoneNumber (call), address (navigate to the location), and dateTime (create new schedule reminder) from TextMenuItemId.
When the AI menu takes effect, the corresponding option can be displayed only when the selection contains a complete AI entity. This menu item and the askAI menu item in TextMenuItemId do not appear at the same time.
For details about the application scenario, see Using Smart Text Data Detector.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enable | boolean | Yes | Whether to enable web text recognition. The value true means to enable web text recognition, and false means the opposite. When undefined or null is passed in, the attribute setting does not take effect. |
Dynamically updating the enableDataDetector status does not affect the current page immediately. You need to refresh the page for the new configuration to take effect.
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: $rawfile("index.html"), controller: this.controller })
- .enableDataDetector(true)
- }
- }
- }
HTML file to be loaded:
- <!-- index.html -->
- <!DOCTYPE html>
- <html>
- <head>
- <title>Example enableDataDetector</title>;
- </head>
- <body>
- <p> Telephone: 400-123-4567 </p>
- <p>Email: example@example.com </p>
- </body>
- </html>
dataDetectorConfig(config: TextDataDetectorConfig)
Configures text recognition settings.
This API must be used together with enableDataDetector. It takes effect only when enableDataDetector is set to true.
When entities A and B overlap, the following rules are followed:
If A is a subset of B (A ⊂ B), then B is retained; otherwise, A is retained.
If A is not a subset of B (A ⊄ B) and B is not a subset of A (B ⊄ A), and if the starting point of A is earlier than that of B (A.start < B.start), then A is retained; otherwise, B is retained.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| config | TextDataDetectorConfig | Yes | Text recognition configuration. |
The onDetectResultUpdate method in TextDataDetectorConfig is not supported in the Web component. The configured callback will not be called.
When copyOptions is set to CopyOptions.None, the enablePreviewMenu item in TextDataDetectorConfig is invalid.
Dynamically updating the TextDataDetectorConfig configuration does not affect the current page immediately. You need to refresh the page for the new configuration to take effect.
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: $rawfile("index.html"), controller: this.controller })
- .enableDataDetector(true)
- .dataDetectorConfig({
- types: [
- TextDataDetectorType.PHONE_NUMBER,
- TextDataDetectorType.EMAIL
- ],
- color: Color.Red,
- decoration: {
- type: TextDecorationType.LineThrough,
- color: Color.Green,
- style: TextDecorationStyle.WAVY
- }
- })
- }
- }
- }
HTML file to be loaded:
- <!-- index.html -->
- <!DOCTYPE html>
- <html>
- <head>
- <title>Example dataDetectorConfig</title>;
- </head>
- <body>
- <p> Telephone: 400-123-4567 </p>
- <p> Email: 12345678901@example.com </p>
- <p> Website: www.example.com (cannot be identified) </p>
- </body>
- </html>
enableSelectedDataDetector(enable: boolean)
Sets whether to enable the AI menu feature for text selection menu. After the AI menu feature is enabled, the email, phone number, website, date, and address in the selection can be identified, and the corresponding AI menu items are displayed in the text selection menu. By default, the AI menu feature is enabled.
When the AI menu feature is enabled, after text is selected on the web page, the text selection menu can display the corresponding AI menu items, including url (open link), email (create new email), phoneNumber (call), address (navigate to the location), and dateTime (create new schedule) from TextMenuItemId.
When the AI menu takes effect, the corresponding option can be displayed only when the selection contains a complete AI entity. This menu item and the askAI menu item in TextMenuItemId do not appear at the same time.
For details about the application scenario, see Using Smart Text Data Detector.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enable | boolean | Yes | Whether to enable web text recognition. The value true means to enable web text recognition, and false means the opposite. If undefined or null is passed in, the attribute is reset to the default value. |
If enableSelectedDataDetector is not set or is set to true, the types in dataDetectorConfig are used. If dataDetectorConfig is not set, all types are recognized by default.
If enableSelectedDataDetector is set to false, the AI menu for text selection is not activated.
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: $rawfile("index.html"), controller: this.controller })
- .enableSelectedDataDetector(true)
- }
- }
- }
HTML file to be loaded:
- <!-- index.html -->
- <!DOCTYPE html>
- <html>
- <head>
- <title>enableSelectedDataDetector Example</title>
- </head>
- <body>
- <p> Telephone: 400-123-4567 </p>
- <p>Email: example@example.com </p>
- </body>
- </html>
gestureFocusMode(mode: GestureFocusMode)
Sets the gesture focus mode of the Web component, which controls the focus response behavior of the Web component. If this attribute is not explicitly called, the default behavior is that any gesture causes the Web component to gain focus when the gesture is pressed.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| mode | GestureFocusMode | Yes | Gesture focus mode of the Web component. If undefined or null is passed in, the value GestureFocusMode.DEFAULT is used. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State mode: GestureFocusMode = GestureFocusMode.DEFAULT;
- build() {
- Column() {
- Web({ src: $rawfile("index.html"), controller: this.controller })
- .gestureFocusMode(this.mode)
- }
- }
- }
HTML file to be loaded:
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <title>Test Web Page</title>
- </head>
- <body>
- <input type="text" placeholder="Text">
- </body>
- </html>
rotateRenderEffect(effect: WebRotateEffect)
Sets how the final state of the Web component's content is rendered during its width and height animation process when the component rotates. If this attribute is not explicitly called, by default, the component's content stays at the final size and always aligned with the upper left corner of the component.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| effect | WebRotateEffect | Yes | How the final state of the Web component's content is rendered during its width and height animation process when the component rotates. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State effect: WebRotateEffect = WebRotateEffect.TOPLEFT_EFFECT;
- build() {
- Column() {
- Web({ src: $rawfile("index.html"), controller: this.controller })
- .rotateRenderEffect(this.effect)
- }
- }
- }
HTML file to be loaded:
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <title>Test Web Page</title>
- </head>
- <body>
- <p>Test Web Page</p>
- </body>
- </html>
forceEnableZoom(enable: boolean)
Sets whether to enable the forcible zoom functionality for the Web component.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enable | boolean | Yes | Whether to comply with the zoom restriction specified by the <meta name="viewport"> tag on the web page. The value true means to not comply with the web page zoom restriction, and false means the opposite. When undefined or null is passed in, the attribute setting does not take effect. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: $rawfile("index.html"), controller: this.controller })
- .forceEnableZoom(true)
- }
- }
- }
HTML file to be loaded:
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
- <title>Test Web Page</title>
- </head>
- <body>
- <h1>forceEnableZoom Demo</h1>
- <span>You can scale page when forceEnableZoom is true.</span>
- </body>
- </html>
backToTop(backToTop: boolean)
Sets whether to enable the back-to-top feature for the Web component when the status bar is touched. When this attribute is not explicitly called, the back-to-top feature for the status bar is enabled by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| backToTop | boolean | Yes | Whether to enable the back-to-top feature. The value true means to enable the feature, and false means the opposite. When undefined or null is passed in, the value is true. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: $rawfile("index.html"), controller: this.controller })
- .backToTop(true)
- }
- }
- }
HTML file to be loaded:
- <!-- index.html -->
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" id="viewport" content="width=device-width, initial-scale=1.0">
- <style>
- .blue {
- background-color: lightblue;
- }
- .green {
- background-color: lightgreen;
- }
- .blue, .green {
- font-size:16px;
- height:200px;
- text-align: center; /* Horizontally centered */
- line-height: 200px; /* Vertically centered (the height matches the container height) */
- }
- </style>
- </head>
- <body>
- <div class="blue" >webArea</div>
- <div class="green">webArea</div>
- <div class="blue">webArea</div>
- <div class="green">webArea</div>
- <div class="blue">webArea</div>
- <div class="green">webArea</div>
- <div class="blue">webArea</div>
- <div class="green">webArea</div>
- <div class="blue">webArea</div>
- </body>
- </html>
blankScreenDetectionConfig(detectConfig: BlankScreenDetectionConfig)
Sets the blank screen detection configuration, such as whether to enable the detection, detection time, and detection policy. When this attribute is not explicitly called, blank screen detection is disabled by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| detectConfig | BlankScreenDetectionConfig | Yes | Blank screen detection policy. |
Example
- // blankScreenDetectionConfig.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .blankScreenDetectionConfig({
- enable: true,
- detectionTiming: [2, 4, 6, 8],
- contentfulNodesCountThreshold: 4,
- detectionMethods:[BlankScreenDetectionMethod.DETECTION_CONTENTFUL_NODES_SEVENTEEN]
- })
- .onDetectedBlankScreen((event: BlankScreenDetectionEventInfo)=>{
- console.info(`Found blank screen on ${event.url}.`);
- console.info(`The blank screen reason is ${event.blankScreenReason}.`);
- console.info(`The blank screen detail is ${event.blankScreenDetails?.detectedContentfulNodesCount}.`);
- })
- }
- }
- }
enableImageAnalyzer(enable: boolean)
Sets whether to enable AI analysis of web page images. Currently, the image text recognition feature is supported. If this attribute is not explicitly called, this feature is enabled by default.
When you long-press or hover the mouse over the image text, AI analyzer is triggered and the text in the image can be selected. The specifications of images that can trigger analyzer are as follows:
The original width and height of the image are greater than or equal to 100 pixels.
For devices other than 2-in-1 devices, the image rendering width must exceed 80% of the web page width.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enable | boolean | Yes | Whether to enable AI analyzer for web page images. The value true means to enable AI analyzer, and false means the opposite. If undefined or null is passed in, the value is reset to true. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: $rawfile("index.html"), controller: this.controller })
- .enableImageAnalyzer(true) // To disable the image analyzer, set this parameter to false.
- }
- }
- }
HTML file to be loaded:
- <!-- index.html -->
- <!DOCTYPE html>
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" id="viewport" content="width=device-width, initial-scale=1.0">
- <style>
- .image-container {
- width: 90%;
- }
- .image-container img {
- width: 100%;
- height: auto;
- }
- </style>
- </head>
- <body>
- <div class="image-container">
- <!--example.jpg is in the same directory as the HTML file-->
- <img src="example.jpg" alt="Image to be analyzed by AI">
- </div>
- </body>
- </html>
enableAutoFill(value: boolean)
Sets whether to enable web page autofill. By default, this feature is enabled.
The autofill feature of this API depends on SmartFill service and Password Autofill Service.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | boolean | Yes | Whether to enable autofill for web pages. The value true means to enable autofill, and false means the opposite. When undefined or null is passed in, the value is true. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: $rawfile("index.html"), controller: this.controller })
- .enableAutoFill(true)
- }
- }
- }
HTML file to be loaded:
- <!-- index.html -->
- <!DOCTYPE html>
- <html>
- <head>
- <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" name="viewport"/>
- <title>Autofill test</title>
- </head>
- <body>
- <h4 align="center">Autofill test</h4>
- <form method="post" action="">
- <div align="center">
- <label for="name" style="width: 120px; display: inline-block; text-align: end;">Name:</label>
- <input type="text" id="name" autocomplete="name"/><br/><br/>
- <label for="tel-national" style="width: 120px; display: inline-block; text-align: end;">Mobile number:</label>
- <input type="text" id="tel-national" autocomplete="tel-national"/><br/><br/>
- </div>
- <div align="center">
- <button type="submit" style="width: 80px">Submit</button>
- </div>
- </form>
- </body>
- </html>
enableDefaultContextMenu(enable: boolean)
Sets whether to enable the default right-click context menu. If this method is not explicitly called, the menu is disabled by default. The default menu supports only the CUT, COPY, PASTE, and SELECT_ALL menu items.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enable | boolean | Yes | Whether to enable the default right-click context menu. The value true indicates enabling, and false indicates disabling. The value is false when undefined or null is passed in. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .enableDefaultContextMenu(true)
- }
- }
- }
enableDrag(value: boolean)
Sets whether to enable the drag function. If this attribute is not explicitly called, the web page drag function is enabled by default.
Since: 26.0.0
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| value | boolean | Yes | Whether to enable the web page drag function. The value true indicates enabling, and false indicates disabling. When undefined or null is passed in, the value is true. |
| Example |
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct Index {
- private controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: $rawfile('test.html'), controller: this.controller })
- .enableDrag(false)
- }
- }
- }
HTML file to be loaded:
- <!--test.html-->
- <!DOCTYPE html>
- <html>
- <head><meta charset="UTF-8"><title>Drag test</title></head>
- <body>
- <div id="drag" draggable="true" style="width:100px;height:100px;background:red;margin:20px;"></div>
- <div id="drop" style="width:200px;height:200px;background:gray;margin:20px;"></div>
- <script>
- drag.ondragstart=e=>e.dataTransfer.setData('text/plain','');
- drop.ondragover=e=>e.preventDefault();
- drop.ondrop=e=>{e.preventDefault(); drop.style.background='green';};
- drag.ondragend=()=>{drop.style.background='gray';};
- </script>
- </body>
- </html>
password(password: boolean)
Sets whether to save the password. This API is an empty API.
This API is supported since API version 8 and deprecated since API version 10. You are advised to use enableAutoFill23+ instead.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| password | boolean | Yes | Whether to allow the web component to save passwords. The value true means the web component is allowed to save passwords, and false means the opposite. If undefined or null is passed, the default value false is used. |
textZoomAtio(textZoomAtio: number)
Sets the text zoom ratio of the page.
This API is supported since API version 8 and deprecated since API version 9. You are advised to use textZoomRatio9+ instead.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| textZoomAtio | number | Yes | Text zoom percentage of the web page to set. 100 indicates the original size, a value greater than 100 indicates zooming in, and a value less than 100 indicates zooming out. The value range is (0, 2147483647]. |
Example
- // xxx.ets
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController()
- @State ratio: number = 150
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .textZoomAtio(this.ratio)
- }
- }
- }
userAgent(userAgent: string)
Sets the user agent.
This API is supported since API version 8 and deprecated since API version 10. You are advised to use setCustomUserAgent10+ instead.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| userAgent | string | Yes | User agent to set. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State userAgent:string = 'Mozilla/5.0 (Phone; OpenHarmony 5.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 ArkWeb/4.1.6.1 Mobile DemoApp';
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .userAgent(this.userAgent)
- }
- }
- }
tableData(tableData: boolean)
Sets whether to save form data. When this attribute is not explicitly called, the Web component is allowed to save form data by default. This API is an empty API.
This API is supported since API version 8 and deprecated since API version 10. You are advised to use enableAutoFill23+ instead.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| tableData | boolean | Yes | Whether to allow the Web component to save form data. The value true means the Web component is allowed to save form data, and false means the opposite. If undefined or null is passed, the value is true. |
wideViewModeAccess(wideViewModeAccess: boolean)
Sets whether to support the viewport attribute of the HTML <meta> tag. This API is an empty API.
This API is supported since API version 8 and deprecated since API version 10. You are advised to use metaViewport12+ instead.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| wideViewModeAccess | boolean | Yes | Whether to support the viewport attribute of the HTML <meta> tag. The value true means to support the viewport attribute of the HTML <meta> tag, and false means the opposite. |
selectionMenuOptions(expandedMenuOptions: Array<ExpandedMenuItemOptions>)
Sets the extended options of the custom context menu on selection, including the text content, icon, and callback.
The API only supports the selection of plain text; if the selected content contains images or other non-text elements, the action information may display garbled content.
When used together with editMenuOptions, this API does not take effect.
This API is supported since API version 12 and deprecated since API version 20. You are advised to use editMenuOptions12+ instead.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| expandedMenuOptions | Array<ExpandedMenuItemOptions> | Yes | Extended options of the custom context menu on selection. The number of menu options, menu content size, and start icon size must be the same as those of the ArkUI Menu component. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State menuOptionArray: Array<ExpandedMenuItemOptions> = [
- {content: 'Apple', startIcon: $r('app.media.icon'), action: (selectedText) => {
- console.info('select info ' + selectedText.toString());
- }},
- {content: 'Banana', startIcon: $r('app.media.icon'), action: (selectedText) => {
- console.info('select info ' + selectedText.toString());
- }}
- ];
-
- build() {
- Column() {
- Web({ src: $rawfile("index.html"), controller: this.controller })
- .selectionMenuOptions(this.menuOptionArray)
- }
- }
- }
HTML file to be loaded:
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <title>Test Web Page</title>
- </head>
- <body>
- <h1>selectionMenuOptions Demo</h1>
- <span>selection menu options</span>
- </body>
- </html>
zoomControlAccess(zoomControlAccess: boolean)
Sets whether to allow zooming by pressing Ctrl + '-/+' or Ctrl + mouse wheel/touchpad.
If this attribute is not explicitly called, zooming by pressing Ctrl + '-/+' or Ctrl + mouse wheel/touchpad is allowed by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| zoomControlAccess | boolean | Yes | Set whether to allow scaling through combined keys. true indicates support, and false indicates no support. The value is false when null or undefined is passed in. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: $rawfile("index.html"), controller: this.controller })
- .zoomControlAccess(true)
- }
- }
- }
HTML file to be loaded:
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Test Web Page</title>
- </head>
- <body>
- <h1>zoomControlAccess Demo</h1>
- <span>You can zoom in/out page when zoomControlAccess is true.</span>
- </body>
- </html>
aiSessionOptions(aiSessions: Array<AISessionEvent>)
Configures custom frontend AI sessions for the Web component, used to register multiple custom AI sessions.
System capability: SystemCapability.Web.Webview.Core
Since: 26.0.0
Model restriction: This API can be used only in the stage model.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| aiSessions | Array<AISessionEvent> | Yes | Array of frontend AI session configuration objects. Each object contains the AI session type and the corresponding lifecycle callback methods. Currently, only the models included in AISessionType are supported. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct DemoPage {
- private webController: webview.WebviewController = new webview.WebviewController();
- sessions: Map<string, string> = new Map<string, string>();
-
- onCreateAISession = (id: string, params: string, result: OnAISessionCallback): boolean => {
- this.sessions.set(id, params); // Simulate creating an AI session.
- console.info(`[AISession]onCreateAISession params: ${params}`);
- // Notify the caller that the AI session is created successfully.
- result(AISessionResultType.SUCCESS, "AISession created");
- return true;
- }
-
- onExecuteAIAction = (id: string, params: string, result: OnAISessionCallback): void => {
- this.sessions.get(id); // Simulate retrieving the session and executing an action.
- console.info(`[AISession]onExecuteAIAction params: ${params}`);
- // Simulate streaming the AI execution result: multiple RUNNING calls indicate the task is in progress and return data chunks, and a final SUCCESS indicates task completion.
- result(AISessionResultType.RUNNING, "AISession chunk 1\n");
- result(AISessionResultType.RUNNING, "AISession chunk 2\n");
- result(AISessionResultType.SUCCESS, "AISession chunk end\n");
- }
-
- onDestroyAISession = (id: string): void => {
- this.sessions.delete(id); // Simulate destroying the session and releasing resources.
- }
-
- @State options: AISessionEvent = {
- aiSessionType: AISessionType.SUMMARIZER,
- onCreateAISession: this.onCreateAISession,
- onExecuteAIAction: this.onExecuteAIAction,
- onDestroyAISession: this.onDestroyAISession
- }
-
- build() {
- Column() {
- Web({ src: $rawfile('index.html'), controller: this.webController })
- .aiSessionOptions([this.options])
- }
- .width('100%')
- .height('100%')
- }
- }
HTML file to be loaded:
- <!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width,initial-scale=1.0">
- <title>Summarizer API Test</title>
- </head>
- <body style="max-width:600px;margin:20px auto;padding:0 16px;">
- <p id="status">checking...</p>
- <button id="initBtn" onclick="init()">Create Session</button>
- <br><br>
- <textarea id="input" rows="6" style="width:100%;font:inherit" placeholder="paste text to summarize"></textarea>
- <br><br>
- <button id="btn" onclick="run()" disabled>Summarize</button>
- <pre id="result"></pre>
- <script>
- let s;
- (async () => {
- const d = document.getElementById('status');
- if (!('Summarizer' in self)) { d.textContent = 'API not supported'; return; }
- const a = await Summarizer.availability();
- d.textContent = 'Summarizer: ' + a;
- if (a === 'unavailable') document.getElementById('initBtn').disabled = true;
- })();
- async function init() {
- const d = document.getElementById('status'), ib = document.getElementById('initBtn');
- ib.disabled = true;
- d.textContent = 'creating...';
- try {
- s = await Summarizer.create({
- type: 'tldr', length: 'medium', format: 'plain-text',
- monitor(m) { m.addEventListener('downloadprogress', e => { d.textContent = 'downloading ' + (e.loaded * 100 | 0) + '%' }); }
- });
- d.textContent = 'ready';
- document.getElementById('btn').disabled = false;
- } catch (e) { d.textContent = 'Error: ' + e.message; ib.disabled = false; }
- }
- async function run() {
- const t = document.getElementById('input').value.trim();
- if (!t || !s) return;
- const btn = document.getElementById('btn'), r = document.getElementById('result');
- btn.disabled = true;
- r.textContent = '...';
- try { r.textContent = await s.summarize(t); }
- catch (e) { r.textContent = 'Error: ' + e.message; }
- btn.disabled = false;
- }
- </script>
- </body>
- </html>
scrollbarLayoutPolicy(policy: ScrollbarLayoutPolicy)
Selects the layout mode of the vertical scrollbar within the Web component, used to adapt to the writing direction of different languages. The CONTENT mode is suitable for scenarios where the web page CSS direction attribute needs to be followed, while the SYSTEM mode is suitable for scenarios in multilingual apps where the system language direction needs to be followed, such as for right-to-left languages like Arabic and Hebrew.
System capability: SystemCapability.Web.Webview.Core
Model restriction: This API can be used only in the stage model.
Since: 26.0.0
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| policy | ScrollbarLayoutPolicy | Yes | Sets the layout mode of the vertical scrollbar in the Web component. Available values: CONTENT (follows the direction attribute of the web page CSS), SYSTEM (lays out based on the left-to-right or right-to-left writing direction of the system language. For right-to-left languages, the scrollbar is laid out on the left. This applies to all nested multi-level scrollbars in the web page). |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .width('100%')
- .height('100%')
- // Set to SYSTEM to indicate following the system language direction for layout. Set to CONTENT to indicate using the Web style layout.
- .scrollbarLayoutPolicy(ScrollbarLayoutPolicy.SYSTEM)
- }
- }
- }
keyboardAppearance(mode: WebKeyboardAppearanceMode)
Sets the keyboard appearance mode, which controls the appearance style of the keyboard that pops up for input boxes in the Web component, including immersive and non-immersive modes. If this method is not explicitly called, the system immersive mode is followed by default.
System capability: SystemCapability.Web.Webview.Core
Model restriction: This API can be used only in the stage model.
Since: 26.0.0
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| mode | WebKeyboardAppearanceMode | Yes | Keyboard appearance. When undefined or null is passed in, the system immersive mode is followed. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
- @State appearanceMode: WebKeyboardAppearanceMode = WebKeyboardAppearanceMode.DARK_IMMERSIVE;
-
- build() {
- Column() {
- Web({ src: $rawfile("index.html"), controller: this.controller })
- .keyboardAppearance(this.appearanceMode)
- }
- }
- }
HTML file to be loaded:
- <!--index.html-->
- <!DOCTYPE html>
- <html>
- <head>
- <title>Test web page</title>
- </head>
- <body>
- <input type="text" placeholder="Text">
- </body>
- </html>
enableFullscreenVideoOverlay(enabled: boolean)
Sets whether to enable the overlay fullscreen playback feature for the Web component. If this attribute is not explicitly called, this feature is disabled by default.
Since: 26.0.0
System capability: SystemCapability.Web.Webview.Core
Model restriction: This API can be used only in the stage model.
Device behavior: This API has no effect on the PCs/2-in-1 devices and works on other devices.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enabled | boolean | Yes | Sets whether to enable the overlay fullscreen playback feature for the Web component. true indicates enabling this feature. false indicates disabling this feature. When undefined or null is passed in, the value is false. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .enableFullscreenVideoOverlay(true)
- }
- }
- }
enableMediaNetworkProxy(enabled: boolean)
Sets whether to enable the media resource network request proxy feature for the Web component. If this attribute is not explicitly called, this feature is disabled by default.
Since: 26.0.0
System capability: SystemCapability.Web.Webview.Core
Model restriction: This API can be used only in the stage model.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enabled | boolean | Yes | Sets whether to enable the media resource network request proxy for the Web component. true indicates enabling this function. false indicates disabling it. |
Example
- // xxx.ets
- import { webview } from '@kit.ArkWeb';
-
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController();
-
- build() {
- Column() {
- Web({ src: 'www.example.com', controller: this.controller })
- .enableMediaNetworkProxy(true)
- }
- }
- }