1# Web 2 3The **Web** component can be used to display web pages. It can be used with the [@ohos.web.webview](js-apis-webview.md) module, which provides APIs for web control. 4 5> **NOTE** 6> 7> - This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. 8> - You can preview how this component looks on a real device, but not in DevEco Studio Previewer. 9 10## Required Permissions 11 12To use online resources, the application must have the **ohos.permission.INTERNET** permission. For details about how to apply for a permission, see [Declaring Permissions](../../security/AccessToken/declare-permissions.md). 13 14## Child Components 15 16Not supported 17 18## APIs 19 20Web(value: WebOptions) 21 22> **NOTE** 23> 24> Transition animation is not supported. 25> 26> **Web** components on the same page must be bound to different **WebviewController** instances. 27 28**System capability**: SystemCapability.Web.Webview.Core 29 30**Parameters** 31 32| Name | Type | Mandatory | Description | 33| ---------- | ---------------------------------------- | ---- | ---------------------------------------- | 34| value | [WebOptions](#weboptions) | Yes | Define web options.| 35 36**Example** 37 38Example of loading online web pages: 39 40 ```ts 41 // xxx.ets 42 import { webview } from '@kit.ArkWeb'; 43 44 @Entry 45 @Component 46 struct WebComponent { 47 controller: webview.WebviewController = new webview.WebviewController(); 48 49 build() { 50 Column() { 51 Web({ src: 'www.example.com', controller: this.controller }) 52 } 53 } 54 } 55 ``` 56 57Example of loading online web pages in incognito mode: 58 59 ```ts 60 // xxx.ets 61 import { webview } from '@kit.ArkWeb'; 62 63 @Entry 64 @Component 65 struct WebComponent { 66 controller: webview.WebviewController = new webview.WebviewController(); 67 68 build() { 69 Column() { 70 Web({ src: 'www.example.com', controller: this.controller, incognitoMode: true }) 71 } 72 } 73 } 74 ``` 75 76Example of rendering the **Web** component in synchronous mode: 77 78 ```ts 79 // xxx.ets 80 import { webview } from '@kit.ArkWeb'; 81 82 @Entry 83 @Component 84 struct WebComponent { 85 controller: webview.WebviewController = new webview.WebviewController(); 86 87 build() { 88 Column() { 89 Web({ src: 'www.example.com', controller: this.controller, renderMode: RenderMode.SYNC_RENDER }) 90 } 91 } 92 } 93 ``` 94 95Example of using the **Web** component to specify the shared rendering process. 96 97 ```ts 98 // xxx.ets 99 import { webview } from '@kit.ArkWeb'; 100 101 @Entry 102 @Component 103 struct WebComponent { 104 controller: webview.WebviewController = new webview.WebviewController(); 105 106 build() { 107 Column() { 108 Web({ src: 'www.example.com', controller: this.controller, sharedRenderProcessToken: "111" }) 109 Web({ src: 'www.w3.org', controller: this.controller, sharedRenderProcessToken: "111" }) 110 } 111 } 112 } 113 ``` 114 115Example of loading local web pages using **$rawfile()**: 116 117 118 ```ts 119 // xxx.ets 120 import { webview } from '@kit.ArkWeb'; 121 122 @Entry 123 @Component 124 struct WebComponent { 125 controller: webview.WebviewController = new webview.WebviewController(); 126 127 build() { 128 Column() { 129 // Load a local resource file through $rawfile. 130 Web({ src: $rawfile("index.html"), controller: this.controller }) 131 } 132 } 133 } 134 ``` 135 136Example of loading a link with the hash (#) route through the resource protocol in WebView: 137 ```ts 138 // xxx.ets 139 import { webview } from '@kit.ArkWeb'; 140 141 @Entry 142 @Component 143 struct WebComponent { 144 controller: webview.WebviewController = new webview.WebviewController(); 145 146 build() { 147 Column() { 148 // Load a local resource file through the resource protocol. 149 Web({ src: "resource://rawfile/index.html", controller: this.controller }) 150 } 151 } 152 } 153 ``` 154 155To load the local resource file in the sandbox path, you need to enable the [fileAccess](#fileaccess) permission for the file system in the application. 156 1571. Obtain the sandbox path through the constructed singleton object **GlobalContext**. 158 159 ```ts 160 // GlobalContext.ets 161 export class GlobalContext { 162 private constructor() {} 163 private static instance: GlobalContext; 164 private _objects = new Map<string, Object>(); 165 166 public static getContext(): GlobalContext { 167 if (!GlobalContext.instance) { 168 GlobalContext.instance = new GlobalContext(); 169 } 170 return GlobalContext.instance; 171 } 172 173 getObject(value: string): Object | undefined { 174 return this._objects.get(value); 175 } 176 177 setObject(key: string, objectClass: Object): void { 178 this._objects.set(key, objectClass); 179 } 180 } 181 ``` 182 183 ```ts 184 // xxx.ets 185 import { webview } from '@kit.ArkWeb'; 186 import { GlobalContext } from '../GlobalContext'; 187 188 let url = 'file://' + GlobalContext.getContext().getObject("filesDir") + '/index.html'; 189 190 @Entry 191 @Component 192 struct WebComponent { 193 controller: webview.WebviewController = new webview.WebviewController(); 194 195 build() { 196 Column() { 197 // Load the files in the sandbox. 198 Web({ src: url, controller: this.controller }) 199 .fileAccess(true) 200 } 201 } 202 } 203 ``` 204 2052. Modify the **EntryAbility.ets** file. 206 207 The following uses **filesDir** as an example to describe how to obtain the path of the sandbox. For details about how to obtain other paths, see [Obtaining Application File Paths](../../application-models/application-context-stage.md#obtaining-application-file-paths). 208 209 ```ts 210 // xxx.ets 211 import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 212 import { webview } from '@kit.ArkWeb'; 213 import { GlobalContext } from '../GlobalContext'; 214 215 export default class EntryAbility extends UIAbility { 216 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 217 // Data synchronization between the UIAbility component and UI can be implemented by binding filesDir to the GlobalContext object. 218 GlobalContext.getContext().setObject("filesDir", this.context.filesDir); 219 console.log("Sandbox path is " + GlobalContext.getContext().getObject("filesDir")); 220 } 221 } 222 ``` 223 224 HTML file to be loaded: 225 226 ```html 227 <!-- index.html --> 228 <!DOCTYPE html> 229 <html> 230 <body> 231 <p>Hello World</p> 232 </body> 233 </html> 234 ``` 235 236## WebOptions 237 238Define web options through [APIs](#apis). 239 240**System capability**: SystemCapability.Web.Webview.Core 241 242| Name | Type | Mandatory | Description | 243| ---------- | ---------------------------------------- | ---- | ---------------------------------------- | 244| src | string \| [Resource](../apis-arkui/arkui-ts/ts-types.md#resource) | Yes | Address of a web page resource. To access local resource files, use the **$rawfile** or **resource** protocol. To load a local resource file (in HTML or TXT format) in the sandbox outside of the application package, use **file://** to specify the path of the sandbox.<br>**src** cannot be dynamically changed through a state variable (for example, @State). To change the value, call [loadUrl()](js-apis-webview.md#loadurl).| 245| controller | [WebController](#webcontroller) \| [WebviewController<sup>9+</sup>](#webviewcontroller9) | Yes | Controller. This API is deprecated since API version 9. You are advised to use **WebviewController** instead.| 246| renderMode<sup>12+</sup> | [RenderMode](#rendermode12)| No | Rendering mode.<br>**RenderMode.ASYNC_RENDER** (default, cannot be dynamically adjusted): The **Web** component is rendered asynchronously.<br>**RenderMode.SYNC_RENDER**: The **Web** component is rendered synchronously within the current execution context.| 247| incognitoMode<sup>11+</sup> | boolean | No| Whether to enable incognito mode. The value **true** means to enable incognito mode, and **false** means the opposite.<br> Default value: **false**| 248| sharedRenderProcessToken<sup>12+</sup> | string | No| The token of the shared rendering process specified by the **Web** component. In multi-rendering process mode, the **Web** component with the same token preferentially attempts to reuse the rendering process bound to the token. The token is bound to the rendering process when the rendering process is initialized. When the rendering process is not associated with a **Web** component, its binding to the token is removed.<br> Default value: **""** | 249 250## WebviewController<sup>9+</sup> 251 252type WebviewController = WebviewController 253 254Provides methods for the web controller. 255 256**System capability**: SystemCapability.Web.Webview.Core 257 258| Type | Description | 259| ------ | ---------- | 260| [WebviewController](js-apis-webview.md#webviewcontroller) | Implements a **WebviewController** to control the behavior of the **Web** component. A **WebviewController** object can control only one **Web** component. Methods (except static methods) on the **WebviewController** can be called only after the **Web** component is bound to the **WebviewController**.| 261 262## Attributes 263 264Supported common attributes: [aspectRatio](../apis-arkui/arkui-ts/ts-universal-attributes-layout-constraints.md#aspectratio), [backdropBlur](../apis-arkui/arkui-ts/ts-universal-attributes-background.md#backdropblur), [backgroundColor](../apis-arkui/arkui-ts/ts-universal-attributes-background.md#backgroundcolor), [bindContentCover](../apis-arkui/arkui-ts/ts-universal-attributes-modal-transition.md#bindcontentcover), [bindContextMenu](../apis-arkui/arkui-ts/ts-universal-attributes-menu.md#bindcontextmenu8), [bindMenu](../apis-arkui/arkui-ts/ts-universal-attributes-menu.md#bindmenu), [bindSheet](../apis-arkui/arkui-ts/ts-universal-attributes-sheet-transition.md#bindsheet), [borderColor](../apis-arkui/arkui-ts/ts-universal-attributes-border.md#bordercolor), [borderRadius](../apis-arkui/arkui-ts/ts-universal-attributes-border.md#borderradius), [borderStyle](../apis-arkui/arkui-ts/ts-universal-attributes-border.md#borderstyle), [borderWidth](../apis-arkui/arkui-ts/ts-universal-attributes-border.md#borderwidth), [clip](../apis-arkui/arkui-ts/ts-universal-attributes-sharp-clipping.md#clip), [constraintSize](../apis-arkui/arkui-ts/ts-universal-attributes-size.md#constraintsize), [defaultFocus](../apis-arkui/arkui-ts/ts-universal-attributes-focus.md#defaultfocus9), [focusable](../apis-arkui/arkui-ts/ts-universal-attributes-focus.md#focusable), [tabIndex](../apis-arkui/arkui-ts/ts-universal-attributes-focus.md#tabindex9), [groupDefaultFocus](../apis-arkui/arkui-ts/ts-universal-attributes-focus.md#groupdefaultfocus9), [displayPriority](../apis-arkui/arkui-ts/ts-universal-attributes-layout-constraints.md#displaypriority), [enabled](../apis-arkui/arkui-ts/ts-universal-attributes-enable.md#enabled), [flexBasis](../apis-arkui/arkui-ts/ts-universal-attributes-flex-layout.md#flexbasis), [flexShrink](../apis-arkui/arkui-ts/ts-universal-attributes-flex-layout.md#flexshrink), [layoutWeight](../apis-arkui/arkui-ts/ts-universal-attributes-size.md#layoutweight), [id](../apis-arkui/arkui-ts/ts-universal-attributes-component-id.md), [gridOffset](../apis-arkui/arkui-ts/ts-universal-attributes-grid.md), [gridSpan](../apis-arkui/arkui-ts/ts-universal-attributes-grid.md), [useSizeType](../apis-arkui/arkui-ts/ts-universal-attributes-grid.md), [height](../apis-arkui/arkui-ts/ts-universal-attributes-size.md#height), [touchable](../apis-arkui/arkui-ts/ts-universal-attributes-click.md), [margin](../apis-arkui/arkui-ts/ts-universal-attributes-size.md#margin), [markAnchor](../apis-arkui/arkui-ts/ts-universal-attributes-location.md#markanchor), [offset](../apis-arkui/arkui-ts/ts-universal-attributes-location.md#offset), [width](../apis-arkui/arkui-ts/ts-universal-attributes-size.md#width), [zIndex](../apis-arkui/arkui-ts/ts-universal-attributes-z-order.md#zindex), [visibility](../apis-arkui/arkui-ts/ts-universal-attributes-visibility.md#visibility), [scale](../apis-arkui/arkui-ts/ts-universal-attributes-transformation.md#scale), [translate](../apis-arkui/arkui-ts/ts-universal-attributes-transformation.md#translate), [responseRegion](../apis-arkui/arkui-ts/ts-universal-attributes-touch-target.md#responseregion), [size](../apis-arkui/arkui-ts/ts-universal-attributes-size.md#size), [opacity](../apis-arkui/arkui-ts/ts-universal-attributes-opacity.md#opacity), [shadow](../apis-arkui/arkui-ts/ts-universal-attributes-image-effect.md#shadow), [sharedTransition](../apis-arkui/arkui-ts/ts-transition-animation-shared-elements.md), and [transition](../apis-arkui/arkui-ts/ts-transition-animation-component.md). 265 266### domStorageAccess 267 268domStorageAccess(domStorageAccess: boolean) 269 270Sets whether to enable the DOM Storage API. By default, this feature is disabled. 271 272**System capability**: SystemCapability.Web.Webview.Core 273 274**Parameters** 275 276| Name | Type | Mandatory | Description | 277| ---------------- | ------- | ---- | ------------------------------------ | 278| domStorageAccess | boolean | Yes | Whether to enable the DOM Storage API. The default value is **false**.| 279 280**Example** 281 282 ```ts 283 // xxx.ets 284 import { webview } from '@kit.ArkWeb'; 285 286 @Entry 287 @Component 288 struct WebComponent { 289 controller: webview.WebviewController = new webview.WebviewController(); 290 291 build() { 292 Column() { 293 Web({ src: 'www.example.com', controller: this.controller }) 294 .domStorageAccess(true) 295 } 296 } 297 } 298 ``` 299 300### fileAccess 301 302fileAccess(fileAccess: boolean) 303 304Sets 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)](../../quick-start/resource-categories-and-access.md). 305 306**fileAccess** is disabled by default since API version 12. When **fileAccess** is set to **false**, files in the read-only **/data/storage/el1/bundle/entry/resources/resfile** directory can still be accessed through the **file** protocol. 307 308**System capability**: SystemCapability.Web.Webview.Core 309 310**Parameters** 311 312| Name | Type | Mandatory | Description | 313| ---------- | ------- | ---- | ---------------------- | 314| fileAccess | boolean | Yes | Whether to enable access to the file system in the application.<br>Default value:<br>API version 11 and earlier: **true**<br> API version 12 and later: **false**| 315 316**Example** 317 318 ```ts 319 // xxx.ets 320 import { webview } from '@kit.ArkWeb'; 321 322 @Entry 323 @Component 324 struct WebComponent { 325 controller: webview.WebviewController = new webview.WebviewController(); 326 327 build() { 328 Column() { 329 Web({ src: 'www.example.com', controller: this.controller }) 330 .fileAccess(true) 331 } 332 } 333 } 334 ``` 335 336### imageAccess 337 338imageAccess(imageAccess: boolean) 339 340Sets whether to enable automatic image loading. By default, this feature is enabled. 341 342**System capability**: SystemCapability.Web.Webview.Core 343 344**Parameters** 345 346| Name | Type | Mandatory | Description | 347| ----------- | ------- | ---- | --------------- | 348| imageAccess | boolean | Yes | Whether to enable automatic image loading. Default value: **true**| 349 350**Example** 351 ```ts 352 // xxx.ets 353 import { webview } from '@kit.ArkWeb'; 354 355 @Entry 356 @Component 357 struct WebComponent { 358 controller: webview.WebviewController = new webview.WebviewController(); 359 360 build() { 361 Column() { 362 Web({ src: 'www.example.com', controller: this.controller }) 363 .imageAccess(true) 364 } 365 } 366 } 367 ``` 368 369### javaScriptProxy 370 371javaScriptProxy(javaScriptProxy: JavaScriptProxy) 372 373Registers a JavaScript object with the window. APIs of this object can then be invoked in the window. The parameters cannot be updated. This API can be used in synchronous or asynchronous mode, or in both modes. If the API can be used in both synchronous and asynchronous modes, it is called asynchronously by default. Only one object can be registered through this API. To register multiple objects, use [registerJavaScriptProxy<sup>9+</sup>](js-apis-webview.md#registerjavascriptproxy). 374 375**System capability**: SystemCapability.Web.Webview.Core 376 377**Parameters** 378 379| Name | Type | Mandatory | Description | 380| ---------- | ---------------------------------------- | ---- |---------------------------------------- | 381| javaScriptProxy | [JavaScriptProxy](#javascriptproxy12) | Yes | Object to be registered. Methods can be declared, but attributes cannot. | 382 383**Example** 384 385 ```ts 386 // xxx.ets 387 import { webview } from '@kit.ArkWeb'; 388 389 class TestObj { 390 constructor() { 391 } 392 393 test(data1: string, data2: string, data3: string): string { 394 console.log("data1:" + data1); 395 console.log("data2:" + data2); 396 console.log("data3:" + data3); 397 return "AceString"; 398 } 399 400 asyncTest(data: string): void { 401 console.log("async data:" + data); 402 } 403 404 toString(): void { 405 console.log('toString' + "interface instead."); 406 } 407 } 408 409 @Entry 410 @Component 411 struct WebComponent { 412 controller: webview.WebviewController = new webview.WebviewController(); 413 testObj = new TestObj(); 414 build() { 415 Column() { 416 Button('deleteJavaScriptRegister') 417 .onClick(() => { 418 try { 419 this.controller.deleteJavaScriptRegister("objName"); 420 } catch (error) { 421 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 422 } 423 }) 424 Web({ src: 'www.example.com', controller: this.controller }) 425 .javaScriptAccess(true) 426 .javaScriptProxy({ 427 object: this.testObj, 428 name: "objName", 429 methodList: ["test", "toString"], 430 asyncMethodList: ["asyncTest"], 431 controller: this.controller, 432 }) 433 } 434 } 435 } 436 ``` 437 438### javaScriptAccess 439 440javaScriptAccess(javaScriptAccess: boolean) 441 442Sets whether JavaScript scripts can be executed. By default, JavaScript scripts can be executed. 443 444**System capability**: SystemCapability.Web.Webview.Core 445 446**Parameters** 447 448| Name | Type | Mandatory | Description | 449| ---------------- | ------- | ---- | ------------------- | 450| javaScriptAccess | boolean | Yes | Whether JavaScript scripts can be executed. Default value: **true**| 451 452**Example** 453 454 ```ts 455 // xxx.ets 456 import { webview } from '@kit.ArkWeb'; 457 458 @Entry 459 @Component 460 struct WebComponent { 461 controller: webview.WebviewController = new webview.WebviewController(); 462 build() { 463 Column() { 464 Web({ src: 'www.example.com', controller: this.controller }) 465 .javaScriptAccess(true) 466 } 467 } 468 } 469 ``` 470 471### overScrollMode<sup>11+</sup> 472 473overScrollMode(mode: OverScrollMode) 474 475Sets the overscroll mode, which is disabled by default. When the overscroll mode is enabled and the boundary of the scrolling area is reached, the **Web** component plays a bounce effect animation. The internal page on the root page does not trigger rebound. 476 477**System capability**: SystemCapability.Web.Webview.Core 478 479**Parameters** 480 481| Name | Type | Mandatory | Description | 482| ---- | --------------------------------------- | ---- | ------------------ | 483| mode | [OverScrollMode](#overscrollmode11) | Yes | Whether to enable the overscroll mode. Default value: **OverScrollMode.NEVER**| 484 485**Example** 486 487 ```ts 488 // xxx.ets 489 import { webview } from '@kit.ArkWeb'; 490 491 @Entry 492 @Component 493 struct WebComponent { 494 controller: webview.WebviewController = new webview.WebviewController(); 495 @State mode: OverScrollMode = OverScrollMode.ALWAYS; 496 build() { 497 Column() { 498 Web({ src: 'www.example.com', controller: this.controller }) 499 .overScrollMode(this.mode) 500 } 501 } 502 } 503 ``` 504 505### mixedMode 506 507mixedMode(mixedMode: MixedMode) 508 509Sets whether to enable loading of HTTP and HTTPS hybrid content can be loaded. By default, this feature is disabled. 510 511**System capability**: SystemCapability.Web.Webview.Core 512 513**Parameters** 514 515| Name | Type | Mandatory | Description | 516| --------- | --------------------------- | ---- | --------- | 517| mixedMode | [MixedMode](#mixedmode)| Yes | Mixed content to load. Default value: **MixedMode.None**| 518 519**Example** 520 521 ```ts 522 // xxx.ets 523 import { webview } from '@kit.ArkWeb'; 524 525 @Entry 526 @Component 527 struct WebComponent { 528 controller: webview.WebviewController = new webview.WebviewController(); 529 @State mode: MixedMode = MixedMode.All; 530 build() { 531 Column() { 532 Web({ src: 'www.example.com', controller: this.controller }) 533 .mixedMode(this.mode) 534 } 535 } 536 } 537 ``` 538 539### onlineImageAccess 540 541onlineImageAccess(onlineImageAccess: boolean) 542 543Sets whether to enable access to online images through HTTP and HTTPS. By default, this feature is enabled. 544 545**System capability**: SystemCapability.Web.Webview.Core 546 547**Parameters** 548 549| Name | Type | Mandatory | Description | 550| ----------------- | ------- | ---- | ---------------- | 551| onlineImageAccess | boolean | Yes | Whether to enable access to online images through HTTP and HTTPS. Default value: **true**| 552 553**Example** 554 555 ```ts 556 // xxx.ets 557 import { webview } from '@kit.ArkWeb'; 558 559 @Entry 560 @Component 561 struct WebComponent { 562 controller: webview.WebviewController = new webview.WebviewController(); 563 564 build() { 565 Column() { 566 Web({ src: 'www.example.com', controller: this.controller }) 567 .onlineImageAccess(true) 568 } 569 } 570 } 571 ``` 572 573### zoomAccess 574 575zoomAccess(zoomAccess: boolean) 576 577Sets whether to enable zoom gestures. By default, this feature is enabled. 578 579**System capability**: SystemCapability.Web.Webview.Core 580 581**Parameters** 582 583| Name | Type | Mandatory | Description | 584| ---------- | ------- | ---- | ------------- | 585| zoomAccess | boolean | Yes | Whether to enable zoom gestures. Default value: **true**| 586 587**Example** 588 589 ```ts 590 // xxx.ets 591 import { webview } from '@kit.ArkWeb'; 592 593 @Entry 594 @Component 595 struct WebComponent { 596 controller: webview.WebviewController = new webview.WebviewController(); 597 598 build() { 599 Column() { 600 Web({ src: 'www.example.com', controller: this.controller }) 601 .zoomAccess(true) 602 } 603 } 604 } 605 ``` 606 607### overviewModeAccess 608 609overviewModeAccess(overviewModeAccess: boolean) 610 611Sets whether to load web pages by using the overview mode. By default, this feature is enabled. Currently, only mobile devices are supported. 612 613**System capability**: SystemCapability.Web.Webview.Core 614 615**Parameters** 616 617| Name | Type | Mandatory | Description | 618| ------------------ | ------- | ---- | --------------- | 619| overviewModeAccess | boolean | Yes | Whether to load web pages by using the overview mode. Default value: **true**| 620 621**Example** 622 623 ```ts 624 // xxx.ets 625 import { webview } from '@kit.ArkWeb'; 626 627 @Entry 628 @Component 629 struct WebComponent { 630 controller: webview.WebviewController = new webview.WebviewController(); 631 632 build() { 633 Column() { 634 Web({ src: 'www.example.com', controller: this.controller }) 635 .overviewModeAccess(true) 636 } 637 } 638 } 639 ``` 640 641### databaseAccess 642 643databaseAccess(databaseAccess: boolean) 644 645Sets whether to enable database access. By default, this feature is disabled. 646 647**System capability**: SystemCapability.Web.Webview.Core 648 649**Parameters** 650 651| Name | Type | Mandatory | Description | 652| -------------- | ------- | ---- | ----------------- | 653| databaseAccess | boolean | Yes | Whether to enable database access. The default value is **false**.| 654 655**Example** 656 657 ```ts 658 // xxx.ets 659 import { webview } from '@kit.ArkWeb'; 660 661 @Entry 662 @Component 663 struct WebComponent { 664 controller: webview.WebviewController = new webview.WebviewController(); 665 666 build() { 667 Column() { 668 Web({ src: 'www.example.com', controller: this.controller }) 669 .databaseAccess(true) 670 } 671 } 672 } 673 ``` 674 675### geolocationAccess 676 677geolocationAccess(geolocationAccess: boolean) 678 679Sets whether to enable geolocation access. By default, this feature is enabled. For details, see [Managing Location Permissions](../../web/web-geolocation-permission.md). 680 681**System capability**: SystemCapability.Web.Webview.Core 682 683**Parameters** 684 685| Name | Type | Mandatory | Description | 686| ----------------- | ------- | ---- | --------------- | 687| geolocationAccess | boolean | Yes | Whether to enable geolocation access. Default value: **true**| 688 689**Example** 690 691 ```ts 692 // xxx.ets 693 import { webview } from '@kit.ArkWeb'; 694 695 @Entry 696 @Component 697 struct WebComponent { 698 controller: webview.WebviewController = new webview.WebviewController(); 699 700 build() { 701 Column() { 702 Web({ src: 'www.example.com', controller: this.controller }) 703 .geolocationAccess(true) 704 } 705 } 706 } 707 ``` 708 709### mediaPlayGestureAccess<sup>9+</sup> 710 711mediaPlayGestureAccess(access: boolean) 712 713Sets whether video playback must be started by user gestures. This API is not applicable to videos that do not have an audio track or whose audio track is muted. 714 715**System capability**: SystemCapability.Web.Webview.Core 716 717**Parameters** 718 719| Name | Type | Mandatory | Description | 720| ------ | ------- | ---- | ------------------- | 721| access | boolean | Yes | Whether video playback must be started by user gestures. Default value: **true**| 722 723**Example** 724 725 ```ts 726 // xxx.ets 727 import { webview } from '@kit.ArkWeb'; 728 729 @Entry 730 @Component 731 struct WebComponent { 732 controller: webview.WebviewController = new webview.WebviewController(); 733 @State access: boolean = true; 734 735 build() { 736 Column() { 737 Web({ src: 'www.example.com', controller: this.controller }) 738 .mediaPlayGestureAccess(this.access) 739 } 740 } 741 } 742 ``` 743 744### multiWindowAccess<sup>9+</sup> 745 746multiWindowAccess(multiWindow: boolean) 747 748Sets whether to enable the multi-window permission. By default, this feature is disabled. 749Enabling the multi-window permission requires implementation of the **onWindowNew** event. For the sample code, see [onWindowNew](#onwindownew9). 750 751**System capability**: SystemCapability.Web.Webview.Core 752 753**Parameters** 754 755| Name | Type | Mandatory | Description | 756| ----------- | ------- | ---- | ------------ | 757| multiWindow | boolean | Yes | Whether to enable the multi-window permission. The default value is **false**.| 758 759**Example** 760 761 ```ts 762 // xxx.ets 763 import { webview } from '@kit.ArkWeb'; 764 765 @Entry 766 @Component 767 struct WebComponent { 768 controller: webview.WebviewController = new webview.WebviewController(); 769 770 build() { 771 Column() { 772 Web({ src: 'www.example.com', controller: this.controller }) 773 .multiWindowAccess(false) 774 } 775 } 776 } 777 ``` 778 779### horizontalScrollBarAccess<sup>9+</sup> 780 781horizontalScrollBarAccess(horizontalScrollBar: boolean) 782 783Sets whether to display the horizontal scrollbar, including the default system scrollbar and custom scrollbar. By default, the horizontal scrollbar is displayed. 784 785> **NOTE** 786> 787> - If an @State decorated variable is used to control the horizontal scrollbar visibility, **controller.refresh()** must be called for the settings to take effect. 788> - If the horizontal scrollbar visibility changes frequently through an @State decorated variable, it is recommended that the variable correspond to the **Web** component one by one. 789 790**System capability**: SystemCapability.Web.Webview.Core 791 792**Parameters** 793 794| Name | Type | Mandatory | Description | 795| ------------------- | ------- | ---- | ------------ | 796| horizontalScrollBar | boolean | Yes | Whether to display the horizontal scrollbar. Default value: **true**| 797 798**Example** 799 800 ```ts 801 // xxx.ets 802 import { webview } from '@kit.ArkWeb'; 803 import { BusinessError } from '@kit.BasicServicesKit'; 804 805 @Entry 806 @Component 807 struct WebComponent { 808 controller: webview.WebviewController = new webview.WebviewController(); 809 @State isShow: boolean = true; 810 @State btnMsg: string ="Hide the scrollbar"; 811 812 build() { 813 Column() { 814 // If an @State decorated variable is used to control the horizontal scrollbar visibility, controller.refresh() must be called for the settings to take effect. 815 Button('refresh') 816 .onClick(() => { 817 if(this.isShow){ 818 this.isShow = false; 819 this.btnMsg="Display the scrollbar"; 820 }else{ 821 this.isShow = true; 822 this.btnMsg="Hide the scrollbar"; 823 } 824 try { 825 this.controller.refresh(); 826 } catch (error) { 827 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 828 } 829 }).height("10%").width("40%") 830 Web({ src: $rawfile('index.html'), controller: this.controller }).height("90%") 831 .horizontalScrollBarAccess(this.isShow) 832 } 833 } 834 } 835 ``` 836 837 HTML file to be loaded: 838 ```html 839 <!--index.html--> 840 <!DOCTYPE html> 841 <html> 842 <head> 843 <meta name="viewport" id="viewport" content="width=device-width,initial-scale=1.0"> 844 <title>Demo</title> 845 <style> 846 body { 847 width:3000px; 848 height:6000px; 849 padding-right:170px; 850 padding-left:170px; 851 border:5px solid blueviolet 852 } 853 </style> 854 </head> 855 <body> 856 Scroll Test 857 </body> 858 </html> 859 ``` 860 861### verticalScrollBarAccess<sup>9+</sup> 862 863verticalScrollBarAccess(verticalScrollBar: boolean) 864 865Sets whether to display the vertical scrollbar, including the default system scrollbar and custom scrollbar. By default, the vertical scrollbar is displayed. 866 867> **NOTE** 868> 869> - If an @State decorated variable is used to control the vertical scrollbar visibility, **controller.refresh()** must be called for the settings to take effect. 870> - If the vertical scrollbar visibility changes frequently through an @State decorated variable, it is recommended that the variable correspond to the **Web** component one by one. 871 872**System capability**: SystemCapability.Web.Webview.Core 873 874**Parameters** 875 876| Name | Type | Mandatory | Description | 877| ----------------- | ------- | ---- | ------------ | 878| verticalScrollBar | boolean | Yes | Whether to display the vertical scrollbar. Default value: **true**| 879 880**Example** 881 882 ```ts 883 // xxx.ets 884 import { webview } from '@kit.ArkWeb'; 885 import { BusinessError } from '@kit.BasicServicesKit'; 886 887 @Entry 888 @Component 889 struct WebComponent { 890 controller: webview.WebviewController = new webview.WebviewController(); 891 @State isShow: boolean = true; 892 @State btnMsg: string ="Hide the scrollbar"; 893 894 build() { 895 Column() { 896 // If an @State decorated variable is used to control the horizontal scrollbar visibility, controller.refresh() must be called for the settings to take effect. 897 Button(this.btnMsg) 898 .onClick(() => { 899 if(this.isShow){ 900 this.isShow = false; 901 this.btnMsg="Display the scrollbar"; 902 }else{ 903 this.isShow = true; 904 this.btnMsg="Hide the scrollbar"; 905 } 906 try { 907 this.controller.refresh(); 908 } catch (error) { 909 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 910 } 911 }).height("10%").width("40%") 912 Web({ src: $rawfile('index.html'), controller: this.controller }).height("90%") 913 .verticalScrollBarAccess(this.isShow) 914 } 915 } 916 } 917 ``` 918 919 HTML file to be loaded: 920 ```html 921 <!--index.html--> 922 <!DOCTYPE html> 923 <html> 924 <head> 925 <meta name="viewport" id="viewport" content="width=device-width,initial-scale=1.0"> 926 <title>Demo</title> 927 <style> 928 body { 929 width:3000px; 930 height:6000px; 931 padding-right:170px; 932 padding-left:170px; 933 border:5px solid blueviolet 934 } 935 </style> 936 </head> 937 <body> 938 Scroll Test 939 </body> 940 </html> 941 ``` 942 943### password<sup>(deprecated)</sup> 944 945password(password: boolean) 946 947Sets whether the password should be saved. This API is a void API. 948 949> **NOTE** 950> 951> This API is deprecated since API version 10, and no new API is provided as a substitute. 952 953**System capability**: SystemCapability.Web.Webview.Core 954 955### cacheMode 956 957cacheMode(cacheMode: CacheMode) 958 959Sets the cache mode. 960 961**System capability**: SystemCapability.Web.Webview.Core 962 963**Parameters** 964 965| Name | Type | Mandatory | Description | 966| --------- | --------------------------- | ---- | --------- | 967| cacheMode | [CacheMode](#cachemode)| Yes | Cache mode to set. Default value: **CacheMode.Default**| 968 969**Example** 970 971 ```ts 972 // xxx.ets 973 import { webview } from '@kit.ArkWeb'; 974 975 @Entry 976 @Component 977 struct WebComponent { 978 controller: webview.WebviewController = new webview.WebviewController(); 979 @State mode: CacheMode = CacheMode.None; 980 981 build() { 982 Column() { 983 Web({ src: 'www.example.com', controller: this.controller }) 984 .cacheMode(this.mode) 985 } 986 } 987 } 988 ``` 989 990### copyOptions<sup>11+</sup> 991 992copyOptions(value: CopyOptions) 993 994Sets the pasteboard copy options. 995 996**System capability**: SystemCapability.Web.Webview.Core 997 998**Parameters** 999 1000| Name | Type | Mandatory | Description | 1001| --------- | --------------------------- | ---- | --------- | 1002| value | [CopyOptions](../apis-arkui/arkui-ts/ts-appendix-enums.md#copyoptions9) | Yes | Pasteboard copy options. Default value: **CopyOptions.LocalDevice**| 1003 1004**Example** 1005 1006 ```ts 1007import { webview } from '@kit.ArkWeb'; 1008 1009@Entry 1010@Component 1011struct WebComponent { 1012 controller: webview.WebviewController = new webview.WebviewController(); 1013 1014 build() { 1015 Column() { 1016 Web({ src: 'www.example.com', controller: this.controller }) 1017 .copyOptions(CopyOptions.None) 1018 } 1019 } 1020} 1021 ``` 1022 1023### textZoomAtio<sup>(deprecated)</sup> 1024 1025textZoomAtio(textZoomAtio: number) 1026 1027Sets the text zoom ratio of the page. The default value is **100**, which indicates 100%. 1028 1029**System capability**: SystemCapability.Web.Webview.Core 1030 1031This API is deprecated since API version 9. You are advised to use [textZoomRatio<sup>9+</sup>](#textzoomratio9) instead. 1032 1033**Parameters** 1034 1035| Name | Type | Mandatory | Description | 1036| ------------ | ------ | ---- | -------------------------------- | 1037| textZoomAtio | number | Yes | Text zoom ratio to set. The value is an integer. The value range is (0, +∞). Default value: **100**| 1038 1039**Example** 1040 1041 ```ts 1042 // xxx.ets 1043 @Entry 1044 @Component 1045 struct WebComponent { 1046 controller: WebController = new WebController() 1047 @State ratio: number = 150 1048 build() { 1049 Column() { 1050 Web({ src: 'www.example.com', controller: this.controller }) 1051 .textZoomAtio(this.ratio) 1052 } 1053 } 1054 } 1055 ``` 1056 1057### textZoomRatio<sup>9+</sup> 1058 1059textZoomRatio(textZoomRatio: number) 1060 1061Sets the text zoom ratio of the page. The default value is **100**, which indicates 100%. 1062 1063**System capability**: SystemCapability.Web.Webview.Core 1064 1065**Parameters** 1066 1067| Name | Type | Mandatory | Description | 1068| ------------- | ------ | ---- | -------------------------------- | 1069| textZoomRatio | number | Yes | Text zoom ratio to set. The value is an integer. The value range is (0, +∞). Default value: **100**| 1070 1071**Example** 1072 1073 ```ts 1074 // xxx.ets 1075 import { webview } from '@kit.ArkWeb'; 1076 1077 @Entry 1078 @Component 1079 struct WebComponent { 1080 controller: webview.WebviewController = new webview.WebviewController(); 1081 @State ratio: number = 150; 1082 1083 build() { 1084 Column() { 1085 Web({ src: 'www.example.com', controller: this.controller }) 1086 .textZoomRatio(this.ratio) 1087 } 1088 } 1089 } 1090 ``` 1091 1092### initialScale<sup>9+</sup> 1093 1094initialScale(percent: number) 1095 1096Sets the scale factor of the entire page. The default value is 100%. 1097 1098**System capability**: SystemCapability.Web.Webview.Core 1099 1100**Parameters** 1101 1102| Name | Type | Mandatory | Description | 1103| ------- | ------ | ---- | ----------------------------- | 1104| percent | number | Yes | Scale factor of the entire page. Default value: **100**| 1105 1106**Example** 1107 1108 ```ts 1109 // xxx.ets 1110 import { webview } from '@kit.ArkWeb'; 1111 1112 @Entry 1113 @Component 1114 struct WebComponent { 1115 controller: webview.WebviewController = new webview.WebviewController(); 1116 @State percent: number = 100; 1117 1118 build() { 1119 Column() { 1120 Web({ src: 'www.example.com', controller: this.controller }) 1121 .initialScale(this.percent) 1122 } 1123 } 1124 } 1125 ``` 1126 1127### userAgent<sup>(deprecated)</sup> 1128 1129userAgent(userAgent: string) 1130 1131Sets the user agent. 1132 1133> **NOTE** 1134> 1135> This API is supported since API version 8 and deprecated since API version 10. You are advised to use [setCustomUserAgent](js-apis-webview.md#setcustomuseragent10)<sup>10+</sup> instead. 1136 1137**System capability**: SystemCapability.Web.Webview.Core 1138 1139**Parameters** 1140 1141| Name | Type | Mandatory | Description | 1142| --------- | ------ | ---- | --------- | 1143| userAgent | string | Yes | User agent to set.| 1144 1145**Example** 1146 1147 ```ts 1148 // xxx.ets 1149 import { webview } from '@kit.ArkWeb'; 1150 1151 @Entry 1152 @Component 1153 struct WebComponent { 1154 controller: webview.WebviewController = new webview.WebviewController(); 1155 @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'; 1156 1157 build() { 1158 Column() { 1159 Web({ src: 'www.example.com', controller: this.controller }) 1160 .userAgent(this.userAgent) 1161 } 1162 } 1163 } 1164 ``` 1165 1166### blockNetwork<sup>9+</sup> 1167 1168blockNetwork(block: boolean) 1169 1170Sets whether to block online downloads. 1171 1172**System capability**: SystemCapability.Web.Webview.Core 1173 1174**Parameters** 1175 1176| Name | Type | Mandatory | Description | 1177| ----- | ------- | ---- | ------------------- | 1178| block | boolean | Yes | Sets whether to block online downloads. The default value is **false**.| 1179 1180**Example** 1181 1182 ```ts 1183 // xxx.ets 1184 import { webview } from '@kit.ArkWeb'; 1185 1186 @Entry 1187 @Component 1188 struct WebComponent { 1189 controller: webview.WebviewController = new webview.WebviewController(); 1190 @State block: boolean = true; 1191 1192 build() { 1193 Column() { 1194 Web({ src: 'www.example.com', controller: this.controller }) 1195 .blockNetwork(this.block) 1196 } 1197 } 1198 } 1199 ``` 1200 1201### defaultFixedFontSize<sup>9+</sup> 1202 1203defaultFixedFontSize(size: number) 1204 1205Sets the default fixed font size for the web page. 1206 1207**System capability**: SystemCapability.Web.Webview.Core 1208 1209**Parameters** 1210 1211| Name | Type | Mandatory | Description | 1212| ---- | ------ | ---- | ---------------------------------------- | 1213| size | number | Yes | Default fixed font size to set, in px. The value ranges from -2^31 to 2^31-1. In actual rendering, values greater than 72 are handled as 72, and values less than 1 are handled as 1. Default value: **13**| 1214 1215**Example** 1216 1217 ```ts 1218 // xxx.ets 1219 import { webview } from '@kit.ArkWeb'; 1220 1221 @Entry 1222 @Component 1223 struct WebComponent { 1224 controller: webview.WebviewController = new webview.WebviewController(); 1225 @State fontSize: number = 16; 1226 1227 build() { 1228 Column() { 1229 Web({ src: 'www.example.com', controller: this.controller }) 1230 .defaultFixedFontSize(this.fontSize) 1231 } 1232 } 1233 } 1234 ``` 1235 1236### defaultFontSize<sup>9+</sup> 1237 1238defaultFontSize(size: number) 1239 1240Sets the default font size for the web page. 1241 1242**System capability**: SystemCapability.Web.Webview.Core 1243 1244**Parameters** 1245 1246| Name | Type | Mandatory | Description | 1247| ---- | ------ | ---- | ---------------------------------------- | 1248| size | number | Yes | Default font size to set, in px. The value ranges from -2^31 to 2^31-1. In actual rendering, values greater than 72 are handled as 72, and values less than 1 are handled as 1. Default value: **16**| 1249 1250**Example** 1251 1252 ```ts 1253 // xxx.ets 1254 import { webview } from '@kit.ArkWeb'; 1255 1256 @Entry 1257 @Component 1258 struct WebComponent { 1259 controller: webview.WebviewController = new webview.WebviewController(); 1260 @State fontSize: number = 13; 1261 1262 build() { 1263 Column() { 1264 Web({ src: 'www.example.com', controller: this.controller }) 1265 .defaultFontSize(this.fontSize) 1266 } 1267 } 1268 } 1269 ``` 1270 1271### minFontSize<sup>9+</sup> 1272 1273minFontSize(size: number) 1274 1275Sets the minimum font size for the web page. 1276 1277**System capability**: SystemCapability.Web.Webview.Core 1278 1279**Parameters** 1280 1281| Name | Type | Mandatory | Description | 1282| ---- | ------ | ---- | ---------------------------------------- | 1283| size | number | Yes | Minimum font size to set, in px. The value ranges from -2^31 to 2^31-1. In actual rendering, values greater than 72 are handled as 72, and values less than 1 are handled as 1. Default value: **8**| 1284 1285**Example** 1286 1287 ```ts 1288 // xxx.ets 1289 import { webview } from '@kit.ArkWeb'; 1290 1291 @Entry 1292 @Component 1293 struct WebComponent { 1294 controller: webview.WebviewController = new webview.WebviewController(); 1295 @State fontSize: number = 13; 1296 1297 build() { 1298 Column() { 1299 Web({ src: 'www.example.com', controller: this.controller }) 1300 .minFontSize(this.fontSize) 1301 } 1302 } 1303 } 1304 ``` 1305 1306### minLogicalFontSize<sup>9+</sup> 1307 1308minLogicalFontSize(size: number) 1309 1310Sets the minimum logical font size for the web page. 1311 1312**System capability**: SystemCapability.Web.Webview.Core 1313 1314**Parameters** 1315 1316| Name | Type | Mandatory | Description | 1317| ---- | ------ | ---- | ---------------------------------------- | 1318| size | number | Yes | Minimum logical font size to set, in px. The value ranges from -2^31 to 2^31-1. In actual rendering, values greater than 72 are handled as 72, and values less than 1 are handled as 1. Default value: **8**| 1319 1320**Example** 1321 1322 ```ts 1323 // xxx.ets 1324 import { webview } from '@kit.ArkWeb'; 1325 1326 @Entry 1327 @Component 1328 struct WebComponent { 1329 controller: webview.WebviewController = new webview.WebviewController(); 1330 @State fontSize: number = 13; 1331 1332 build() { 1333 Column() { 1334 Web({ src: 'www.example.com', controller: this.controller }) 1335 .minLogicalFontSize(this.fontSize) 1336 } 1337 } 1338 } 1339 ``` 1340 1341### webFixedFont<sup>9+</sup> 1342 1343webFixedFont(family: string) 1344 1345Sets the fixed font family for the web page. 1346 1347**System capability**: SystemCapability.Web.Webview.Core 1348 1349**Parameters** 1350 1351| Name | Type | Mandatory | Description | 1352| ------ | ------ | ---- | ------------------- | 1353| family | string | Yes | Sets the fixed font family for the web page. Default value: **monospace**| 1354 1355**Example** 1356 1357 ```ts 1358 // xxx.ets 1359 import { webview } from '@kit.ArkWeb'; 1360 1361 @Entry 1362 @Component 1363 struct WebComponent { 1364 controller: webview.WebviewController = new webview.WebviewController(); 1365 @State family: string = "monospace"; 1366 1367 build() { 1368 Column() { 1369 Web({ src: 'www.example.com', controller: this.controller }) 1370 .webFixedFont(this.family) 1371 } 1372 } 1373 } 1374 ``` 1375 1376### webSansSerifFont<sup>9+</sup> 1377 1378webSansSerifFont(family: string) 1379 1380Sets the sans serif font family for the web page. 1381 1382**System capability**: SystemCapability.Web.Webview.Core 1383 1384**Parameters** 1385 1386| Name | Type | Mandatory | Description | 1387| ------ | ------ | ---- | ------------------------ | 1388| family | string | Yes | Sets the sans serif font family for the web page. Default value: **sans-serif**| 1389 1390**Example** 1391 1392 ```ts 1393 // xxx.ets 1394 import { webview } from '@kit.ArkWeb'; 1395 1396 @Entry 1397 @Component 1398 struct WebComponent { 1399 controller: webview.WebviewController = new webview.WebviewController(); 1400 @State family: string = "sans-serif"; 1401 1402 build() { 1403 Column() { 1404 Web({ src: 'www.example.com', controller: this.controller }) 1405 .webSansSerifFont(this.family) 1406 } 1407 } 1408 } 1409 ``` 1410 1411### webSerifFont<sup>9+</sup> 1412 1413webSerifFont(family: string) 1414 1415Sets the serif font family for the web page. 1416 1417**System capability**: SystemCapability.Web.Webview.Core 1418 1419**Parameters** 1420 1421| Name | Type | Mandatory | Description | 1422| ------ | ------ | ---- | ------------------- | 1423| family | string | Yes | Sets the serif font family for the web page. Default value: **serif**| 1424 1425**Example** 1426 1427 ```ts 1428 // xxx.ets 1429 import { webview } from '@kit.ArkWeb'; 1430 1431 @Entry 1432 @Component 1433 struct WebComponent { 1434 controller: webview.WebviewController = new webview.WebviewController(); 1435 @State family: string = "serif"; 1436 1437 build() { 1438 Column() { 1439 Web({ src: 'www.example.com', controller: this.controller }) 1440 .webSerifFont(this.family) 1441 } 1442 } 1443 } 1444 ``` 1445 1446### webStandardFont<sup>9+</sup> 1447 1448webStandardFont(family: string) 1449 1450Sets the standard font family for the web page. 1451 1452**System capability**: SystemCapability.Web.Webview.Core 1453 1454**Parameters** 1455 1456| Name | Type | Mandatory | Description | 1457| ------ | ------ | ---- | ---------------------- | 1458| family | string | Yes | Sets the standard font family for the web page. Default value: **sans-serif**| 1459 1460**Example** 1461 1462 ```ts 1463 // xxx.ets 1464 import { webview } from '@kit.ArkWeb'; 1465 1466 @Entry 1467 @Component 1468 struct WebComponent { 1469 controller: webview.WebviewController = new webview.WebviewController(); 1470 @State family: string = "sans-serif"; 1471 1472 build() { 1473 Column() { 1474 Web({ src: 'www.example.com', controller: this.controller }) 1475 .webStandardFont(this.family) 1476 } 1477 } 1478 } 1479 ``` 1480 1481### webFantasyFont<sup>9+</sup> 1482 1483webFantasyFont(family: string) 1484 1485Sets the fantasy font family for the web page. 1486 1487**System capability**: SystemCapability.Web.Webview.Core 1488 1489**Parameters** 1490 1491| Name | Type | Mandatory | Description | 1492| ------ | ------ | ---- | --------------------- | 1493| family | string | Yes | Sets the fantasy font family for the web page. Default value: **fantasy**| 1494 1495**Example** 1496 1497 ```ts 1498 // xxx.ets 1499 import { webview } from '@kit.ArkWeb'; 1500 @Entry 1501 @Component 1502 struct WebComponent { 1503 controller: webview.WebviewController = new webview.WebviewController(); 1504 @State family: string = "fantasy"; 1505 1506 build() { 1507 Column() { 1508 Web({ src: 'www.example.com', controller: this.controller }) 1509 .webFantasyFont(this.family) 1510 } 1511 } 1512 } 1513 ``` 1514 1515### webCursiveFont<sup>9+</sup> 1516 1517webCursiveFont(family: string) 1518 1519Sets the cursive font family for the web page. 1520 1521**System capability**: SystemCapability.Web.Webview.Core 1522 1523**Parameters** 1524 1525| Name | Type | Mandatory | Description | 1526| ------ | ------ | ---- | --------------------- | 1527| family | string | Yes | Sets the cursive font family for the web page. Default value: **cursive**| 1528 1529**Example** 1530 1531 ```ts 1532 // xxx.ets 1533 import { webview } from '@kit.ArkWeb'; 1534 1535 @Entry 1536 @Component 1537 struct WebComponent { 1538 controller: webview.WebviewController = new webview.WebviewController(); 1539 @State family: string = "cursive"; 1540 1541 build() { 1542 Column() { 1543 Web({ src: 'www.example.com', controller: this.controller }) 1544 .webCursiveFont(this.family) 1545 } 1546 } 1547 } 1548 ``` 1549 1550### darkMode<sup>9+</sup> 1551 1552darkMode(mode: WebDarkMode) 1553 1554Sets the web dark mode. By default, web dark mode is disabled. When it is enabled, the **Web** component enables the dark theme defined for web pages if the theme has been defined in **prefers-color-scheme** of a media query, and remains unchanged otherwise. To enable the forcible dark mode, use this API with [forceDarkAccess](#forcedarkaccess9). 1555 1556**System capability**: SystemCapability.Web.Webview.Core 1557 1558**Parameters** 1559 1560| Name | Type | Mandatory | Description | 1561| ---- | -------------------------------- | ---- | ---------------------- | 1562| mode | [WebDarkMode](#webdarkmode9) | Yes | Web dark mode to set. Default value: **WebDarkMode.Off**| 1563 1564**Example** 1565 1566 ```ts 1567 // xxx.ets 1568 import { webview } from '@kit.ArkWeb'; 1569 1570 @Entry 1571 @Component 1572 struct WebComponent { 1573 controller: webview.WebviewController = new webview.WebviewController(); 1574 @State mode: WebDarkMode = WebDarkMode.On; 1575 1576 build() { 1577 Column() { 1578 Web({ src: 'www.example.com', controller: this.controller }) 1579 .darkMode(this.mode) 1580 } 1581 } 1582 } 1583 ``` 1584 1585### forceDarkAccess<sup>9+</sup> 1586 1587forceDarkAccess(access: boolean) 1588 1589Sets whether to enable forcible dark mode for the web page. By default, this feature is turned off. This API is applicable only when dark mode is enabled in [darkMode](#darkmode9). 1590 1591**System capability**: SystemCapability.Web.Webview.Core 1592 1593**Parameters** 1594 1595| Name | Type | Mandatory | Description | 1596| ------ | ------- | ---- | --------------- | 1597| access | boolean | Yes | Sets whether to enable forcible dark mode for the web page. The default value is **false**.| 1598 1599**Example** 1600 1601 ```ts 1602 // xxx.ets 1603 import { webview } from '@kit.ArkWeb'; 1604 1605 @Entry 1606 @Component 1607 struct WebComponent { 1608 controller: webview.WebviewController = new webview.WebviewController(); 1609 @State mode: WebDarkMode = WebDarkMode.On; 1610 @State access: boolean = true; 1611 1612 build() { 1613 Column() { 1614 Web({ src: 'www.example.com', controller: this.controller }) 1615 .darkMode(this.mode) 1616 .forceDarkAccess(this.access) 1617 } 1618 } 1619 } 1620 ``` 1621 1622### tableData<sup>(deprecated)</sup> 1623 1624tableData(tableData: boolean) 1625 1626Sets whether form data should be saved. This API is a void API. 1627 1628> **NOTE** 1629> 1630> This API is deprecated since API version 10, and no new API is provided as a substitute. 1631 1632**System capability**: SystemCapability.Web.Webview.Core 1633 1634### wideViewModeAccess<sup>(deprecated)</sup> 1635 1636wideViewModeAccess(wideViewModeAccess: boolean) 1637 1638Sets whether to support the viewport attribute of the HTML **\<meta>** tag. This API is a void API. 1639 1640> **NOTE** 1641> 1642> This API is deprecated since API version 10, and no new API is provided as a substitute. 1643 1644**System capability**: SystemCapability.Web.Webview.Core 1645 1646### pinchSmooth<sup>9+</sup> 1647 1648pinchSmooth(isEnabled: boolean) 1649 1650Sets whether to enable smooth pinch mode for the web page. 1651 1652**System capability**: SystemCapability.Web.Webview.Core 1653 1654**Parameters** 1655 1656| Name | Type | Mandatory | Description | 1657| --------- | ------- | ---- | ------------- | 1658| isEnabled | boolean | Yes | Whether to enable smooth pinch mode for the web page. The default value is **false**.| 1659 1660**Example** 1661 1662 ```ts 1663 // xxx.ets 1664 import { webview } from '@kit.ArkWeb'; 1665 1666 @Entry 1667 @Component 1668 struct WebComponent { 1669 controller: webview.WebviewController = new webview.WebviewController(); 1670 1671 build() { 1672 Column() { 1673 Web({ src: 'www.example.com', controller: this.controller }) 1674 .pinchSmooth(true) 1675 } 1676 } 1677 } 1678 ``` 1679 1680### allowWindowOpenMethod<sup>10+</sup> 1681 1682allowWindowOpenMethod(flag: boolean) 1683 1684Sets whether to allow a new window to automatically open through JavaScript. 1685 1686When **flag** is set to **true**, a new window can automatically open through JavaScript. When **flag** is set to **false**, a new window can still automatically open through JavaScript for user behavior, but cannot for non-user behavior. The user behavior here refers to that a user requests to open a new window (**window.open**) within 5 seconds of operating the **Web** component. 1687 1688This API takes effect only when [javaScriptAccess](#javascriptaccess) is enabled. 1689 1690This API opens a new window when [multiWindowAccess](#multiwindowaccess9) is enabled and opens a local window when [multiWindowAccess](#multiwindowaccess9) is disabled. 1691 1692The default value of **flag** is subject to the settings of the **persist.web.allowWindowOpenMethod.enabled** system attribute. If this attribute is not set, the default value of **flag** is **false**. 1693 1694To check the settings of **persist.web.allowWindowOpenMethod.enabled**, 1695 1696run the **hdc shell param get persist.web.allowWindowOpenMethod.enabled** command. If the attribute is set to 0 or does not exist, 1697you can run the **hdc shell param set persist.web.allowWindowOpenMethod.enabled 1** command to enable it. 1698 1699**System capability**: SystemCapability.Web.Webview.Core 1700 1701**Parameters** 1702 1703| Name | Type | Mandatory | Description | 1704| ---- | ------- | ---- | ------------------------- | 1705| flag | boolean | Yes | Whether to allow a new window to automatically open through JavaScript. When the **persist.web.allowWindowOpenMethod.enabled** system attribute is set to **true**, the default value of **flag** is **true**; otherwise, the default value of **flag** is **false**.| 1706 1707**Example** 1708 1709 ```ts 1710 // xxx.ets 1711 import { webview } from '@kit.ArkWeb'; 1712 1713 // There are two Web components on the same page. When the WebComponent object opens a new window, the NewWebViewComp object is displayed. 1714 @CustomDialog 1715 struct NewWebViewComp { 1716 controller?: CustomDialogController; 1717 webviewController1: webview.WebviewController = new webview.WebviewController(); 1718 1719 build() { 1720 Column() { 1721 Web({ src: "", controller: this.webviewController1 }) 1722 .javaScriptAccess(true) 1723 .multiWindowAccess(false) 1724 .onWindowExit(() => { 1725 console.info("NewWebViewComp onWindowExit"); 1726 if (this.controller) { 1727 this.controller.close(); 1728 } 1729 }) 1730 } 1731 } 1732 } 1733 1734 @Entry 1735 @Component 1736 struct WebComponent { 1737 controller: webview.WebviewController = new webview.WebviewController(); 1738 dialogController: CustomDialogController | null = null; 1739 1740 build() { 1741 Column() { 1742 Web({ src: 'www.example.com', controller: this.controller }) 1743 .javaScriptAccess(true) 1744 // MultiWindowAccess needs to be enabled. 1745 .multiWindowAccess(true) 1746 .allowWindowOpenMethod(true) 1747 .onWindowNew((event) => { 1748 if (this.dialogController) { 1749 this.dialogController.close(); 1750 } 1751 let popController: webview.WebviewController = new webview.WebviewController(); 1752 this.dialogController = new CustomDialogController({ 1753 builder: NewWebViewComp({ webviewController1: popController }) 1754 }) 1755 this.dialogController.open(); 1756 // Return the WebviewController object corresponding to the new window to the Web kernel. 1757 // If the event.handler.setWebController API is not called, the render process will be blocked. 1758 // If no new window is created, set the value of event.handler.setWebController to null to notify the Web component that no new window is created. 1759 event.handler.setWebController(popController); 1760 }) 1761 } 1762 } 1763 } 1764 ``` 1765 1766### mediaOptions<sup>10+</sup> 1767 1768mediaOptions(options: WebMediaOptions) 1769 1770Sets 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. 1771 1772> **NOTE** 1773> 1774> - Audios in the same **Web** instance are considered as the same audio. 1775> - The media playback policy controls videos with an audio track. 1776> - After the parameter settings are updated, the playback must be started again for the settings to take effect. 1777> - It is recommended that you set the same **audioExclusive** value for all **Web** components. 1778> - Audio and video interruption takes effect within an app and between apps, and playback resumption takes effect only between apps. 1779 1780**System capability**: SystemCapability.Web.Webview.Core 1781 1782**Parameters** 1783 1784| Name | Type | Mandatory | Description | 1785| ------- | ------------------------------------- | ---- | ---------------------------------------- | 1786| options | [WebMediaOptions](#webmediaoptions10) | Yes | Web-based media playback policy. The default value of **resumeInterval** is **0**, indicating that the playback is not automatically resumed. Default value: **{resumeInterval: 0, audioExclusive: true}**| 1787 1788**Example** 1789 1790 ```ts 1791 // xxx.ets 1792 import { webview } from '@kit.ArkWeb'; 1793 1794 @Entry 1795 @Component 1796 struct WebComponent { 1797 controller: webview.WebviewController = new webview.WebviewController(); 1798 @State options: WebMediaOptions = {resumeInterval: 10, audioExclusive: true}; 1799 1800 build() { 1801 Column() { 1802 Web({ src: 'www.example.com', controller: this.controller }) 1803 .mediaOptions(this.options) 1804 } 1805 } 1806 } 1807 ``` 1808 1809### javaScriptOnDocumentStart<sup>11+</sup> 1810 1811javaScriptOnDocumentStart(scripts: Array\<ScriptItem>) 1812 1813Injects 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**. 1814 1815> **NOTE** 1816> 1817> - The script runs before any JavaScript code of the page, when the DOM tree may not have been loaded or rendered. 1818> - The script is executed in the lexicographic order, not the array order. 1819> - You are not advised to use this API together with [runJavaScriptOnDocumentStart](#runjavascriptondocumentstart15). 1820 1821**System capability**: SystemCapability.Web.Webview.Core 1822 1823**Parameters** 1824 1825| Name | Type | Mandatory | Description | 1826| ------- | ----------------------------------- | ---- | ------------------ | 1827| scripts | Array\<[ScriptItem](#scriptitem11)> | Yes | Script item array to be injected.| 1828 1829**Example in the .ets file** 1830 1831 ```ts 1832 // xxx.ets 1833 import { webview } from '@kit.ArkWeb'; 1834 1835 @Entry 1836 @Component 1837 struct Index { 1838 controller: webview.WebviewController = new webview.WebviewController(); 1839 private localStorage: string = 1840 "if (typeof(Storage) !== 'undefined') {" + 1841 " localStorage.setItem('color', 'Red');" + 1842 "}"; 1843 @State scripts: Array<ScriptItem> = [ 1844 { script: this.localStorage, scriptRules: ["*"] } 1845 ]; 1846 1847 build() { 1848 Column({ space: 20 }) { 1849 Web({ src: $rawfile('index.html'), controller: this.controller }) 1850 .javaScriptAccess(true) 1851 .domStorageAccess(true) 1852 .backgroundColor(Color.Grey) 1853 .javaScriptOnDocumentStart(this.scripts) 1854 .width('100%') 1855 .height('100%') 1856 } 1857 } 1858 } 1859 ``` 1860**Example in the HTML file** 1861 1862```html 1863<!-- index.html --> 1864<!DOCTYPE html> 1865<html> 1866 <head> 1867 <meta charset="utf-8"> 1868 </head> 1869 <body style="font-size: 30px;" onload='bodyOnLoadLocalStorage()'> 1870 Hello world! 1871 <div id="result"></div> 1872 </body> 1873 <script type="text/javascript"> 1874 function bodyOnLoadLocalStorage() { 1875 if (typeof(Storage) !== 'undefined') { 1876 document.getElementById('result').innerHTML = localStorage.getItem('color'); 1877 } else { 1878 document.getElementById('result').innerHTML = 'Your browser does not support localStorage.'; 1879 } 1880 } 1881 </script> 1882</html> 1883``` 1884 1885### javaScriptOnDocumentEnd<sup>11+</sup> 1886 1887javaScriptOnDocumentEnd(scripts: Array\<ScriptItem>) 1888 1889Injects 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**. 1890 1891> **NOTE** 1892> 1893> - The script runs before any JavaScript code of the page, when the DOM tree has been loaded and rendered. 1894> - The script is executed in the lexicographic order, not the array order. 1895> - You are not advised to use this API together with [runJavaScriptOnDocumentEnd](#runjavascriptondocumentend15). 1896 1897**System capability**: SystemCapability.Web.Webview.Core 1898 1899**Parameters** 1900 1901| Name | Type | Mandatory | Description | 1902| ------- | ----------------------------------- | ---- | ------------------ | 1903| scripts | Array\<[ScriptItem](#scriptitem11)> | Yes | Script item array to be injected.| 1904 1905**Example** 1906 1907 ```ts 1908// xxx.ets 1909import { webview } from '@kit.ArkWeb'; 1910 1911@Entry 1912@Component 1913struct Index { 1914 controller: webview.WebviewController = new webview.WebviewController(); 1915 private jsStr: string = 1916 "window.document.getElementById(\"result\").innerHTML = 'this is msg from javaScriptOnDocumentEnd'"; 1917 @State scripts: Array<ScriptItem> = [ 1918 { script: this.jsStr, scriptRules: ["*"] } 1919 ]; 1920 1921 build() { 1922 Column({ space: 20 }) { 1923 Web({ src: $rawfile('index.html'), controller: this.controller }) 1924 .javaScriptAccess(true) 1925 .domStorageAccess(true) 1926 .backgroundColor(Color.Grey) 1927 .javaScriptOnDocumentEnd(this.scripts) 1928 .width('100%') 1929 .height('100%') 1930 } 1931 } 1932} 1933 ``` 1934 1935```html 1936<!DOCTYPE html> 1937<html> 1938<head> 1939 <meta charset="utf-8"> 1940</head> 1941<body style="font-size: 30px;"> 1942Hello world! 1943<div id="result">test msg</div> 1944</body> 1945</html> 1946``` 1947 1948### runJavaScriptOnDocumentStart<sup>15+</sup> 1949 1950runJavaScriptOnDocumentStart(scripts: Array\<ScriptItem>) 1951 1952Injects 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**. 1953 1954> **NOTE** 1955> 1956> - The script runs before any JavaScript code of the page, when the DOM tree may not have been loaded or rendered. 1957> - This script is executed in the array order. 1958> - You are advised not to use this API together with [javaScriptOnDocumentStart](#javascriptondocumentstart11). 1959 1960**System capability**: SystemCapability.Web.Webview.Core 1961 1962**Parameters** 1963 1964| Name | Type | Mandatory | Description | 1965| ------- | ----------------------------------- | ---- | ------------------ | 1966| scripts | Array\<[ScriptItem](#scriptitem11)> | Yes | Script item array to be injected.| 1967 1968**Example in the .ets file** 1969 1970 ```ts 1971 // xxx.ets 1972 import { webview } from '@kit.ArkWeb'; 1973 1974 @Entry 1975 @Component 1976 struct Index { 1977 controller: webview.WebviewController = new webview.WebviewController(); 1978 private localStorage: string = 1979 "if (typeof(Storage) !== 'undefined') {" + 1980 " localStorage.setItem('color', 'Red');" + 1981 "}"; 1982 @State scripts: Array<ScriptItem> = [ 1983 { script: this.localStorage, scriptRules: ["*"] } 1984 ]; 1985 1986 build() { 1987 Column({ space: 20 }) { 1988 Web({ src: $rawfile('index.html'), controller: this.controller }) 1989 .javaScriptAccess(true) 1990 .domStorageAccess(true) 1991 .backgroundColor(Color.Grey) 1992 .runJavaScriptOnDocumentStart(this.scripts) 1993 .width('100%') 1994 .height('100%') 1995 } 1996 } 1997 } 1998 ``` 1999**Example in the HTML file** 2000 2001```html 2002<!-- index.html --> 2003<!DOCTYPE html> 2004<html> 2005 <head> 2006 <meta charset="utf-8"> 2007 </head> 2008 <body style="font-size: 30px;" onload='bodyOnLoadLocalStorage()'> 2009 Hello world! 2010 <div id="result"></div> 2011 </body> 2012 <script type="text/javascript"> 2013 function bodyOnLoadLocalStorage() { 2014 if (typeof(Storage) !== 'undefined') { 2015 document.getElementById('result').innerHTML = localStorage.getItem('color'); 2016 } else { 2017 document.getElementById('result').innerHTML = 'Your browser does not support localStorage.'; 2018 } 2019 } 2020 </script> 2021</html> 2022``` 2023 2024### runJavaScriptOnDocumentEnd<sup>15+</sup> 2025 2026runJavaScriptOnDocumentEnd(scripts: Array\<ScriptItem>) 2027 2028Injects 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**. 2029 2030> **NOTE** 2031> 2032> - The script runs before any JavaScript code of the page, when the DOM tree has been loaded and rendered. 2033> - This script is executed in the array order. 2034> - You are advised not to use this API together with [javaScriptOnDocumentEnd](#javascriptondocumentend11). 2035 2036**System capability**: SystemCapability.Web.Webview.Core 2037 2038**Parameters** 2039 2040| Name | Type | Mandatory | Description | 2041| ------- | ----------------------------------- | ---- | ------------------ | 2042| scripts | Array\<[ScriptItem](#scriptitem11)> | Yes | Script item array to be injected.| 2043 2044**Example** 2045 2046 ```ts 2047// xxx.ets 2048import { webview } from '@kit.ArkWeb'; 2049 2050@Entry 2051@Component 2052struct Index { 2053 controller: webview.WebviewController = new webview.WebviewController(); 2054 private jsStr: string = 2055 "window.document.getElementById(\"result\").innerHTML = 'this is msg from runJavaScriptOnDocumentEnd'"; 2056 @State scripts: Array<ScriptItem> = [ 2057 { script: this.jsStr, scriptRules: ["*"] } 2058 ]; 2059 2060 build() { 2061 Column({ space: 20 }) { 2062 Web({ src: $rawfile('index.html'), controller: this.controller }) 2063 .javaScriptAccess(true) 2064 .domStorageAccess(true) 2065 .backgroundColor(Color.Grey) 2066 .runJavaScriptOnDocumentEnd(this.scripts) 2067 .width('100%') 2068 .height('100%') 2069 } 2070 } 2071} 2072 ``` 2073 2074```html 2075<!DOCTYPE html> 2076<html> 2077<head> 2078 <meta charset="utf-8"> 2079</head> 2080<body style="font-size: 30px;"> 2081Hello world! 2082<div id="result">test msg</div> 2083</body> 2084</html> 2085``` 2086 2087### runJavaScriptOnHeadEnd<sup>15+</sup> 2088 2089runJavaScriptOnHeadEnd(scripts: Array\<ScriptItem>) 2090 2091Injects 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**. 2092 2093> **NOTE** 2094> 2095> - This script is executed in the array order. 2096 2097**System capability**: SystemCapability.Web.Webview.Core 2098 2099**Parameters** 2100 2101| Name | Type | Mandatory | Description | 2102| ------- | ----------------------------------- | ---- | ------------------ | 2103| scripts | Array\<[ScriptItem](#scriptitem11)> | Yes | Script item array to be injected.| 2104 2105**Example** 2106 2107 ```ts 2108// xxx.ets 2109import { webview } from '@kit.ArkWeb'; 2110 2111@Entry 2112@Component 2113struct Index { 2114 controller: webview.WebviewController = new webview.WebviewController(); 2115 private jsStr: string = 2116 "window.document.getElementById(\"result\").innerHTML = 'this is msg from runJavaScriptOnHeadEnd'"; 2117 @State scripts: Array<ScriptItem> = [ 2118 { script: this.jsStr, scriptRules: ["*"] } 2119 ]; 2120 2121 build() { 2122 Column({ space: 20 }) { 2123 Web({ src: $rawfile('index.html'), controller: this.controller }) 2124 .javaScriptAccess(true) 2125 .domStorageAccess(true) 2126 .backgroundColor(Color.Grey) 2127 .runJavaScriptOnHeadEnd(this.scripts) 2128 .width('100%') 2129 .height('100%') 2130 } 2131 } 2132} 2133 ``` 2134 2135```html 2136<!DOCTYPE html> 2137<html> 2138<head> 2139 <meta charset="utf-8"> 2140</head> 2141<body style="font-size: 30px;"> 2142Hello world! 2143<div id="result">test msg</div> 2144</body> 2145</html> 2146``` 2147 2148### layoutMode<sup>11+</sup> 2149 2150layoutMode(mode: WebLayoutMode) 2151 2152Sets the web layout mode. 2153 2154> **NOTE** 2155> 2156> Currently, only two web layout modes are supported: **WebLayoutMode.NONE** and **WebLayoutMode.FIT_CONTENT**. 2157> 2158> The following restrictions apply with the usage of **WebLayoutMode.FIT_CONTENT**: 2159> - If the **Web** component is wider or longer than 7680 px, specify the **RenderMode.SYNC_RENDER** mode when creating the **Web** component; otherwise, the screen may be blank. 2160> - After the **Web** component is created, dynamic switching of the **layoutMode** is not supported. 2161> - The width and height of a **Web** component cannot exceed 500,000 px when the **RenderMode.SYNC_RENDER** mode is specified, and cannot exceed 7680 px when the **RenderMode.ASYNC_RENDER** mode is specified. 2162> - Frequent changes to the page width and height will trigger a re-layout of the **Web** component, which can affect the user experience. 2163> - Waterfall web pages are not supported (drop down to the bottom to load more). 2164> - Only height adaptation is supported. Width adaptation is not supported. 2165> - Because the height is adaptive to the web page height, the component height cannot be changed by modifying the component height attribute. 2166 2167**System capability**: SystemCapability.Web.Webview.Core 2168 2169**Parameters** 2170 2171| Name | Type | Mandatory | Description | 2172| ---- | ------------------------------------- | ---- | --------------------- | 2173| mode | [WebLayoutMode](#weblayoutmode11) | Yes | Web layout mode. Default value: **WebLayoutMode.NONE**.| 2174 2175**Example** 2176 2177 1. After specifying the **layoutMode** as **WebLayoutMode.FIT_CONTENT**, you need to explicitly specify the **renderMode** to** RenderMode.SYNC_RENDER**. Otherwise, rendering errors may occur when the viewport height exceeds 7680px in the default **RenderMode.ASYNC_RENDER**. 2178 ```ts 2179 // xxx.ets 2180 import { webview } from '@kit.ArkWeb'; 2181 2182 @Entry 2183 @Component 2184 struct WebComponent { 2185 controller: webview.WebviewController = new webview.WebviewController(); 2186 mode: WebLayoutMode = WebLayoutMode.FIT_CONTENT; 2187 2188 build() { 2189 Column() { 2190 Web({ src: 'www.example.com', controller: this.controller, renderMode: RenderMode.SYNC_RENDER }) 2191 .layoutMode(this.mode) 2192 } 2193 } 2194 } 2195 ``` 2196 2197 2. After specifying the layoutMode as **WebLayoutMode.FIT_CONTENT**, you are advised to specify **overScrollMode** as **OverScrollMode.NEVER**. Otherwise, when the web page scrolls to the edge in the nested scrolling scenario, the rebounding effect is triggered first, which affects user experience. 2198 ```ts 2199 // xxx.ets 2200 import { webview } from '@kit.ArkWeb'; 2201 2202 @Entry 2203 @Component 2204 struct WebComponent { 2205 controller: webview.WebviewController = new webview.WebviewController(); 2206 layoutMode: WebLayoutMode = WebLayoutMode.FIT_CONTENT; 2207 @State overScrollMode: OverScrollMode = OverScrollMode.NEVER; 2208 2209 build() { 2210 Column() { 2211 Web({ src: 'www.example.com', controller: this.controller, renderMode: RenderMode.SYNC_RENDER }) 2212 .layoutMode(this.layoutMode) 2213 .overScrollMode(this.overScrollMode) 2214 } 2215 } 2216 } 2217 ``` 2218 2219### nestedScroll<sup>11+</sup> 2220 2221nestedScroll(value: NestedScrollOptions | NestedScrollOptionsExt) 2222 2223Sets nested scrolling options. 2224 2225> **NOTE** 2226> 2227> - You can set the up, down, left, and right directions, or set the forward and backward nested scrolling modes to implement scrolling linkage with the parent component. 2228> - 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 [NestedScrollMode.SELF_FIRST](../apis-arkui/arkui-ts/ts-appendix-enums.md#nestedscrollmode10). 2229> - 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**. 2230> - The following containers support nested scrolling: [Grid](../apis-arkui/arkui-ts/ts-container-grid.md), [List](../apis-arkui/arkui-ts/ts-container-list.md), [Scroll](../apis-arkui/arkui-ts/ts-container-scroll.md), [Swiper](../apis-arkui/arkui-ts/ts-container-swiper.md), [Tabs](../apis-arkui/arkui-ts/ts-container-tabs.md), [WaterFlow](../apis-arkui/arkui-ts/ts-container-waterflow.md), [Refresh](../apis-arkui/arkui-ts/ts-container-refresh.md) and [bindSheet](../apis-arkui/arkui-ts/ts-universal-attributes-sheet-transition.md#bindsheet). 2231> - Input sources that support nested scrolling: gestures, mouse device, and touchpad. 2232> - In nested scrolling scenarios, since the **Web** component's over-scrolling to the edge will trigger the over-scroll bounce effect first, it is recommended that you set **overScrollMode** to **OverScrollMode.NEVER** to avoid undermining the user experience. 2233 2234**System capability**: SystemCapability.Web.Webview.Core 2235 2236**Parameters** 2237 2238| Name | Type | Mandatory | Description | 2239| ----- | ---------------------------------------- | ---- | ---------------- | 2240| value | [NestedScrollOptions](../apis-arkui/arkui-ts/ts-container-scrollable-common.md#nestedscrolloptions10)\| [NestedScrollOptionsExt](#nestedscrolloptionsext14) <sup>14+</sup>| Yes | Nested scrolling options.| 2241 2242**Example** 2243 2244 ```ts 2245 // xxx.ets 2246 import { webview } from '@kit.ArkWeb'; 2247 @Entry 2248 @Component 2249 struct WebComponent { 2250 controller: webview.WebviewController = new webview.WebviewController(); 2251 2252 build() { 2253 Column() { 2254 Web({ src: 'www.example.com', controller: this.controller }) 2255 .nestedScroll({ 2256 scrollForward: NestedScrollMode.SELF_FIRST, 2257 scrollBackward: NestedScrollMode.SELF_FIRST, 2258 }) 2259 } 2260 } 2261 } 2262 ``` 2263 ```ts 2264 // xxx.ets 2265 import { webview } from '@kit.ArkWeb'; 2266 @Entry 2267 @Component 2268 struct WebComponent { 2269 controller: webview.WebviewController = new webview.WebviewController() 2270 build() { 2271 Scroll(){ 2272 Column() { 2273 Text ("Nested Web") 2274 .height("25%") 2275 .width("100%") 2276 .fontSize(30) 2277 .backgroundColor(Color.Yellow) 2278 Web({ src: $rawfile('index.html'), 2279 controller: this.controller }) 2280 .nestedScroll({ 2281 scrollUp: NestedScrollMode.SELF_FIRST, 2282 scrollDown: NestedScrollMode.PARENT_FIRST, 2283 scrollLeft: NestedScrollMode.SELF_FIRST, 2284 scrollRight: NestedScrollMode.SELF_FIRST, 2285 }) 2286 } 2287 } 2288 } 2289 } 2290 ``` 2291 HTML file to be loaded: 2292 ```html 2293 <!-- index.html --> 2294 <!DOCTYPE html> 2295 <html> 2296 <head> 2297 <style> 2298 .blue { 2299 background-color: lightblue; 2300 } 2301 .green { 2302 background-color: lightgreen; 2303 } 2304 .blue, .green { 2305 width: 100%; 2306 font-size:70px; 2307 height:1000px; 2308 } 2309 </style> 2310 </head> 2311 <body> 2312 <div class="blue" align="center" >Scroll 1</div> 2313 <div class="green" align="center">Scroll 2</div> 2314 <div class="blue" align="center" >Scroll 3</div> 2315 <div class="green" align="center">Scroll 4</div> 2316 <div class="blue" align="center" >Scroll 5</div> 2317 <div class="green" align="center">Scroll 6</div> 2318 <div class="blue" align="center" >Scroll 7</div> 2319 </body> 2320 </html> 2321 ``` 2322 2323### enableNativeEmbedMode<sup>11+</sup> 2324 2325enableNativeEmbedMode(mode: boolean) 2326 2327Specifies whether to enable the same-layer rendering feature. By default, this feature is disabled. 2328 2329**System capability**: SystemCapability.Web.Webview.Core 2330 2331**Parameters** 2332 2333| Name | Type | Mandatory | Description | 2334| ----- | ---------------------------------------- | ---- | ---------------- | 2335| mode | boolean | Yes | Whether to enable the same-layer rendering feature. The default value is **false**.| 2336 2337**Example** 2338 2339 ```ts 2340 // xxx.ets 2341 import { webview } from '@kit.ArkWeb'; 2342 @Entry 2343 @Component 2344 struct WebComponent { 2345 controller: webview.WebviewController = new webview.WebviewController(); 2346 2347 build() { 2348 Column() { 2349 Web({ src: 'www.example.com', controller: this.controller }) 2350 .enableNativeEmbedMode(true) 2351 } 2352 } 2353 } 2354 ``` 2355### forceDisplayScrollBar<sup>14+</sup> 2356 2357forceDisplayScrollBar(enabled: boolean) 2358 2359 2360Sets whether the scroll bar is always visible. By default, it is not always visible. Under the always-visible settings, when the page size exceeds one page, the scroll bar appears and remains visible. 2361 2362When **layoutMode** is set to **WebLayoutMode.FIT_CONTENT**, the **enabled** parameter is set to **false**. 2363 2364**System capability**: SystemCapability.Web.Webview.Core 2365 2366**Parameters** 2367 2368| Name | Type| Mandatory| Description | 2369| ------- | -------- | ---- | ------------------ | 2370| enabled | boolean | Yes | Whether the scroll bar is always visible. The default value is **false**.| 2371 2372 2373**Example** 2374 2375 ```ts 2376 // xxx.ets 2377 import { webview } from '@kit.ArkWeb'; 2378 2379 @Entry 2380 @Component 2381 struct WebComponent { 2382 controller: webview.WebviewController = new webview.WebviewController(); 2383 2384 build() { 2385 Column() { 2386 Web({ src: $rawfile('index.html'), controller: this.controller }) 2387 .forceDisplayScrollBar(true) 2388 } 2389 } 2390 } 2391 ``` 2392 2393 HTML file to be loaded: 2394 ```html 2395 <!--index.html--> 2396 <!DOCTYPE html> 2397 <html> 2398 <head> 2399 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 2400 <title>Demo</title> 2401 <style> 2402 body { 2403 width:2560px; 2404 height:2560px; 2405 padding-right:170px; 2406 padding-left:170px; 2407 border:5px solid blueviolet 2408 } 2409 </style> 2410 </head> 2411 <body> 2412 Scroll Test 2413 </body> 2414 </html> 2415 ``` 2416### registerNativeEmbedRule<sup>12+</sup> 2417 2418registerNativeEmbedRule(tag: string, type: string) 2419 2420Registers 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. 2421 2422If 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. 2423 2424This API is also controlled by the **enableNativeEmbedMode** API and does not take effect if same-layer rendering is not enabled. When this API is not used, the ArkWeb engine recognizes the **embed** tags with the "native/" prefix as same-layer tags. 2425 2426**System capability**: SystemCapability.Web.Webview.Core 2427 2428**Parameters** 2429 2430| Name | Type | Mandatory | Description | 2431|------|--------| ---- |------------------| 2432| tag | string | Yes | Tag name. | 2433| type | string | Yes | Tag type. It is used by the ArkWeb engine for prefix matching.| 2434 2435**Example** 2436 2437 ```ts 2438 // xxx.ets 2439 import { webview } from '@kit.ArkWeb'; 2440 2441 @Entry 2442 @Component 2443 struct WebComponent { 2444 controller: webview.WebviewController = new webview.WebviewController(); 2445 2446 build() { 2447 Column() { 2448 Web({ src: 'www.example.com', controller: this.controller }) 2449 .enableNativeEmbedMode(true) 2450 .registerNativeEmbedRule("object", "application/view") 2451 } 2452 } 2453 } 2454 ``` 2455### defaultTextEncodingFormat<sup>12+</sup> 2456 2457defaultTextEncodingFormat(textEncodingFormat: string) 2458 2459Sets the default character encoding for web pages. 2460 2461**System capability**: SystemCapability.Web.Webview.Core 2462 2463**Parameters** 2464 2465| Name | Type | Mandatory | Description | 2466| ---- | ------ | ---- | ---------------------------------------- | 2467| textEncodingFormat | string | Yes | Default character encoding. Default value: **"UTF-8"**| 2468 2469 **Example** 2470 2471 ```ts 2472 // xxx.ets 2473 import { webview } from '@kit.ArkWeb'; 2474 2475 @Entry 2476 @Component 2477 struct WebComponent { 2478 controller: webview.WebviewController = new webview.WebviewController(); 2479 2480 build() { 2481 Column() { 2482 Web({ src: $rawfile('index.html'), controller: this.controller }) 2483 // Set the height. 2484 .height(500) 2485 .defaultTextEncodingFormat("UTF-8") 2486 .javaScriptAccess(true) 2487 } 2488 } 2489 } 2490 ``` 2491 2492```html 2493 2494<!doctype html> 2495<html> 2496<head> 2497 <meta name="viewport" content="width=device-width" /> 2498 <title>My test html5 page</title> 2499</head> 2500<body> 2501 Hello world! 2502</body> 2503</html> 2504``` 2505### metaViewport<sup>12+</sup> 2506 2507metaViewport(enabled: boolean) 2508 2509Sets whether the **viewport** property of the **meta** tag is enabled. 2510 2511> **NOTE** 2512> 2513> - If this parameter is set to **false**, the **viewport** property of the **meta** tag is not enabled. This means that the property will not be parsed and a default layout will be used. 2514> - If this parameter is set to **true**, the **viewport** property of the **meta** tag is enabled. This means that the property will be parsed and used for the layout. 2515> - If set to an invalid value, this parameter does not take effect. 2516> - If the device is 2-in-1, the **viewport** property is not supported. This means that, regardless of whether this parameter is set to **true** or **false**, the **viewport** property will not be parsed and a default layout will be used. 2517> - If the device is a tablet, the **viewport-fit** property of the **meta** tag is parsed regardless of 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. 2518> - Currently, the **viewport** attribute of the **meta** tag on the frontend HTML page is enabled based on whether **UserAgent** contains the **Mobile** field. If a **UserAgent** does not contain the **Mobile** field, the **viewport** property in the **meta** tag is disabled by default. In this case, you can explicitly set the **metaViewport** property to **true** to overwrite the disabled state. 2519 2520**System capability**: SystemCapability.Web.Webview.Core 2521 2522**Parameters** 2523 2524| Name| Type| Mandatory| Description | 2525| ------ | -------- | ---- | -------------------------------- | 2526| enabled | boolean | Yes | Whether the **viewport** property of the **meta** tag is enabled. Default value: **true**| 2527 2528**Example** 2529 2530 ```ts 2531// xxx.ets 2532import { webview } from '@kit.ArkWeb'; 2533 2534@Entry 2535@Component 2536struct WebComponent { 2537 controller: webview.WebviewController = new webview.WebviewController(); 2538 2539 build() { 2540 Column() { 2541 Web({ src: $rawfile('index.html'), controller: this.controller }) 2542 .metaViewport(true) 2543 } 2544 } 2545} 2546 ``` 2547 2548```html 2549<!doctype html> 2550<html> 2551<head> 2552 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 2553</head> 2554<body> 2555 <p>Hello world! </p> 2556</body> 2557</html> 2558``` 2559 2560### textAutosizing<sup>12+</sup> 2561 2562textAutosizing(textAutosizing: boolean) 2563 2564Sets whether automatic text resizing is enabled. 2565 2566**System capability**: SystemCapability.Web.Webview.Core 2567 2568**Parameters** 2569 2570| Name | Type | Mandatory | Description | 2571| ---- | ------ | ---- | ---------------------------------------- | 2572| textAutosizing | boolean | Yes | Whether automatic text resizing is enabled. Default value: **true**| 2573 2574 **Example** 2575 2576 ```ts 2577 // xxx.ets 2578 import { webview } from '@kit.ArkWeb'; 2579 2580 @Entry 2581 @Component 2582 struct WebComponent { 2583 controller: webview.WebviewController = new webview.WebviewController(); 2584 2585 build() { 2586 Column() { 2587 Web({ src: 'www.example.com', controller: this.controller }) 2588 .textAutosizing(false) 2589 } 2590 } 2591 } 2592 ``` 2593### enableNativeMediaPlayer<sup>12+</sup> 2594 2595enableNativeMediaPlayer(config: NativeMediaPlayerConfig) 2596 2597Enable the [application takeover of web media playback feature](../../web/app-takeovers-web-media.md). 2598 2599**System capability**: SystemCapability.Web.Webview.Core 2600 2601**Parameters** 2602 2603| Name | Type | Mandatory | Description| 2604| ---- | ------ | ---- | ---------------------| 2605| config | [NativeMediaPlayerConfig](#nativemediaplayerconfig12) | Yes | **enable**: whether to enable the feature.<br> **shouldOverlay**: whether the image of the video player taken over by the application will overlay the web page content, if this feature is enabled. Default value: **{enable: false, shouldOverlay: false}**| 2606 2607 **Example** 2608 2609 ```ts 2610 // xxx.ets 2611 import { webview } from '@kit.ArkWeb'; 2612 2613 @Entry 2614 @Component 2615 struct WebComponent { 2616 controller: webview.WebviewController = new webview.WebviewController(); 2617 2618 build() { 2619 Column() { 2620 Web({ src: 'www.example.com', controller: this.controller }) 2621 .enableNativeMediaPlayer({enable: true, shouldOverlay: false}) 2622 } 2623 } 2624 } 2625 ``` 2626 2627### selectionMenuOptions<sup>12+</sup> 2628 2629selectionMenuOptions(expandedMenuOptions: Array\<ExpandedMenuItemOptions>) 2630 2631Sets the extended options of the custom context menu on selection, including the text content, icon, and callback. 2632 2633The 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. 2634 2635**System capability**: SystemCapability.Web.Webview.Core 2636 2637**Parameters** 2638 2639| Name | Type | Mandatory | Description | 2640| ------------------- | ---------------------------------------------------------- | ---- | ------------- | 2641| expandedMenuOptions | Array<[ExpandedMenuItemOptions](#expandedmenuitemoptions12)> | Yes | Extended options of the custom context menu on selection.<br>The number of menu options, menu content size, and start icon size must be the same as those of the ArkUI [\<Menu>](../apis-arkui/arkui-ts/ts-basic-components-menu.md) component.| 2642 2643**Example** 2644 2645 ```ts 2646 // xxx.ets 2647 import { webview } from '@kit.ArkWeb'; 2648 2649 @Entry 2650 @Component 2651 struct WebComponent { 2652 controller: webview.WebviewController = new webview.WebviewController(); 2653 @State menuOptionArray: Array<ExpandedMenuItemOptions> = [ 2654 {content: 'Apple', startIcon: $r('app.media.icon'), action: (selectedText) => { 2655 console.info('select info ' + selectedText.toString()); 2656 }}, 2657 {content: 'Banana', startIcon: $r('app.media.icon'), action: (selectedText) => { 2658 console.info('select info ' + selectedText.toString()); 2659 }} 2660 ]; 2661 2662 build() { 2663 Column() { 2664 Web({ src: $rawfile("index.html"), controller: this.controller }) 2665 .selectionMenuOptions(this.menuOptionArray) 2666 } 2667 } 2668 } 2669 ``` 2670 2671 HTML file to be loaded: 2672 ```html 2673 <!--index.html--> 2674 <!DOCTYPE html> 2675 <html> 2676 <head> 2677 <title>Test Web Page</title> 2678 </head> 2679 <body> 2680 <h1>selectionMenuOptions Demo</h1> 2681 <span>selection menu options</span> 2682 </body> 2683 </html> 2684 ``` 2685 2686### onAdsBlocked<sup>12+</sup> 2687 2688onAdsBlocked(callback: OnAdsBlockedCallback) 2689 2690Called 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. 2691 2692**System capability**: SystemCapability.Web.Webview.Core 2693 2694**Parameters** 2695 2696| Name | Type | Mandatory | Description | 2697| ------ | ------ | ---- | --------------------- | 2698| callback | [OnAdsBlockedCallback](#onadsblockedcallback12) | Yes| Callback for **onAdsBlocked**.| 2699 2700**Example** 2701 2702 ```ts 2703 // xxx.ets 2704 import { webview } from '@kit.ArkWeb'; 2705 2706 @Entry 2707 @Component 2708 struct WebComponent { 2709 @State totalAdsBlockCounts: number = 0; 2710 controller: webview.WebviewController = new webview.WebviewController(); 2711 2712 build() { 2713 Column() { 2714 Web({ src: 'https://www.example.com', controller: this.controller }) 2715 .onAdsBlocked((details: AdsBlockedDetails) => { 2716 if (details) { 2717 console.log(' Blocked ' + details.adsBlocked.length + ' in ' + details.url); 2718 let adList: Array<string> = Array.from(new Set(details.adsBlocked)); 2719 this.totalAdsBlockCounts += adList.length; 2720 console.log('Total blocked counts :' + this.totalAdsBlockCounts); 2721 } 2722 }) 2723 } 2724 } 2725 } 2726 ``` 2727 2728### keyboardAvoidMode<sup>12+</sup> 2729 2730keyboardAvoidMode(mode: WebKeyboardAvoidMode) 2731 2732Sets the custom soft keyboard avoidance mode. 2733 2734If the keyboard avoidance mode set in **UIContext** is [KeyboardAvoidMode.RESIZE](../apis-arkui/js-apis-arkui-UIContext.md#keyboardavoidmode11), this API does not take effect. 2735 2736**System capability**: SystemCapability.Web.Webview.Core 2737 2738**Parameters** 2739 2740| Name | Type | Mandatory | Description | 2741| ------------------- | ------------------------------ | ------ | ------------- | 2742| mode | [WebKeyboardAvoidMode](#webkeyboardavoidmode12) | Yes | Web soft keyboard avoidance mode.<br>Default value: **WebKeyboardAvoidMode.RESIZE_CONTENT**<br>In the nested scrolling scenario, the soft keyboard avoidance mode of the **Web** component is not recommended, including **RESIZE_VISUAL** and **RESIZE_CONTENT**.| 2743 2744**Example** 2745 2746 ```ts 2747 // xxx.ets 2748 import { webview } from '@kit.ArkWeb'; 2749 2750 @Entry 2751 @Component 2752 struct WebComponent { 2753 controller: webview.WebviewController = new webview.WebviewController(); 2754 @State avoidMode: WebKeyboardAvoidMode = WebKeyboardAvoidMode.RESIZE_VISUAL; 2755 2756 build() { 2757 Column() { 2758 Web({ src: $rawfile("index.html"), controller: this.controller }) 2759 .keyboardAvoidMode(this.avoidMode) 2760 } 2761 } 2762 } 2763 ``` 2764 2765 HTML file to be loaded: 2766 ```html 2767 <!--index.html--> 2768 <!DOCTYPE html> 2769 <html> 2770 <head> 2771 <title>Test Web Page</title> 2772 </head> 2773 <body> 2774 <input type="text" placeholder="Text"> 2775 </body> 2776 </html> 2777 ``` 2778 2779### editMenuOptions<sup>12+</sup> 2780 2781editMenuOptions(editMenu: EditMenuOptions) 2782 2783Sets the custom menu options of the **Web** component. 2784 2785You can use this property to customize a text menu. 2786 2787You can use [onCreateMenu](../apis-arkui/arkui-ts/ts-text-common.md#oncreatemenu) to modify, add, and delete menu options. If you do not want to display text menus, return an empty array. 2788 2789You can use [onMenuItemClick](../apis-arkui/arkui-ts/ts-text-common.md#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. 2790 2791If this API is used together with [selectionMenuOptions](#selectionmenuoptions12), **selectionMenuOptions** does not take effect. 2792 2793**System capability**: SystemCapability.Web.Webview.Core 2794 2795**Parameters** 2796 2797| Name | Type | Mandatory | Description | 2798| ------------------- | ------------------------------ | ------ | ------------- | 2799| editMenu | [EditMenuOptions](../apis-arkui/arkui-ts/ts-text-common.md#editmenuoptions) | Yes | Custom menu options of the **Web** component.<br>The number of menu options, menu content size, and icon size must be the same as those of the ArkUI [\<Menu>](../apis-arkui/arkui-ts/ts-basic-components-menu.md) component.<br>The values of ([TextMenuItemId](../apis-arkui/arkui-ts/ts-text-common.md#textmenuitemid12)) supported by the **Web** component are **CUT**, **COPY**, **PASTE**, and **SELECT_ALL**.<br>**textRange** in **onMenuItemClick()** is useless in the **Web** component. The input value is **-1**.| 2800 2801**Example** 2802 2803```ts 2804// xxx.ets 2805import { webview } from '@kit.ArkWeb'; 2806 2807@Entry 2808@Component 2809struct WebComponent { 2810 controller: webview.WebviewController = new webview.WebviewController(); 2811 2812 onCreateMenu(menuItems: Array<TextMenuItem>): Array<TextMenuItem> { 2813 let items = menuItems.filter((menuItem) => { 2814 // Filter the menu items as required. 2815 return ( 2816 menuItem.id.equals(TextMenuItemId.CUT) || 2817 menuItem.id.equals(TextMenuItemId.COPY) || 2818 menuItem.id.equals((TextMenuItemId.PASTE)) 2819 ) 2820 }); 2821 let customItem1: TextMenuItem = { 2822 content: 'customItem1', 2823 id: TextMenuItemId.of('customItem1'), 2824 icon: $r('app.media.icon') 2825 }; 2826 let customItem2: TextMenuItem = { 2827 content: $r('app.string.customItem2'), 2828 id: TextMenuItemId.of('customItem2'), 2829 icon: $r('app.media.icon') 2830 }; 2831 items.push(customItem1);// Add an option to the end of the option list. 2832 items.unshift(customItem2);// Add an option to the beginning of the option list. 2833 2834 return items; 2835 } 2836 2837 onMenuItemClick(menuItem: TextMenuItem, textRange: TextRange): boolean { 2838 if (menuItem.id.equals(TextMenuItemId.CUT)) { 2839 // User-defined behavior. 2840 console.log ("Intercept ID: CUT") 2841 return true; // Return true to not execute the system callback. 2842 } else if (menuItem.id.equals(TextMenuItemId.COPY)) { 2843 // User-defined behavior. 2844 console.log ("Do not intercept ID: COPY") 2845 return false; // Return false to execute the system callback. 2846 } else if (menuItem.id.equals(TextMenuItemId.of('customItem1'))) { 2847 // User-defined behavior. 2848 console.log ("Intercept ID: customItem1") 2849 return true;// User-defined menu option. If true is returned, the menu is not closed after being clicked. If false is returned, the menu is closed. 2850 } else if (menuItem.id.equals((TextMenuItemId.of($r('app.string.customItem2'))))){ 2851 // User-defined behavior. 2852 console.log ("Intercept ID: app.string.customItem2") 2853 return true; 2854 } 2855 return false;// Return the default value false. 2856 } 2857 2858 @State EditMenuOptions: EditMenuOptions = { onCreateMenu: this.onCreateMenu, onMenuItemClick: this.onMenuItemClick } 2859 2860 build() { 2861 Column() { 2862 Web({ src: $rawfile("index.html"), controller: this.controller }) 2863 .editMenuOptions(this.EditMenuOptions) 2864 } 2865 } 2866} 2867``` 2868 2869 HTML file to be loaded: 2870```html 2871<!--index.html--> 2872<!DOCTYPE html> 2873<html> 2874 <head> 2875 <title>Test Web Page</title> 2876 </head> 2877 <body> 2878 <h1>editMenuOptions Demo</h1> 2879 <span>edit menu options</span> 2880 </body> 2881</html> 2882``` 2883 2884### enableHapticFeedback<sup>13+</sup> 2885 2886enableHapticFeedback(enabled: boolean) 2887 2888Sets whether to enable vibration when the text in the **Web** component is pressed and held. The vibration is enabled by default. The **ohos.permission.VIBRATE** permission must be declared. 2889 2890**System capability**: SystemCapability.Web.Webview.Core 2891 2892**Parameters** 2893 2894| Name | Type | Mandatory | Description| 2895| --------- | --------- | ------ | ------------- | 2896| enabled | boolean | Yes | Whether to enable vibration. Default value: **true**| 2897 2898**Example** 2899 2900```ts 2901// xxx.ets 2902import { webview } from '@kit.ArkWeb'; 2903 2904@Entry 2905@Component 2906struct WebComponent { 2907 controller: webview.WebviewController = new webview.WebviewController(); 2908 2909 build() { 2910 Column() { 2911 Web({ src: $rawfile("index.html"), controller: this.controller }) 2912 .enableHapticFeedback(true) 2913 } 2914 } 2915} 2916``` 2917 2918 HTML file to be loaded: 2919```html 2920<!--index.html--> 2921<!DOCTYPE html> 2922<html> 2923 <head> 2924 <title>Test Web Page</title> 2925 </head> 2926 <body> 2927 <h1>enableHapticFeedback Demo</h1> 2928 <span>enable haptic feedback</span> 2929 </body> 2930</html> 2931``` 2932 2933### bindSelectionMenu<sup>13+</sup> 2934 2935bindSelectionMenu(elementType: WebElementType, content: CustomBuilder, responseType: WebResponseType, options?: SelectionMenuOptionsExt) 2936 2937Sets the custom selection menu. 2938 2939**System capability**: SystemCapability.Web.Webview.Core 2940 2941**Parameters** 2942 2943| Name | Type | Mandatory| Description | 2944| ------------ | ------------------------------- | ---- | ----------------------------------- | 2945| elementType | [WebElementType](#webelementtype13) | Yes | Menu type. | 2946| content | [CustomBuilder](../apis-arkui/arkui-ts/ts-types.md#custombuilder8) | Yes | Menu content. | 2947| responseType | [WebResponseType](#webresponsetype13) | Yes | Response type of the menu.| 2948| options | [SelectionMenuOptionsExt](#selectionmenuoptionsext13) | No | Menu options.| 2949 2950**Example** 2951 2952```ts 2953// xxx.ets 2954import { webview } from '@kit.ArkWeb'; 2955 2956interface PreviewBuilderParam { 2957 previewImage: Resource | string | undefined; 2958 width: number; 2959 height: number; 2960} 2961 2962@Builder function PreviewBuilderGlobal($$: PreviewBuilderParam) { 2963 Column() { 2964 Image($$.previewImage) 2965 .objectFit(ImageFit.Fill) 2966 .autoResize(true) 2967 }.width($$.width).height($$.height) 2968} 2969 2970@Entry 2971@Component 2972struct WebComponent { 2973 controller: webview.WebviewController = new webview.WebviewController(); 2974 2975 private result: WebContextMenuResult | undefined = undefined; 2976 @State previewImage: Resource | string | undefined = undefined; 2977 @State previewWidth: number = 0; 2978 @State previewHeight: number = 0; 2979 2980 @Builder 2981 MenuBuilder() { 2982 Menu() { 2983 MenuItem({content:'Copy',}) 2984 .onClick(() => { 2985 this.result?.copy(); 2986 this.result?.closeContextMenu(); 2987 }) 2988 MenuItem({content:'Select All',}) 2989 .onClick(() => { 2990 this.result?.selectAll(); 2991 this.result?.closeContextMenu(); 2992 }) 2993 } 2994 } 2995 build() { 2996 Column() { 2997 Web({ src: $rawfile("index.html"), controller: this.controller }) 2998 .bindSelectionMenu(WebElementType.IMAGE, this.MenuBuilder, WebResponseType.LONG_PRESS, 2999 { 3000 onAppear: () => {}, 3001 onDisappear: () => { 3002 this.result?.closeContextMenu(); 3003 }, 3004 preview: PreviewBuilderGlobal({ 3005 previewImage: this.previewImage, 3006 width: this.previewWidth, 3007 height: this.previewHeight 3008 }), 3009 menuType: MenuType.PREVIEW_MENU 3010 }) 3011 .onContextMenuShow((event) => { 3012 if (event) { 3013 this.result = event.result; 3014 if (event.param.getLinkUrl()) { 3015 return false; 3016 } 3017 this.previewWidth = px2vp(event.param.getPreviewWidth()); 3018 this.previewHeight = px2vp(event.param.getPreviewHeight()); 3019 if (event.param.getSourceUrl().indexOf("resource://rawfile/") == 0) { 3020 this.previewImage = $rawfile(event.param.getSourceUrl().substr(19)); 3021 } else { 3022 this.previewImage = event.param.getSourceUrl(); 3023 } 3024 return true; 3025 } 3026 return false; 3027 }) 3028 } 3029 } 3030} 3031``` 3032 3033 HTML file to be loaded: 3034```html 3035<!--index.html--> 3036<!DOCTYPE html> 3037<html> 3038 <head> 3039 <title>Test Web Page</title> 3040 </head> 3041 <body> 3042 <h1>bindSelectionMenu Demo</h1> 3043 <img src="./img.png" > 3044 </body> 3045</html> 3046``` 3047 3048### blurOnKeyboardHideMode<sup>14+</sup> 3049 3050blurOnKeyboardHideMode(mode: BlurOnKeyboardHideMode) 3051 3052Sets the blur mode of the **Web** component when the soft keyboard is hidden. The default value of this mode is **SILENT**. When a user collapses the soft keyboard, the focus is still on the text box. When the value is set to **BLUR**, the focus moves from the text box to the web body when a user manually collapses the soft keyboard. 3053 3054**System capability**: SystemCapability.Web.Webview.Core 3055 3056**Parameters** 3057 3058| Name | Type | Mandatory | Description | 3059| ---- | --------------------------------------- | ---- | ------------------ | 3060| mode | [BlurOnKeyboardHideMode](#bluronkeyboardhidemode14)| Yes | Sets whether to enable the blur mode of the **Web** component when the soft keyboard is hidden. The default value is **BlurOnKeyboardHideMode.SILENT**.| 3061 3062**Example** 3063 3064 ```ts 3065 // xxx.ets 3066 import { webview } from '@kit.ArkWeb'; 3067 3068 @Entry 3069 @Component 3070 struct WebComponent { 3071 controller: webview.WebviewController = new webview.WebviewController(); 3072 @State blurMode: BlurOnKeyboardHideMode = BlurOnKeyboardHideMode.BLUR; 3073 build() { 3074 Column() { 3075 Web({ src: $rawfile("index.html"), controller: this.controller }) 3076 .blurOnKeyboardHideMode(this.blurMode) 3077 } 3078 } 3079 } 3080 ``` 3081 3082 HTML file to be loaded: 3083```html 3084<!--index.html--> 3085<!DOCTYPE html> 3086<html> 3087 <head> 3088 <title>Test Web Page</title> 3089 </head> 3090 <body> 3091 <h1>blurOnKeyboardHideMode Demo</h1> 3092 <input type="text" id="input_a"> 3093 <script> 3094 const inputElement = document.getElementById('input_a'); 3095 inputElement.addEventListener('blur', function() { 3096 console.log('Input has lost focus'); 3097 }); 3098 </script> 3099 </body> 3100</html> 3101``` 3102 3103### optimizeParserBudget<sup>15+</sup> 3104 3105optimizeParserBudget(optimizeParserBudget: boolean) 3106 3107Sets whether to enable segment-based HTML parsing optimization. By default, this function is disabled. 3108 3109To 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 document structure. 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. 3110 3111After this function is enabled, the ArkWeb kernel checks whether the parsing time exceeds the limit and whether the number of parsed tokens (minimum parsing unit of HTML documents, such as **\<div>** and **attr="xxx"**) exceeds the threshold specified by the kernel, and decreases the threshold. When the First Contentful Paint (FCP) of the page is triggered, the default interrupt judgment logic is restored. In this way, the web page is parsed more frequently before the FCP is triggered, thereby the first-frame content may be parsed in advance and enter a rendering phase, effectively reducing the workload of first-frame rendering, and finally advancing the FCP. 3112 3113When 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. 3114 3115**System capability**: SystemCapability.Web.Webview.Core 3116 3117**Parameters** 3118 3119| Name | Type | Mandatory | Default Value | Description | 3120| ---------- | ------- | ---- | ---- | ---------------------- | 3121| optimizeParserBudget | boolean | Yes | false | If this parameter is set to **true**, the number of parsed records instead of the parsing time is used as the segment point for HTML segment parsing, and the upper limit of the number of parsed records in each segment is reduced. If it is set to **false**, the parsing time is used as the segment point for HTML segment parsing. The default value is **false**.| 3122 3123 3124**Example** 3125 3126 ```ts 3127 // xxx.ets 3128 import { webview } from '@kit.ArkWeb'; 3129 3130 @Entry 3131 @Component 3132 struct WebComponent { 3133 controller: webview.WebviewController = new webview.WebviewController() 3134 build() { 3135 Column() { 3136 Web({ src: 'www.example.com', controller: this.controller }) 3137 .optimizeParserBudget(true) 3138 } 3139 } 3140 } 3141 ``` 3142 3143## Events 3144 3145The following universal events are supported: [onAppear](../apis-arkui/arkui-ts/ts-universal-events-show-hide.md#onappear), [onDisAppear](../apis-arkui/arkui-ts/ts-universal-events-show-hide.md#ondisappear), [onBlur](../apis-arkui/arkui-ts/ts-universal-focus-event.md#onblur), [onFocus](../apis-arkui/arkui-ts/ts-universal-focus-event.md#onfocus), [onDragEnd](../apis-arkui/arkui-ts/ts-universal-events-drag-drop.md#ondragend), [onDragEnter](../apis-arkui/arkui-ts/ts-universal-events-drag-drop.md#ondragenter), [onDragStart](../apis-arkui/arkui-ts/ts-universal-events-drag-drop.md#ondragstart), [onDragMove](../apis-arkui/arkui-ts/ts-universal-events-drag-drop.md#ondragmove), [onDragLeave](../apis-arkui/arkui-ts/ts-universal-events-drag-drop.md#ondragleave), [onDrop](../apis-arkui/arkui-ts/ts-universal-events-drag-drop.md#ondrop), [onHover](../apis-arkui/arkui-ts/ts-universal-mouse-key.md#onhover), [onMouse](../apis-arkui/arkui-ts/ts-universal-mouse-key.md#onmouse), [onKeyEvent](../apis-arkui/arkui-ts/ts-universal-events-key.md#onkeyevent), [onTouch](../apis-arkui/arkui-ts/ts-universal-events-touch.md#ontouch), [onVisibleAreaChange](../apis-arkui/arkui-ts/ts-universal-component-visible-area-change-event.md#onvisibleareachange) 3146 3147### onAlert 3148 3149onAlert(callback: Callback\<OnAlertEvent, boolean\>) 3150 3151Called when **alert()** is invoked to display an alert dialog box on the web page. 3152 3153**System capability**: SystemCapability.Web.Webview.Core 3154 3155**Parameters** 3156 3157| Name | Type | Mandatory | Description | 3158| ------- | --------------------- | ---- | --------------- | 3159| callback | Callback\<[OnAlertEvent](#onalertevent12), boolean\> | Yes | Callback used when **alert()** is invoked to display an alert dialog box on the web page.<br>Return value: boolean<br> If the callback returns **true**, the application can use the custom dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to instruct the **Web** component to exit the current page based on the user operation. The value **false** means that the custom dialog box drawn in the function is ineffective.| 3160 3161**Example** 3162 3163 ```ts 3164 // xxx.ets 3165 import { webview } from '@kit.ArkWeb'; 3166 3167 @Entry 3168 @Component 3169 struct WebComponent { 3170 controller: webview.WebviewController = new webview.WebviewController(); 3171 3172 build() { 3173 Column() { 3174 Web({ src: $rawfile("index.html"), controller: this.controller }) 3175 .onAlert((event) => { 3176 if (event) { 3177 console.log("event.url:" + event.url); 3178 console.log("event.message:" + event.message); 3179 AlertDialog.show({ 3180 title: 'onAlert', 3181 message: 'text', 3182 primaryButton: { 3183 value: 'cancel', 3184 action: () => { 3185 event.result.handleCancel(); 3186 } 3187 }, 3188 secondaryButton: { 3189 value: 'ok', 3190 action: () => { 3191 event.result.handleConfirm(); 3192 } 3193 }, 3194 cancel: () => { 3195 event.result.handleCancel(); 3196 } 3197 }) 3198 } 3199 return true; 3200 }) 3201 } 3202 } 3203 } 3204 ``` 3205 3206 HTML file to be loaded: 3207 ```html 3208 <!--index.html--> 3209 <!DOCTYPE html> 3210 <html> 3211 <head> 3212 <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8"> 3213 </head> 3214 <body> 3215 <h1>WebView onAlert Demo</h1> 3216 <button onclick="myFunction()">Click here</button> 3217 <script> 3218 function myFunction() { 3219 alert("Hello World"); 3220 } 3221 </script> 3222 </body> 3223 </html> 3224 ``` 3225 3226### onBeforeUnload 3227 3228onBeforeUnload(callback: Callback\<OnBeforeUnloadEvent, boolean\>) 3229 3230Called when this page is about to exit after the user refreshes or closes the page. This API takes effect only when the page has obtained focus. 3231 3232**System capability**: SystemCapability.Web.Webview.Core 3233 3234**Parameters** 3235 3236| Name | Type | Mandatory | Description | 3237| ------- | --------------------- | ---- | --------------- | 3238| callback | Callback\<[OnBeforeUnloadEvent](#onbeforeunloadevent12), boolean\> | Yes | Callback used when this page is about to exit after the user refreshes or closes the page.<br>Return value: boolean<br> If the callback returns **true**, the application can use the custom dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to instruct the **Web** component to exit the current page based on the user operation. The value **false** means that the custom dialog box drawn in the function is ineffective.| 3239 3240**Example** 3241 3242 ```ts 3243 // xxx.ets 3244 import { webview } from '@kit.ArkWeb'; 3245 3246 @Entry 3247 @Component 3248 struct WebComponent { 3249 controller: webview.WebviewController = new webview.WebviewController(); 3250 3251 build() { 3252 Column() { 3253 Web({ src: $rawfile("index.html"), controller: this.controller }) 3254 .onBeforeUnload((event) => { 3255 if (event) { 3256 console.log("event.url:" + event.url); 3257 console.log("event.message:" + event.message); 3258 AlertDialog.show({ 3259 title: 'onBeforeUnload', 3260 message: 'text', 3261 primaryButton: { 3262 value: 'cancel', 3263 action: () => { 3264 event.result.handleCancel(); 3265 } 3266 }, 3267 secondaryButton: { 3268 value: 'ok', 3269 action: () => { 3270 event.result.handleConfirm(); 3271 } 3272 }, 3273 cancel: () => { 3274 event.result.handleCancel(); 3275 } 3276 }) 3277 } 3278 return true; 3279 }) 3280 } 3281 } 3282 } 3283 ``` 3284 3285 HTML file to be loaded: 3286 ```html 3287 <!--index.html--> 3288 <!DOCTYPE html> 3289 <html> 3290 <head> 3291 <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8"> 3292 </head> 3293 <body onbeforeunload="return myFunction()"> 3294 <h1>WebView onBeforeUnload Demo</h1> 3295 <a href="https://www.example.com">Click here</a> 3296 <script> 3297 function myFunction() { 3298 return "onBeforeUnload Event"; 3299 } 3300 </script> 3301 </body> 3302 </html> 3303 ``` 3304 3305### onConfirm 3306 3307onConfirm(callback: Callback\<OnConfirmEvent, boolean\>) 3308 3309Called when **confirm()** is invoked by the web page. 3310 3311**System capability**: SystemCapability.Web.Webview.Core 3312 3313**Parameters** 3314 3315| Name | Type | Mandatory | Description | 3316| ------- | --------------------- | ---- | --------------- | 3317| callback | Callback\<[OnConfirmEvent](#onconfirmevent12), boolean\> | Yes | Called when **confirm()** is invoked by the web page.<br>Return value: boolean<br> If the callback returns **true**, the application can use the custom dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to instruct the **Web** component to exit the current page based on the user operation. The value **false** means that the custom dialog box drawn in the function is ineffective.| 3318 3319**Example** 3320 3321 ```ts 3322 // xxx.ets 3323 import { webview } from '@kit.ArkWeb'; 3324 3325 @Entry 3326 @Component 3327 struct WebComponent { 3328 controller: webview.WebviewController = new webview.WebviewController(); 3329 3330 build() { 3331 Column() { 3332 Web({ src: $rawfile("index.html"), controller: this.controller }) 3333 .onConfirm((event) => { 3334 if (event) { 3335 console.log("event.url:" + event.url); 3336 console.log("event.message:" + event.message); 3337 AlertDialog.show({ 3338 title: 'onConfirm', 3339 message: 'text', 3340 primaryButton: { 3341 value: 'cancel', 3342 action: () => { 3343 event.result.handleCancel(); 3344 } 3345 }, 3346 secondaryButton: { 3347 value: 'ok', 3348 action: () => { 3349 event.result.handleConfirm(); 3350 } 3351 }, 3352 cancel: () => { 3353 event.result.handleCancel(); 3354 } 3355 }) 3356 } 3357 return true; 3358 }) 3359 } 3360 } 3361 } 3362 ``` 3363 3364 HTML file to be loaded: 3365 ```html 3366 <!--index.html--> 3367 <!DOCTYPE html> 3368 <html> 3369 <head> 3370 <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8"> 3371 </head> 3372 3373 <body> 3374 <h1>WebView onConfirm Demo</h1> 3375 <button onclick="myFunction()">Click here</button> 3376 <p id="demo"></p> 3377 <script> 3378 function myFunction() { 3379 let x; 3380 let r = confirm("click button!"); 3381 if (r == true) { 3382 x = "ok"; 3383 } else { 3384 x = "cancel"; 3385 } 3386 document.getElementById("demo").innerHTML = x; 3387 } 3388 </script> 3389 </body> 3390 </html> 3391 ``` 3392 3393### onPrompt<sup>9+</sup> 3394 3395onPrompt(callback: Callback\<OnPromptEvent, boolean\>) 3396 3397Called when **prompt()** is invoked by the web page. 3398 3399**System capability**: SystemCapability.Web.Webview.Core 3400 3401**Parameters** 3402 3403| Name | Type | Mandatory | Description | 3404| ------- | --------------------- | ---- | --------------- | 3405| callback | Callback\<[OnPromptEvent](#onpromptevent12), boolean\> | Yes | Called when **prompt()** is invoked by the web page.<br>Return value: boolean<br> If the callback returns **true**, the application can use the custom dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to instruct the **Web** component to exit the current page based on the user operation. The value **false** means that the custom dialog box drawn in the function is ineffective.| 3406 3407**Example** 3408 3409 ```ts 3410 // xxx.ets 3411 import { webview } from '@kit.ArkWeb'; 3412 3413 @Entry 3414 @Component 3415 struct WebComponent { 3416 controller: webview.WebviewController = new webview.WebviewController(); 3417 3418 build() { 3419 Column() { 3420 Web({ src: $rawfile("index.html"), controller: this.controller }) 3421 .onPrompt((event) => { 3422 if (event) { 3423 console.log("url:" + event.url); 3424 console.log("message:" + event.message); 3425 console.log("value:" + event.value); 3426 AlertDialog.show({ 3427 title: 'onPrompt', 3428 message: 'text', 3429 primaryButton: { 3430 value: 'cancel', 3431 action: () => { 3432 event.result.handleCancel(); 3433 } 3434 }, 3435 secondaryButton: { 3436 value: 'ok', 3437 action: () => { 3438 event.result.handlePromptConfirm(event.value); 3439 } 3440 }, 3441 cancel: () => { 3442 event.result.handleCancel(); 3443 } 3444 }) 3445 } 3446 return true; 3447 }) 3448 } 3449 } 3450 } 3451 ``` 3452 3453 HTML file to be loaded: 3454 ```html 3455 <!--index.html--> 3456 <!DOCTYPE html> 3457 <html> 3458 <head> 3459 <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8"> 3460 </head> 3461 3462 <body> 3463 <h1>WebView onPrompt Demo</h1> 3464 <button onclick="myFunction()">Click here</button> 3465 <p id="demo"></p> 3466 <script> 3467 function myFunction() { 3468 let message = prompt("Message info", "Hello World"); 3469 if (message != null && message != "") { 3470 document.getElementById("demo").innerHTML = message; 3471 } 3472 } 3473 </script> 3474 </body> 3475 </html> 3476 ``` 3477 3478### onConsole 3479 3480onConsole(callback: Callback\<OnConsoleEvent, boolean\>) 3481 3482Called to notify the host application of a JavaScript console message. 3483 3484**System capability**: SystemCapability.Web.Webview.Core 3485 3486**Parameters** 3487 3488| Name | Type | Mandatory | Description | 3489| ------- | --------------------------------- | ---- | --------- | 3490| callback | Callback\<[OnConsoleEvent](#onconsoleevent12), boolean\> | Yes | Called when the web page receives a JavaScript console message.<br>Return value: boolean<br> Returns **true** if the message will not be printed to the console; returns **false** otherwise.| 3491 3492**Example** 3493 3494 ```ts 3495 // xxx.ets 3496 import { webview } from '@kit.ArkWeb'; 3497 3498 @Entry 3499 @Component 3500 struct WebComponent { 3501 controller: webview.WebviewController = new webview.WebviewController(); 3502 3503 build() { 3504 Column() { 3505 Button('onconsole message') 3506 .onClick(() => { 3507 this.controller.runJavaScript('myFunction()'); 3508 }) 3509 Web({ src: $rawfile('index.html'), controller: this.controller }) 3510 .onConsole((event) => { 3511 if (event) { 3512 console.log('getMessage:' + event.message.getMessage()); 3513 console.log('getSourceId:' + event.message.getSourceId()); 3514 console.log('getLineNumber:' + event.message.getLineNumber()); 3515 console.log('getMessageLevel:' + event.message.getMessageLevel()); 3516 } 3517 return false; 3518 }) 3519 } 3520 } 3521 } 3522 ``` 3523 3524 HTML file to be loaded: 3525 ```html 3526 <!-- index.html --> 3527 <!DOCTYPE html> 3528 <html> 3529 <body> 3530 <script> 3531 function myFunction() { 3532 console.log("onconsole printf"); 3533 } 3534 </script> 3535 </body> 3536 </html> 3537 ``` 3538 3539### onDownloadStart 3540 3541onDownloadStart(callback: Callback\<OnDownloadStartEvent\>) 3542 3543Instructs the main application to start downloading a file. 3544 3545**System capability**: SystemCapability.Web.Webview.Core 3546 3547**Parameters** 3548 3549| Name | Type | Mandatory | Description | 3550| ------------------ | ------ | ---- | ----------------------------------- | 3551| callback | Callback\<[OnDownloadStartEvent](#ondownloadstartevent12)\> | Yes | Called when the download starts. | 3552 3553**Example** 3554 3555 ```ts 3556 // xxx.ets 3557 import { webview } from '@kit.ArkWeb'; 3558 3559 @Entry 3560 @Component 3561 struct WebComponent { 3562 controller: webview.WebviewController = new webview.WebviewController(); 3563 3564 build() { 3565 Column() { 3566 Web({ src: 'www.example.com', controller: this.controller }) 3567 .onDownloadStart((event) => { 3568 if (event) { 3569 console.log('url:' + event.url) 3570 console.log('userAgent:' + event.userAgent) 3571 console.log('contentDisposition:' + event.contentDisposition) 3572 console.log('contentLength:' + event.contentLength) 3573 console.log('mimetype:' + event.mimetype) 3574 } 3575 }) 3576 } 3577 } 3578 } 3579 ``` 3580 3581### onErrorReceive 3582 3583onErrorReceive(callback: Callback\<OnErrorReceiveEvent\>) 3584 3585Called when an error occurs during web page loading. The error may occur on the main resource or sub-resource. You can use **request.isMainFrame()** to determine whether an error occurs on the main resource. For better results, simplify the implementation logic in the callback. This API is called when there is no network connection. 3586 3587**System capability**: SystemCapability.Web.Webview.Core 3588 3589**Parameters** 3590 3591| Name | Type | Mandatory | Description | 3592| ------- | ---------------------------------------- | ---- | --------------- | 3593| callback | Callback\<[OnErrorReceiveEvent](#onerrorreceiveevent12)\> | Yes | Called when an error occurs during web page loading. | 3594 3595**Example** 3596 3597 ```ts 3598 // xxx.ets 3599 import { webview } from '@kit.ArkWeb'; 3600 3601 @Entry 3602 @Component 3603 struct WebComponent { 3604 controller: webview.WebviewController = new webview.WebviewController(); 3605 3606 build() { 3607 Column() { 3608 Web({ src: 'www.example.com', controller: this.controller }) 3609 .onErrorReceive((event) => { 3610 if (event) { 3611 console.log('getErrorInfo:' + event.error.getErrorInfo()); 3612 console.log('getErrorCode:' + event.error.getErrorCode()); 3613 console.log('url:' + event.request.getRequestUrl()); 3614 console.log('isMainFrame:' + event.request.isMainFrame()); 3615 console.log('isRedirect:' + event.request.isRedirect()); 3616 console.log('isRequestGesture:' + event.request.isRequestGesture()); 3617 console.log('getRequestHeader_headerKey:' + event.request.getRequestHeader().toString()); 3618 let result = event.request.getRequestHeader(); 3619 console.log('The request header result size is ' + result.length); 3620 for (let i of result) { 3621 console.log('The request header key is : ' + i.headerKey + ', value is : ' + i.headerValue); 3622 } 3623 } 3624 }) 3625 } 3626 } 3627 } 3628 ``` 3629 3630### onHttpErrorReceive 3631 3632onHttpErrorReceive(callback: Callback\<OnHttpErrorReceiveEvent\>) 3633 3634Called when an HTTP error (the response code is greater than or equal to 400) occurs during web page resource loading. 3635 3636**System capability**: SystemCapability.Web.Webview.Core 3637 3638**Parameters** 3639 3640| Name | Type | Mandatory | Description | 3641| -------- | ---------------------------------------- | ---- | ---------- | 3642| callback | Callback\<[OnHttpErrorReceiveEvent](#onhttperrorreceiveevent12)\> | Yes | Called when an HTTP error occurs during web page resource loading.| 3643 3644**Example** 3645 3646 ```ts 3647 // xxx.ets 3648 import { webview } from '@kit.ArkWeb'; 3649 3650 @Entry 3651 @Component 3652 struct WebComponent { 3653 controller: webview.WebviewController = new webview.WebviewController(); 3654 3655 build() { 3656 Column() { 3657 Web({ src: 'www.example.com', controller: this.controller }) 3658 .onHttpErrorReceive((event) => { 3659 if (event) { 3660 console.log('url:' + event.request.getRequestUrl()); 3661 console.log('isMainFrame:' + event.request.isMainFrame()); 3662 console.log('isRedirect:' + event.request.isRedirect()); 3663 console.log('isRequestGesture:' + event.request.isRequestGesture()); 3664 console.log('getResponseData:' + event.response.getResponseData()); 3665 console.log('getResponseEncoding:' + event.response.getResponseEncoding()); 3666 console.log('getResponseMimeType:' + event.response.getResponseMimeType()); 3667 console.log('getResponseCode:' + event.response.getResponseCode()); 3668 console.log('getReasonMessage:' + event.response.getReasonMessage()); 3669 let result = event.request.getRequestHeader(); 3670 console.log('The request header result size is ' + result.length); 3671 for (let i of result) { 3672 console.log('The request header key is : ' + i.headerKey + ' , value is : ' + i.headerValue); 3673 } 3674 let resph = event.response.getResponseHeader(); 3675 console.log('The response header result size is ' + resph.length); 3676 for (let i of resph) { 3677 console.log('The response header key is : ' + i.headerKey + ' , value is : ' + i.headerValue); 3678 } 3679 } 3680 }) 3681 } 3682 } 3683 } 3684 ``` 3685 3686### onPageBegin 3687 3688onPageBegin(callback: Callback\<OnPageBeginEvent\>) 3689 3690Called when the web page starts to be loaded. This API is called only for the main frame content, and not for the iframe or frameset content. 3691 3692**System capability**: SystemCapability.Web.Webview.Core 3693 3694**Parameters** 3695 3696| Name | Type | Mandatory | Description | 3697| ---- | ------ | ---- | --------- | 3698| callback | Callback\<[OnPageBeginEvent](#onpagebeginevent12)\> | Yes | Called when the web page starts to be loaded.| 3699 3700**Example** 3701 3702 ```ts 3703 // xxx.ets 3704 import { webview } from '@kit.ArkWeb'; 3705 3706 @Entry 3707 @Component 3708 struct WebComponent { 3709 controller: webview.WebviewController = new webview.WebviewController(); 3710 3711 build() { 3712 Column() { 3713 Web({ src: 'www.example.com', controller: this.controller }) 3714 .onPageBegin((event) => { 3715 if (event) { 3716 console.log('url:' + event.url); 3717 } 3718 }) 3719 } 3720 } 3721 } 3722 ``` 3723 3724### onPageEnd 3725 3726onPageEnd(callback: Callback\<OnPageEndEvent\>) 3727 3728Called when the web page loading is complete. This API takes effect only for the main frame content. 3729 3730**System capability**: SystemCapability.Web.Webview.Core 3731 3732**Parameters** 3733 3734| Name | Type | Mandatory | Description | 3735| ---- | ------ | ---- | --------- | 3736| callback | Callback\<[OnPageEndEvent](#onpageendevent12)\> | Yes | Called when the web page loading is complete.| 3737 3738**Example** 3739 3740 ```ts 3741 // xxx.ets 3742 import { webview } from '@kit.ArkWeb'; 3743 3744 @Entry 3745 @Component 3746 struct WebComponent { 3747 controller: webview.WebviewController = new webview.WebviewController(); 3748 3749 build() { 3750 Column() { 3751 Web({ src: 'www.example.com', controller: this.controller }) 3752 .onPageEnd((event) => { 3753 if (event) { 3754 console.log('url:' + event.url); 3755 } 3756 }) 3757 } 3758 } 3759 } 3760 ``` 3761 3762### onProgressChange 3763 3764onProgressChange(callback: Callback\<OnProgressChangeEvent\>) 3765 3766Called when the web page loading progress changes. 3767 3768**System capability**: SystemCapability.Web.Webview.Core 3769 3770**Parameters** 3771 3772| Name | Type | Mandatory | Description | 3773| ----------- | ------ | ---- | --------------------- | 3774| callback | Callback\<[OnProgressChangeEvent](#onprogresschangeevent12)\> | Yes | Called when the web page loading progress changes.| 3775 3776**Example** 3777 3778 ```ts 3779 // xxx.ets 3780 import { webview } from '@kit.ArkWeb'; 3781 @Entry 3782 @Component 3783 struct WebComponent { 3784 controller: webview.WebviewController = new webview.WebviewController(); 3785 3786 build() { 3787 Column() { 3788 Web({ src: 'www.example.com', controller: this.controller }) 3789 .onProgressChange((event) => { 3790 if (event) { 3791 console.log('newProgress:' + event.newProgress); 3792 } 3793 }) 3794 } 3795 } 3796 } 3797 ``` 3798 3799### onTitleReceive 3800 3801onTitleReceive(callback: Callback\<OnTitleReceiveEvent\>) 3802 3803Called when the document title of a web page is changed. If the <title\> element is not set for an HTML5 page, the corresponding URL is returned. 3804 3805**System capability**: SystemCapability.Web.Webview.Core 3806 3807**Parameters** 3808 3809| Name | Type | Mandatory | Description | 3810| ----- | ------ | ---- | ------------- | 3811| callback | Callback\<[OnTitleReceiveEvent](#ontitlereceiveevent12)\> | Yes | Called when the document title of the web page is changed.| 3812 3813**Example** 3814 3815 ```ts 3816 // xxx.ets 3817 import { webview } from '@kit.ArkWeb'; 3818 3819 @Entry 3820 @Component 3821 struct WebComponent { 3822 controller: webview.WebviewController = new webview.WebviewController(); 3823 3824 build() { 3825 Column() { 3826 Web({ src: 'www.example.com', controller: this.controller }) 3827 .onTitleReceive((event) => { 3828 if (event) { 3829 console.log('title:' + event.title); 3830 } 3831 }) 3832 } 3833 } 3834 } 3835 ``` 3836 3837### onRefreshAccessedHistory 3838 3839onRefreshAccessedHistory(callback: Callback\<OnRefreshAccessedHistoryEvent\>) 3840 3841Called when loading of the web page is complete and the access history of a web page is refreshed. 3842 3843**System capability**: SystemCapability.Web.Webview.Core 3844 3845**Parameters** 3846 3847| Name | Type | Mandatory | Description | 3848| ----------- | ------- | ---- | ---------------------------------------- | 3849| callback | Callback\<[OnRefreshAccessedHistoryEvent](#onrefreshaccessedhistoryevent12)\> | Yes | Called when the access history of the web page is refreshed. | 3850 3851**Example** 3852 3853 ```ts 3854 // xxx.ets 3855 import { webview } from '@kit.ArkWeb'; 3856 3857 @Entry 3858 @Component 3859 struct WebComponent { 3860 controller: webview.WebviewController = new webview.WebviewController(); 3861 3862 build() { 3863 Column() { 3864 Web({ src: 'www.example.com', controller: this.controller }) 3865 .onRefreshAccessedHistory((event) => { 3866 if (event) { 3867 console.log('url:' + event.url + ' isReload:' + event.isRefreshed); 3868 } 3869 }) 3870 } 3871 } 3872 } 3873 ``` 3874 3875### onSslErrorReceive<sup>(deprecated)</sup> 3876 3877onSslErrorReceive(callback: (event?: { handler: Function, error: object }) => void) 3878 3879Called when an SSL error occurs during resource loading. 3880 3881> **NOTE** 3882> 3883> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [onSslErrorEventReceive<sup>9+</sup>](#onsslerroreventreceive9) instead. 3884 3885**System capability**: SystemCapability.Web.Webview.Core 3886 3887### onFileSelectorShow<sup>(deprecated)</sup> 3888 3889onFileSelectorShow(callback: (event?: { callback: Function, fileSelector: object }) => void) 3890 3891Called to process an HTML form whose input type is **file**, in response to the tapping of the **Select File** button. 3892 3893> **NOTE** 3894> 3895> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [onShowFileSelector<sup>9+</sup>](#onshowfileselector9) instead. 3896 3897**System capability**: SystemCapability.Web.Webview.Core 3898 3899### onRenderExited<sup>9+</sup> 3900 3901onRenderExited(callback: Callback\<OnRenderExitedEvent\>) 3902 3903Called when the rendering process exits abnormally. 3904 3905A rendering process may be shared by multiple **Web** components. Each affected **Web** component triggers this callback. 3906 3907You can call the bound **webviewController** APIs to restore the web page when this callback is triggered. For example, [refresh](js-apis-webview.md#refresh) and [loadUrl](js-apis-webview.md#loadurl). 3908 3909For details about the component lifecycle, see [Lifecycle of Web Components](../../web/web-event-sequence.md). 3910 3911**System capability**: SystemCapability.Web.Webview.Core 3912 3913**Parameters** 3914 3915| Name | Type | Mandatory | Description | 3916| ---------------- | ---------------------------------------- | ---- | ---------------- | 3917| callback | Callback\<[OnRenderExitedEvent](#onrenderexitedevent12)\> | Yes | Called when the rendering process exits abnormally.| 3918 3919**Example** 3920 3921 ```ts 3922 // xxx.ets 3923 import { webview } from '@kit.ArkWeb'; 3924 3925 @Entry 3926 @Component 3927 struct WebComponent { 3928 controller: webview.WebviewController = new webview.WebviewController(); 3929 3930 build() { 3931 Column() { 3932 Web({ src: 'chrome://crash/', controller: this.controller }) 3933 .onRenderExited((event) => { 3934 if (event) { 3935 console.log('reason:' + event.renderExitReason); 3936 } 3937 }) 3938 } 3939 } 3940 } 3941 ``` 3942### onRenderProcessNotResponding<sup>12+</sup> 3943 3944onRenderProcessNotResponding(callback: OnRenderProcessNotRespondingCallback) 3945 3946Called when the rendering process does not respond. If the **Web** component cannot process the input event or navigate to a new URL within a proper time range, the web page process is considered unresponsive and the callback is triggered. 3947 3948If the web page process does not respond, this callback may be triggered until the web page process responds again. In this case, [onRenderProcessResponding](#onrenderprocessresponding12) is triggered. 3949 3950You can terminate the associated rendering process through [terminateRenderProcess](js-apis-webview.md#terminaterenderprocess12), which may affect other Web components in the same rendering process. 3951 3952**System capability**: SystemCapability.Web.Webview.Core 3953 3954**Parameters** 3955 3956| Name | Type | Mandatory | Description | 3957| -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | 3958| callback | [OnRenderProcessNotRespondingCallback](#onrenderprocessnotrespondingcallback12) | Yes | Callback triggered when the rendering process does not respond.| 3959 3960**Example** 3961 3962 ```ts 3963 // xxx.ets 3964 import { webview } from '@kit.ArkWeb'; 3965 3966 @Entry 3967 @Component 3968 struct WebComponent { 3969 controller: webview.WebviewController = new webview.WebviewController(); 3970 3971 build() { 3972 Column() { 3973 Web({ src: 'www.example.com', controller: this.controller }) 3974 .onRenderProcessNotResponding((data) => { 3975 console.log("onRenderProcessNotResponding: [jsStack]= " + data.jsStack + 3976 ", [process]=" + data.pid + ", [reason]=" + data.reason); 3977 }) 3978 } 3979 } 3980 } 3981 ``` 3982 3983### onRenderProcessResponding<sup>12+</sup> 3984 3985onRenderProcessResponding(callback: OnRenderProcessRespondingCallback) 3986 3987Called when the rendering process transitions back to a normal operating state from an unresponsive state. This callback indicates that the web page was not actually frozen. 3988 3989**System capability**: SystemCapability.Web.Webview.Core 3990 3991**Parameters** 3992 3993| Name | Type | Mandatory | Description | 3994| -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | 3995| callback | [OnRenderProcessRespondingCallback](#onrenderprocessrespondingcallback12) | Yes | Callback triggered when the rendering process transitions back to a normal operating state from an unresponsive state.| 3996 3997**Example** 3998 3999 ```ts 4000 // xxx.ets 4001 import { webview } from '@kit.ArkWeb'; 4002 4003 @Entry 4004 @Component 4005 struct WebComponent { 4006 controller: webview.WebviewController = new webview.WebviewController(); 4007 4008 build() { 4009 Column() { 4010 Web({ src: 'www.example.com', controller: this.controller }) 4011 .onRenderProcessResponding(() => { 4012 console.log("onRenderProcessResponding again"); 4013 }) 4014 } 4015 } 4016 } 4017 ``` 4018 4019### onShowFileSelector<sup>9+</sup> 4020 4021onShowFileSelector(callback: Callback\<OnShowFileSelectorEvent, boolean\>) 4022 4023Called to process an HTML form whose input type is **file**. If this function is not called or returns **false**, the **Web** component provides the default **Select File** handling UI. If it returns **true**, the application can customize the response behavior for **Select File**. 4024 4025**System capability**: SystemCapability.Web.Webview.Core 4026 4027**Parameters** 4028 4029| Name | Type | Mandatory | Description | 4030| ------------ | ---------------------------------------- | ---- | ----------------- | 4031| callback | Callback\<[OnShowFileSelectorEvent](#onshowfileselectorevent12), boolean\> | Yes | File selection result to be sent to the **Web** component.<br>Return value: boolean<br> The value **true** means that you can invoke the system-provided popup capability. The value **false** means that the custom dialog box drawn in the function is ineffective.| 4032 4033**Example** 4034 40351. Start the file selector. 4036 4037 ```ts 4038 // xxx.ets 4039 import { webview } from '@kit.ArkWeb'; 4040 import { picker } from '@kit.CoreFileKit'; 4041 import { BusinessError } from '@kit.BasicServicesKit'; 4042 4043 @Entry 4044 @Component 4045 struct WebComponent { 4046 controller: webview.WebviewController = new webview.WebviewController() 4047 4048 build() { 4049 Column() { 4050 Web({ src: $rawfile('index.html'), controller: this.controller }) 4051 .onShowFileSelector((event) => { 4052 console.log('MyFileUploader onShowFileSelector invoked') 4053 const documentSelectOptions = new picker.DocumentSelectOptions(); 4054 let uri: string | null = null; 4055 const documentViewPicker = new picker.DocumentViewPicker(); 4056 documentViewPicker.select(documentSelectOptions).then((documentSelectResult) => { 4057 uri = documentSelectResult[0]; 4058 console.info('documentViewPicker.select to file succeed and uri is:' + uri); 4059 if (event) { 4060 event.result.handleFileList([uri]); 4061 } 4062 }).catch((err: BusinessError) => { 4063 console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`); 4064 }) 4065 return true; 4066 }) 4067 } 4068 } 4069 } 4070 ``` 4071 40722. Start the photo selector. 4073 4074 ```ts 4075 // xxx.ets 4076 import { webview } from '@kit.ArkWeb'; 4077 import { picker } from '@kit.CoreFileKit'; 4078 import { photoAccessHelper } from '@kit.MediaLibraryKit'; 4079 4080 @Entry 4081 @Component 4082 export struct WebComponent { 4083 controller: webview.WebviewController = new webview.WebviewController() 4084 4085 async selectFile(result: FileSelectorResult): Promise<void> { 4086 let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions(); 4087 let photoPicker = new photoAccessHelper.PhotoViewPicker(); 4088 // Set the MIME file type to IMAGE. 4089 photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE; 4090 // Set the maximum number of media files that can be selected. 4091 photoSelectOptions.maxSelectNumber = 5; 4092 let chooseFile: picker.PhotoSelectResult = await photoPicker.select(photoSelectOptions); 4093 // Obtain the list of selected files. 4094 result.handleFileList(chooseFile.photoUris); 4095 } 4096 4097 build() { 4098 Column() { 4099 Web({ src: $rawfile('index.html'), controller: this.controller }) 4100 .onShowFileSelector((event) => { 4101 if (event) { 4102 this.selectFile(event.result); 4103 } 4104 return true; 4105 }) 4106 } 4107 } 4108 } 4109 ``` 4110 4111 HTML file to be loaded: 4112 ```html 4113 <!DOCTYPE html> 4114 <html> 4115 <head> 4116 <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8"> 4117 </head> 4118 <body> 4119 <form id="upload-form" enctype="multipart/form-data"> 4120 <input type="file" id="upload" name="upload"/> 4121 </form> 4122 </body> 4123 </html> 4124 ``` 4125 4126### onResourceLoad<sup>9+</sup> 4127 4128onResourceLoad(callback: Callback\<OnResourceLoadEvent\>) 4129 4130Called to notify the **Web** component of the URL of the loaded resource file. 4131 4132**System capability**: SystemCapability.Web.Webview.Core 4133 4134**Parameters** 4135 4136| Name | Type | Mandatory | Description | 4137| ------ | ------ | ---- | --------------------- | 4138| callback | Callback\<[OnResourceLoadEvent](#onresourceloadevent12)\> | Yes| Callback invoked when a URL is loaded.| 4139 4140**Example** 4141 4142 ```ts 4143 // xxx.ets 4144 import { webview } from '@kit.ArkWeb'; 4145 4146 @Entry 4147 @Component 4148 struct WebComponent { 4149 controller: webview.WebviewController = new webview.WebviewController(); 4150 4151 build() { 4152 Column() { 4153 Web({ src: 'www.example.com', controller: this.controller }) 4154 .onResourceLoad((event) => { 4155 console.log('onResourceLoad: ' + event.url); 4156 }) 4157 } 4158 } 4159 } 4160 ``` 4161 4162### onScaleChange<sup>9+</sup> 4163 4164onScaleChange(callback: Callback\<OnScaleChangeEvent\>) 4165 4166Called when the display ratio of this page changes. 4167 4168**System capability**: SystemCapability.Web.Webview.Core 4169 4170**Parameters** 4171 4172| Name | Type | Mandatory | Description | 4173| ------ | ------ | ---- | --------------------- | 4174| callback | Callback\<[OnScaleChangeEvent](#onscalechangeevent12)\> | Yes| Callback invoked when the display ratio of the page changes.| 4175 4176**Example** 4177 4178 ```ts 4179 // xxx.ets 4180 import { webview } from '@kit.ArkWeb'; 4181 4182 @Entry 4183 @Component 4184 struct WebComponent { 4185 controller: webview.WebviewController = new webview.WebviewController(); 4186 4187 build() { 4188 Column() { 4189 Web({ src: 'www.example.com', controller: this.controller }) 4190 .onScaleChange((event) => { 4191 console.log('onScaleChange changed from ' + event.oldScale + ' to ' + event.newScale); 4192 }) 4193 } 4194 } 4195 } 4196 ``` 4197 4198### onUrlLoadIntercept<sup>(deprecated)</sup> 4199 4200onUrlLoadIntercept(callback: (event?: { data:string | WebResourceRequest }) => boolean) 4201 4202Called when the **Web** component is about to access a URL. This API is used to determine whether to block the access, which is allowed by default. 4203This API is deprecated since API version 10. You are advised to use [onLoadIntercept<sup>10+</sup>](#onloadintercept10) instead. 4204 4205**System capability**: SystemCapability.Web.Webview.Core 4206 4207**Parameters** 4208 4209| Name | Type | Mandatory | Description | 4210| ------ | ------ | ---- | --------------------- | 4211| callback | (event?: { data:string \| [WebResourceRequest](#webresourcerequest) }) => boolean | Yes| URL information. Returns **true** if the access is blocked; returns **false** otherwise.| 4212 4213**Example** 4214 4215 ```ts 4216 // xxx.ets 4217 import { webview } from '@kit.ArkWeb'; 4218 4219 @Entry 4220 @Component 4221 struct WebComponent { 4222 controller: webview.WebviewController = new webview.WebviewController(); 4223 4224 build() { 4225 Column() { 4226 Web({ src: 'www.example.com', controller: this.controller }) 4227 .onUrlLoadIntercept((event) => { 4228 if (event) { 4229 console.log('onUrlLoadIntercept ' + event.data.toString()); 4230 } 4231 return true 4232 }) 4233 } 4234 } 4235 } 4236 ``` 4237 4238### onInterceptRequest<sup>9+</sup> 4239 4240onInterceptRequest(callback: Callback<OnInterceptRequestEvent, WebResourceResponse>) 4241 4242Called when the **Web** component is about to access a URL. This API is used to block the URL and return the response data. 4243 4244**System capability**: SystemCapability.Web.Webview.Core 4245 4246**Parameters** 4247 4248| Name | Type | Mandatory | Description | 4249| ------ | ------ | ---- | --------------------- | 4250| callback | Callback\<[OnInterceptRequestEvent](#oninterceptrequestevent12)\> | Yes| Callback invoked when the **Web** component is about to load a URL.<br>The return value is [WebResourceResponse](#webresourceresponse). If response data is returned, the data is loaded based on the response data. If no response data is returned, null is returned, indicating that the data is loaded in the original mode.| 4251 4252**Example** 4253 4254 ```ts 4255 // xxx.ets 4256 import { webview } from '@kit.ArkWeb'; 4257 4258 @Entry 4259 @Component 4260 struct WebComponent { 4261 controller: webview.WebviewController = new webview.WebviewController(); 4262 responseWeb: WebResourceResponse = new WebResourceResponse(); 4263 heads: Header[] = new Array(); 4264 webData: string = "<!DOCTYPE html>\n" + 4265 "<html>\n" + 4266 "<head>\n" + 4267 "<title>intercept test</title>\n" + 4268 "</head>\n" + 4269 "<body>\n" + 4270 "<h1>intercept test</h1>\n" + 4271 "</body>\n" + 4272 "</html>"; 4273 4274 build() { 4275 Column() { 4276 Web({ src: 'www.example.com', controller: this.controller }) 4277 .onInterceptRequest((event) => { 4278 if (event) { 4279 console.log('url:' + event.request.getRequestUrl()); 4280 } 4281 let head1: Header = { 4282 headerKey: "Connection", 4283 headerValue: "keep-alive" 4284 } 4285 let head2: Header = { 4286 headerKey: "Cache-Control", 4287 headerValue: "no-cache" 4288 } 4289 // Add a new element to the end of the array and return the length of the new array. 4290 let length = this.heads.push(head1); 4291 length = this.heads.push(head2); 4292 console.log('The response header result length is :' + length); 4293 const promise: Promise<String> = new Promise((resolve: Function, reject: Function) => { 4294 this.responseWeb.setResponseHeader(this.heads); 4295 this.responseWeb.setResponseData(this.webData); 4296 this.responseWeb.setResponseEncoding('utf-8'); 4297 this.responseWeb.setResponseMimeType('text/html'); 4298 this.responseWeb.setResponseCode(200); 4299 this.responseWeb.setReasonMessage('OK'); 4300 resolve("success"); 4301 }) 4302 promise.then(() => { 4303 console.log("prepare response ready"); 4304 this.responseWeb.setResponseIsReady(true); 4305 }) 4306 this.responseWeb.setResponseIsReady(false); 4307 return this.responseWeb; 4308 }) 4309 } 4310 } 4311 } 4312 ``` 4313 4314### onHttpAuthRequest<sup>9+</sup> 4315 4316onHttpAuthRequest(callback: Callback\<OnHttpAuthRequestEvent, boolean\>) 4317 4318Called when an HTTP authentication request is received. 4319 4320**System capability**: SystemCapability.Web.Webview.Core 4321 4322**Parameters** 4323 4324| Name | Type | Mandatory | Description | 4325| ------ | ------ | ---- | --------------------- | 4326| callback | Callback\<[OnHttpAuthRequestEvent](#onhttpauthrequestevent12), boolean\> | Yes| Callback invoked when the browser requires user credentials.<br>Return value: boolean<br> Returns **true** if the authentication is successful; returns **false** otherwise. | 4327 4328**Example** 4329 4330 ```ts 4331 // xxx.ets 4332 import { webview } from '@kit.ArkWeb'; 4333 4334 @Entry 4335 @Component 4336 struct WebComponent { 4337 controller: webview.WebviewController = new webview.WebviewController(); 4338 httpAuth: boolean = false; 4339 4340 build() { 4341 Column() { 4342 Web({ src: 'www.example.com', controller: this.controller }) 4343 .onHttpAuthRequest((event) => { 4344 if (event) { 4345 AlertDialog.show({ 4346 title: 'onHttpAuthRequest', 4347 message: 'text', 4348 primaryButton: { 4349 value: 'cancel', 4350 action: () => { 4351 event.handler.cancel(); 4352 } 4353 }, 4354 secondaryButton: { 4355 value: 'ok', 4356 action: () => { 4357 this.httpAuth = event.handler.isHttpAuthInfoSaved(); 4358 if (this.httpAuth == false) { 4359 webview.WebDataBase.saveHttpAuthCredentials( 4360 event.host, 4361 event.realm, 4362 "2222", 4363 "2222" 4364 ) 4365 event.handler.cancel(); 4366 } 4367 } 4368 }, 4369 cancel: () => { 4370 event.handler.cancel(); 4371 } 4372 }) 4373 } 4374 return true; 4375 }) 4376 } 4377 } 4378 } 4379 ``` 4380### onSslErrorEventReceive<sup>9+</sup> 4381 4382onSslErrorEventReceive(callback: Callback\<OnSslErrorEventReceiveEvent\>) 4383 4384Called to notify users when an SSL error occurs with a request for the main frame. 4385To include errors with requests for subframes, use the [OnSslErrorEvent](#onsslerrorevent12) API. 4386 4387**System capability**: SystemCapability.Web.Webview.Core 4388 4389**Parameters** 4390 4391| Name | Type | Mandatory | Description | 4392| ------ | ------ | ---- | --------------------- | 4393| callback | Callback\<[OnSslErrorEventReceiveEvent](#onsslerroreventreceiveevent12)\> | Yes| Callback invoked when the web page receives an SSL error.| 4394 4395**Example** 4396 4397 ```ts 4398 // xxx.ets 4399 import { webview } from '@kit.ArkWeb'; 4400 import { cert } from '@kit.DeviceCertificateKit'; 4401 4402 function LogCertInfo(certChainData : Array<Uint8Array> | undefined) { 4403 if (!(certChainData instanceof Array)) { 4404 console.log('failed, cert chain data type is not array'); 4405 return; 4406 } 4407 4408 for (let i = 0; i < certChainData.length; i++) { 4409 let encodeBlobData: cert.EncodingBlob = { 4410 data: certChainData[i], 4411 encodingFormat: cert.EncodingFormat.FORMAT_DER 4412 } 4413 cert.createX509Cert(encodeBlobData, (error, x509Cert) => { 4414 if (error) { 4415 console.error('Index : ' + i + ',createX509Cert failed, errCode: ' + error.code + ', errMsg: ' + error.message); 4416 } else { 4417 console.log('createX509Cert success'); 4418 console.log(ParseX509CertInfo(x509Cert)); 4419 } 4420 }); 4421 } 4422 return; 4423 } 4424 4425 function Uint8ArrayToString(dataArray: Uint8Array) { 4426 let dataString = ''; 4427 for (let i = 0; i < dataArray.length; i++) { 4428 dataString += String.fromCharCode(dataArray[i]); 4429 } 4430 return dataString; 4431 } 4432 4433 function ParseX509CertInfo(x509Cert: cert.X509Cert) { 4434 let res: string = 'getCertificate success, ' 4435 + 'issuer name = ' 4436 + Uint8ArrayToString(x509Cert.getIssuerName().data) + ', subject name = ' 4437 + Uint8ArrayToString(x509Cert.getSubjectName().data) + ', valid start = ' 4438 + x509Cert.getNotBeforeTime() 4439 + ', valid end = ' + x509Cert.getNotAfterTime(); 4440 return res; 4441 } 4442 4443 @Entry 4444 @Component 4445 struct WebComponent { 4446 controller: webview.WebviewController = new webview.WebviewController(); 4447 4448 build() { 4449 Column() { 4450 Web({ src: 'www.example.com', controller: this.controller }) 4451 .onSslErrorEventReceive((event) => { 4452 LogCertInfo(event.certChainData); 4453 AlertDialog.show({ 4454 title: 'onSslErrorEventReceive', 4455 message: 'text', 4456 primaryButton: { 4457 value: 'confirm', 4458 action: () => { 4459 event.handler.handleConfirm(); 4460 } 4461 }, 4462 secondaryButton: { 4463 value: 'cancel', 4464 action: () => { 4465 event.handler.handleCancel(); 4466 } 4467 }, 4468 cancel: () => { 4469 event.handler.handleCancel(); 4470 } 4471 }) 4472 }) 4473 } 4474 } 4475 } 4476 ``` 4477 4478### onSslErrorEvent<sup>12+</sup> 4479 4480onSslErrorEvent(callback: OnSslErrorEventCallback) 4481 4482Called to notify users when an SSL error occurs during the loading of resources (for the main frame and subframes). To handle SSL errors for requests for the main frame, use the **isMainFrame** field to distinguish. 4483 4484**System capability**: SystemCapability.Web.Webview.Core 4485 4486**Parameters** 4487 4488| Name | Type | Mandatory | Description | 4489| ------ | ------ | ---- | --------------------- | 4490| callback | [OnSslErrorEventCallback](#onsslerroreventcallback12) | Yes| Callback invoked when an SSL error occurs during resource loading.| 4491 4492**Example** 4493 4494 ```ts 4495 // xxx.ets 4496 import { webview } from '@kit.ArkWeb'; 4497 4498 @Entry 4499 @Component 4500 struct WebComponent { 4501 controller: webview.WebviewController = new webview.WebviewController(); 4502 4503 build() { 4504 Column() { 4505 Web({ src: 'www.example.com', controller: this.controller }) 4506 .onSslErrorEvent((event: SslErrorEvent) => { 4507 console.log("onSslErrorEvent url: " + event.url); 4508 console.log("onSslErrorEvent error: " + event.error); 4509 console.log("onSslErrorEvent originalUrl: " + event.originalUrl); 4510 console.log("onSslErrorEvent referrer: " + event.referrer); 4511 console.log("onSslErrorEvent isFatalError: " + event.isFatalError); 4512 console.log("onSslErrorEvent isMainFrame: " + event.isMainFrame); 4513 AlertDialog.show({ 4514 title: 'onSslErrorEvent', 4515 message: 'text', 4516 primaryButton: { 4517 value: 'confirm', 4518 action: () => { 4519 event.handler.handleConfirm(); 4520 } 4521 }, 4522 secondaryButton: { 4523 value: 'cancel', 4524 action: () => { 4525 event.handler.handleCancel(); 4526 } 4527 }, 4528 cancel: () => { 4529 event.handler.handleCancel(); 4530 } 4531 }) 4532 }) 4533 } 4534 } 4535 } 4536 ``` 4537 4538### onClientAuthenticationRequest<sup>9+</sup> 4539 4540onClientAuthenticationRequest(callback: Callback\<OnClientAuthenticationEvent\>) 4541 4542Called when an SSL client certificate request is received. 4543 4544**System capability**: SystemCapability.Web.Webview.Core 4545 4546**Parameters** 4547 4548| Name | Type | Mandatory | Description | 4549| ------ | ------ | ---- | --------------------- | 4550| callback | Callback\<[OnClientAuthenticationEvent](#onclientauthenticationevent12)\> | Yes| Callback invoked when an SSL client certificate is required from the user. | 4551 4552 **Example** 4553 4554 This example shows two-way authentication when interconnection with certificate management is not supported. 4555 4556 ```ts 4557 // xxx.ets API9 4558 import { webview } from '@kit.ArkWeb'; 4559 4560 @Entry 4561 @Component 4562 struct WebComponent { 4563 controller: webview.WebviewController = new webview.WebviewController(); 4564 4565 build() { 4566 Column() { 4567 Web({ src: 'www.example.com', controller: this.controller }) 4568 .onClientAuthenticationRequest((event) => { 4569 AlertDialog.show({ 4570 title: 'onClientAuthenticationRequest', 4571 message: 'text', 4572 primaryButton: { 4573 value: 'confirm', 4574 action: () => { 4575 event.handler.confirm("/system/etc/user.pk8", "/system/etc/chain-user.pem"); 4576 } 4577 }, 4578 secondaryButton: { 4579 value: 'cancel', 4580 action: () => { 4581 event.handler.cancel(); 4582 } 4583 }, 4584 cancel: () => { 4585 event.handler.ignore(); 4586 } 4587 }) 4588 }) 4589 } 4590 } 4591 } 4592 ``` 4593 4594 This example shows two-way authentication when interconnection with certificate management is supported. 4595 4596 1. Construct the singleton object **GlobalContext**. 4597 4598 ```ts 4599 // GlobalContext.ets 4600 export class GlobalContext { 4601 private constructor() {} 4602 private static instance: GlobalContext; 4603 private _objects = new Map<string, Object>(); 4604 4605 public static getContext(): GlobalContext { 4606 if (!GlobalContext.instance) { 4607 GlobalContext.instance = new GlobalContext(); 4608 } 4609 return GlobalContext.instance; 4610 } 4611 4612 getObject(value: string): Object | undefined { 4613 return this._objects.get(value); 4614 } 4615 4616 setObject(key: string, objectClass: Object): void { 4617 this._objects.set(key, objectClass); 4618 } 4619 } 4620 ``` 4621 4622 4623 2. Implement two-way authentication. 4624 4625 ```ts 4626 // xxx.ets API10 4627 import { webview } from '@kit.ArkWeb'; 4628 import { common, Want, bundleManager } from '@kit.AbilityKit'; 4629 import { BusinessError } from '@kit.BasicServicesKit'; 4630 import { GlobalContext } from '../GlobalContext'; 4631 4632 let uri = ""; 4633 4634 export default class CertManagerService { 4635 private static sInstance: CertManagerService; 4636 private authUri = ""; 4637 private appUid = ""; 4638 4639 public static getInstance(): CertManagerService { 4640 if (CertManagerService.sInstance == null) { 4641 CertManagerService.sInstance = new CertManagerService(); 4642 } 4643 return CertManagerService.sInstance; 4644 } 4645 4646 async grantAppPm(callback: (message: string) => void) { 4647 let message = ''; 4648 let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION; 4649 // Note: Replace com.example.myapplication with the actual application name. 4650 try { 4651 bundleManager.getBundleInfoForSelf(bundleFlags).then((data) => { 4652 console.info('getBundleInfoForSelf successfully. Data: %{public}s', JSON.stringify(data)); 4653 this.appUid = data.appInfo.uid.toString(); 4654 }).catch((err: BusinessError) => { 4655 console.error('getBundleInfoForSelf failed. Cause: %{public}s', err.message); 4656 }); 4657 } catch (err) { 4658 let message = (err as BusinessError).message; 4659 console.error('getBundleInfoForSelf failed: %{public}s', message); 4660 } 4661 4662 // Note: Add GlobalContext.getContext().setObject("AbilityContext", this.context) to the onCreate function in the MainAbility.ts file. 4663 let abilityContext = GlobalContext.getContext().getObject("AbilityContext") as common.UIAbilityContext 4664 await abilityContext.startAbilityForResult( 4665 { 4666 bundleName: "com.ohos.certmanager", 4667 abilityName: "MainAbility", 4668 uri: "requestAuthorize", 4669 parameters: { 4670 appUid: this.appUid, // Pass the UID of the requesting application. 4671 } 4672 } as Want) 4673 .then((data: common.AbilityResult) => { 4674 if (!data.resultCode && data.want) { 4675 if (data.want.parameters) { 4676 this.authUri = data.want.parameters.authUri as string; // Obtain the returned authUri after successful authorization. 4677 } 4678 } 4679 }) 4680 message += "after grantAppPm authUri: " + this.authUri; 4681 uri = this.authUri; 4682 callback(message) 4683 } 4684 } 4685 4686 @Entry 4687 @Component 4688 struct WebComponent { 4689 controller: webview.WebviewController = new webview.WebviewController(); 4690 @State message: string = 'Hello World' // message is used for debugging and observation. 4691 certManager = CertManagerService.getInstance(); 4692 4693 build() { 4694 Row() { 4695 Column() { 4696 Row() { 4697 // Step 1: Perform authorization to obtain the URI. 4698 Button('GrantApp') 4699 .onClick(() => { 4700 this.certManager.grantAppPm((data) => { 4701 this.message = data; 4702 }); 4703 }) 4704 // Step 2: After the authorization, in two-way authentication, the onClientAuthenticationRequest callback is used to send the URI to the web server for authentication. 4705 Button("ClientCertAuth") 4706 .onClick(() => { 4707 this.controller.loadUrl('https://www.example2.com'); // Server website that supports two-way authentication. 4708 }) 4709 } 4710 4711 Web({ src: 'https://www.example1.com', controller: this.controller }) 4712 .fileAccess(true) 4713 .javaScriptAccess(true) 4714 .domStorageAccess(true) 4715 .onlineImageAccess(true) 4716 4717 .onClientAuthenticationRequest((event) => { 4718 AlertDialog.show({ 4719 title: 'ClientAuth', 4720 message: 'Text', 4721 confirm: { 4722 value: 'Confirm', 4723 action: () => { 4724 event.handler.confirm(uri); 4725 } 4726 }, 4727 cancel: () => { 4728 event.handler.cancel(); 4729 } 4730 }) 4731 }) 4732 } 4733 } 4734 .width('100%') 4735 .height('100%') 4736 } 4737 } 4738 ``` 4739 4740### onPermissionRequest<sup>9+</sup> 4741 4742onPermissionRequest(callback: Callback\<OnPermissionRequestEvent\>) 4743 4744Called when a permission request is received. To call this API, you need to declare the **ohos.permission.CAMERA** and **ohos.permission.MICROPHONE** permissions. 4745 4746**System capability**: SystemCapability.Web.Webview.Core 4747 4748**Parameters** 4749 4750| Name | Type | Mandatory | Description | 4751| ------ | ------ | ---- | --------------------- | 4752| callback | Callback\<[OnPermissionRequestEvent](#onpermissionrequestevent12)\> | Yes| Callback invoked when a permission request is received.| 4753 4754**Example** 4755 4756 ```ts 4757 // xxx.ets 4758 import { webview } from '@kit.ArkWeb'; 4759 import { BusinessError } from '@kit.BasicServicesKit'; 4760 import { abilityAccessCtrl } from '@kit.AbilityKit'; 4761 4762 @Entry 4763 @Component 4764 struct WebComponent { 4765 controller: webview.WebviewController = new webview.WebviewController(); 4766 4767 aboutToAppear() { 4768 // Enable web frontend page debugging. 4769 webview.WebviewController.setWebDebuggingAccess(true); 4770 let atManager = abilityAccessCtrl.createAtManager(); 4771 atManager.requestPermissionsFromUser(getContext(this), ['ohos.permission.CAMERA', 'ohos.permission.MICROPHONE']) 4772 .then((data) => { 4773 console.info('data:' + JSON.stringify(data)); 4774 console.info('data permissions:' + data.permissions); 4775 console.info('data authResults:' + data.authResults); 4776 }).catch((error: BusinessError) => { 4777 console.error(`Failed to request permissions from user. Code is ${error.code}, message is ${error.message}`); 4778 }) 4779 } 4780 4781 build() { 4782 Column() { 4783 Web({ src: $rawfile('index.html'), controller: this.controller }) 4784 .onPermissionRequest((event) => { 4785 if (event) { 4786 AlertDialog.show({ 4787 title: 'title', 4788 message: 'text', 4789 primaryButton: { 4790 value: 'deny', 4791 action: () => { 4792 event.request.deny(); 4793 } 4794 }, 4795 secondaryButton: { 4796 value: 'onConfirm', 4797 action: () => { 4798 event.request.grant(event.request.getAccessibleResource()); 4799 } 4800 }, 4801 cancel: () => { 4802 event.request.deny(); 4803 } 4804 }) 4805 } 4806 }) 4807 } 4808 } 4809 } 4810 ``` 4811 4812 HTML file to be loaded: 4813 ```html 4814 <!-- index.html --> 4815 <!DOCTYPE html> 4816 <html> 4817 <head> 4818 <meta charset="UTF-8"> 4819 </head> 4820 <body> 4821 <video id="video" width="500px" height="500px" autoplay="autoplay"></video> 4822 <canvas id="canvas" width="500px" height="500px"></canvas> 4823 <br> 4824 <input type="button" title="HTML5 Camera" value="Enable Camera" onclick="getMedia()"/> 4825 <script> 4826 function getMedia() 4827 { 4828 let constraints = { 4829 video: {width: 500, height: 500}, 4830 audio: true 4831 }; 4832 // Obtain the video camera area. 4833 let video = document.getElementById("video"); 4834 // Returned Promise object 4835 let promise = navigator.mediaDevices.getUserMedia(constraints); 4836 // then() is asynchronous. Invoke the MediaStream object as a parameter. 4837 promise.then(function (MediaStream) { 4838 video.srcObject = MediaStream; 4839 video.play(); 4840 }); 4841 } 4842 </script> 4843 </body> 4844 </html> 4845 ``` 4846 4847### onContextMenuShow<sup>9+</sup> 4848 4849onContextMenuShow(callback: Callback\<OnContextMenuShowEvent, boolean\>) 4850 4851Called when a context menu is displayed after the user clicks the right mouse button or long presses a specific element, such as an image or a link. 4852 4853**System capability**: SystemCapability.Web.Webview.Core 4854 4855**Parameters** 4856 4857| Name | Type | Mandatory | Description | 4858| ------ | ------ | ---- | --------------------- | 4859| callback | Callback\<[OnContextMenuShowEvent](#oncontextmenushowevent12), boolean\> | Yes| Callback invoked during a call to allow for the display of a custom context menu.<br>Return value: boolean<br> The value **true** means a valid custom menu, and **false** means an invalid custom menu. | 4860 4861**Example** 4862 4863 ```ts 4864 // xxx.ets 4865 import { webview } from '@kit.ArkWeb'; 4866 import { pasteboard } from '@kit.BasicServicesKit'; 4867 4868 const TAG = 'ContextMenu'; 4869 4870 @Entry 4871 @Component 4872 struct WebComponent { 4873 controller: webview.WebviewController = new webview.WebviewController(); 4874 private result: WebContextMenuResult | undefined = undefined; 4875 @State linkUrl: string = ''; 4876 @State offsetX: number = 0; 4877 @State offsetY: number = 0; 4878 @State showMenu: boolean = false; 4879 4880 @Builder 4881 // Build and trigger a custom menu. 4882 MenuBuilder() { 4883 // A component that is used to present a vertical list of items to the user. 4884 Menu() { 4885 // A component that is used to represent an item in a menu. 4886 MenuItem({ 4887 content: 'Copy Image', 4888 }) 4889 .width(100) 4890 .height(50) 4891 .onClick(() => { 4892 this.result?.copyImage(); 4893 this.showMenu = false; 4894 }) 4895 MenuItem({ 4896 content: 'Cut', 4897 }) 4898 .width(100) 4899 .height(50) 4900 .onClick(() => { 4901 this.result?.cut(); 4902 this.showMenu = false; 4903 }) 4904 MenuItem({ 4905 content: 'Copy', 4906 }) 4907 .width(100) 4908 .height(50) 4909 .onClick(() => { 4910 this.result?.copy(); 4911 this.showMenu = false; 4912 }) 4913 MenuItem({ 4914 content: 'Paste', 4915 }) 4916 .width(100) 4917 .height(50) 4918 .onClick(() => { 4919 this.result?.paste(); 4920 this.showMenu = false; 4921 }) 4922 MenuItem({ 4923 content: 'Copy Link', 4924 }) 4925 .width(100) 4926 .height(50) 4927 .onClick(() => { 4928 let pasteData = pasteboard.createData('text/plain', this.linkUrl); 4929 pasteboard.getSystemPasteboard().setData(pasteData, (error) => { 4930 if (error) { 4931 return; 4932 } 4933 }) 4934 this.showMenu = false; 4935 }) 4936 MenuItem({ 4937 content: 'Select All', 4938 }) 4939 .width(100) 4940 .height(50) 4941 .onClick(() => { 4942 this.result?.selectAll(); 4943 this.showMenu = false; 4944 }) 4945 } 4946 .width(150) 4947 .height(300) 4948 } 4949 4950 build() { 4951 Column() { 4952 Web({ src: $rawfile("index.html"), controller: this.controller }) 4953 // Trigger a custom dialog box. 4954 .onContextMenuShow((event) => { 4955 if (event) { 4956 this.result = event.result 4957 console.info("x coord = " + event.param.x()); 4958 console.info("link url = " + event.param.getLinkUrl()); 4959 this.linkUrl = event.param.getLinkUrl(); 4960 } 4961 console.info(TAG, `x: ${this.offsetX}, y: ${this.offsetY}`); 4962 this.showMenu = true; 4963 this.offsetX = 0; 4964 this.offsetY = Math.max(px2vp(event?.param.y() ?? 0) - 0, 0); 4965 return true; 4966 }) 4967 .bindPopup(this.showMenu, 4968 { 4969 builder: this.MenuBuilder(), 4970 enableArrow: false, 4971 placement: Placement.LeftTop, 4972 offset: { x: this.offsetX, y: this.offsetY }, 4973 mask: false, 4974 onStateChange: (e) => { 4975 if (!e.isVisible) { 4976 this.showMenu = false; 4977 this.result!.closeContextMenu(); 4978 } 4979 } 4980 }) 4981 } 4982 } 4983 } 4984 ``` 4985 4986 HTML file to be loaded: 4987 ```html 4988 <!-- index.html --> 4989 <!DOCTYPE html> 4990 <html lang="en"> 4991 <body> 4992 <h1>onContextMenuShow</h1> 4993 <a href="http://www.example.com" style="font-size:27px">URL www.example.com</a> 4994 // Place any image in the rawfile directory and name it example.png. 4995 <div><img src="example.png"></div> 4996 <p>Right-click text to display the context menu</p> 4997 </body> 4998 </html> 4999 ``` 5000 5001### onContextMenuHide<sup>11+</sup> 5002 5003onContextMenuHide(callback: OnContextMenuHideCallback) 5004 5005Called when a context menu is hidden after the user clicks the right mouse button or long presses a specific element, such as an image or a link. 5006 5007**System capability**: SystemCapability.Web.Webview.Core 5008 5009**Parameters** 5010 5011| Name | Type | Mandatory | Description | 5012| ------ | ------ | ---- | --------------------- | 5013| callback | [OnContextMenuHideCallback](#oncontextmenuhidecallback11) | Yes| Parameters related to the context menu. | 5014 5015**Example** 5016 5017 ```ts 5018 // xxx.ets 5019 import { webview } from '@kit.ArkWeb'; 5020 5021 @Entry 5022 @Component 5023 struct WebComponent { 5024 controller: webview.WebviewController = new webview.WebviewController(); 5025 5026 build() { 5027 Column() { 5028 Web({ src: 'www.example.com', controller: this.controller }) 5029 .onContextMenuHide(() => { 5030 console.log("onContextMenuHide callback"); 5031 }) 5032 } 5033 } 5034 } 5035 ``` 5036 5037### onScroll<sup>9+</sup> 5038 5039onScroll(callback: Callback\<OnScrollEvent\>) 5040 5041Called when the scrollbar of the page scrolls. 5042 5043**System capability**: SystemCapability.Web.Webview.Core 5044 5045**Parameters** 5046 5047| Name | Type | Mandatory | Description | 5048| ------ | ------ | ---- | --------------------- | 5049| callback | Callback\<[OnScrollEvent](#onscrollevent12)\> | Yes| Callback invoked when the scrollbar scrolls to a specified position.| 5050 5051**Example** 5052 5053 ```ts 5054 // xxx.ets 5055 import { webview } from '@kit.ArkWeb'; 5056 5057 @Entry 5058 @Component 5059 struct WebComponent { 5060 controller: webview.WebviewController = new webview.WebviewController(); 5061 5062 build() { 5063 Column() { 5064 Web({ src: 'www.example.com', controller: this.controller }) 5065 .onScroll((event) => { 5066 console.info("x = " + event.xOffset); 5067 console.info("y = " + event.yOffset); 5068 }) 5069 } 5070 } 5071 } 5072 ``` 5073 5074### onGeolocationShow 5075 5076onGeolocationShow(callback: Callback\<OnGeolocationShowEvent\>) 5077 5078Called when a request to obtain the geolocation information is received. 5079 5080**System capability**: SystemCapability.Web.Webview.Core 5081 5082**Parameters** 5083 5084| Name | Type | Mandatory | Description | 5085| ------ | ------ | ---- | --------------------- | 5086| callback | Callback\<[OnGeolocationShowEvent](#ongeolocationshowevent12)\> | Yes| Callback invoked when a request to obtain the geolocation information is received. | 5087 5088**Example** 5089 5090 ```ts 5091 // xxx.ets 5092 import { webview } from '@kit.ArkWeb'; 5093 5094 @Entry 5095 @Component 5096 struct WebComponent { 5097 controller: webview.WebviewController = new webview.WebviewController(); 5098 5099 build() { 5100 Column() { 5101 Web({ src: $rawfile('index.html'), controller: this.controller }) 5102 .geolocationAccess(true) 5103 .onGeolocationShow((event) => { 5104 if (event) { 5105 AlertDialog.show({ 5106 title: 'title', 5107 message: 'text', 5108 confirm: { 5109 value: 'onConfirm', 5110 action: () => { 5111 event.geolocation.invoke(event.origin, true, true); 5112 } 5113 }, 5114 cancel: () => { 5115 event.geolocation.invoke(event.origin, false, true); 5116 } 5117 }) 5118 } 5119 }) 5120 } 5121 } 5122 } 5123 ``` 5124 5125 HTML file to be loaded: 5126 ```html 5127 <!DOCTYPE html> 5128 <html> 5129 <body> 5130 <p id="locationInfo">Location information</p> 5131 <button onclick="getLocation()">Get Location</button> 5132 <script> 5133 var locationInfo=document.getElementById("locationInfo"); 5134 function getLocation(){ 5135 if (navigator.geolocation) { 5136 <!-- Access to the device location by the frontend page --> 5137 navigator.geolocation.getCurrentPosition(showPosition); 5138 } 5139 } 5140 function showPosition(position){ 5141 locationInfo.innerHTML="Latitude: " + position.coords.latitude + "<br />Longitude: " + position.coords.longitude; 5142 } 5143 </script> 5144 </body> 5145 </html> 5146 ``` 5147 5148### onGeolocationHide 5149 5150onGeolocationHide(callback: () => void) 5151 5152Called to notify the user that the request for obtaining the geolocation information received when [onGeolocationShow](#ongeolocationshow) is called has been canceled. 5153 5154**System capability**: SystemCapability.Web.Webview.Core 5155 5156**Parameters** 5157 5158| Name | Type | Mandatory | Description | 5159| ------ | ------ | ---- | --------------------- | 5160| callback | () => void | Yes| Callback invoked when the request for obtaining geolocation information has been canceled. | 5161 5162**Example** 5163 5164 ```ts 5165 // xxx.ets 5166 import { webview } from '@kit.ArkWeb'; 5167 5168 @Entry 5169 @Component 5170 struct WebComponent { 5171 controller: webview.WebviewController = new webview.WebviewController(); 5172 5173 build() { 5174 Column() { 5175 Web({ src: 'www.example.com', controller: this.controller }) 5176 .geolocationAccess(true) 5177 .onGeolocationHide(() => { 5178 console.log("onGeolocationHide..."); 5179 }) 5180 } 5181 } 5182 } 5183 ``` 5184 5185### onFullScreenEnter<sup>9+</sup> 5186 5187onFullScreenEnter(callback: OnFullScreenEnterCallback) 5188 5189Called when the **Web** component enters full screen mode. 5190 5191**System capability**: SystemCapability.Web.Webview.Core 5192 5193**Parameters** 5194 5195| Name | Type | Mandatory | Description | 5196| ------ | ------ | ---- | --------------------- | 5197| callback | [OnFullScreenEnterCallback](#onfullscreenentercallback12) | Yes| Callback invoked when the **Web** component enters full screen mode.| 5198 5199**Example** 5200 5201 ```ts 5202 // xxx.ets 5203 import { webview } from '@kit.ArkWeb'; 5204 5205 @Entry 5206 @Component 5207 struct WebComponent { 5208 controller: webview.WebviewController = new webview.WebviewController(); 5209 handler: FullScreenExitHandler | null = null; 5210 5211 build() { 5212 Column() { 5213 Web({ src: 'www.example.com', controller: this.controller }) 5214 .onFullScreenEnter((event) => { 5215 console.log("onFullScreenEnter videoWidth: " + event.videoWidth + 5216 ", videoHeight: " + event.videoHeight); 5217 // The application can proactively exit fullscreen mode by calling this.handler.exitFullScreen(). 5218 this.handler = event.handler; 5219 }) 5220 } 5221 } 5222 } 5223 ``` 5224 5225### onFullScreenExit<sup>9+</sup> 5226 5227onFullScreenExit(callback: () => void) 5228 5229Called when the **Web** component exits full screen mode. 5230 5231**System capability**: SystemCapability.Web.Webview.Core 5232 5233**Parameters** 5234 5235| Name | Type | Mandatory | Description | 5236| ------ | ------ | ---- | --------------------- | 5237| callback | () => void | Yes| Callback invoked when the component exits full screen mode.| 5238 5239**Example** 5240 5241 ```ts 5242 // xxx.ets 5243 import { webview } from '@kit.ArkWeb'; 5244 5245 @Entry 5246 @Component 5247 struct WebComponent { 5248 controller: webview.WebviewController = new webview.WebviewController(); 5249 handler: FullScreenExitHandler | null = null; 5250 5251 build() { 5252 Column() { 5253 Web({ src: 'www.example.com', controller: this.controller }) 5254 .onFullScreenExit(() => { 5255 console.log("onFullScreenExit...") 5256 if (this.handler) { 5257 this.handler.exitFullScreen(); 5258 } 5259 }) 5260 .onFullScreenEnter((event) => { 5261 this.handler = event.handler; 5262 }) 5263 } 5264 } 5265 } 5266 ``` 5267 5268### onWindowNew<sup>9+</sup> 5269 5270onWindowNew(callback: Callback\<OnWindowNewEvent\>) 5271 5272Called to notify the user of a new window creation request, when **multiWindowAccess** is enabled. 5273If the **event.handler.setWebController** API is not called, the render process will be blocked. 5274If no new window is created, set the value of event.handler.setWebController to null to notify the Web component that no new window is created. 5275 5276The new window should not cover the original **Web** component, otherwise, users may be misled to other websites. If the application displays the URL of the home page, ensure that the URL of the new window is displayed in a similar way. Otherwise, new windows should be prohibited. 5277 5278Note that there is no reliable method to determine which page requests a new window. The request may be from a third-party iframe. 5279 5280**System capability**: SystemCapability.Web.Webview.Core 5281 5282**Parameters** 5283 5284| Name | Type | Mandatory | Description | 5285| ------ | ------ | ---- | --------------------- | 5286| callback | Callback\<[OnWindowNewEvent](#onwindownewevent12)\> | Yes| Callback invoked when the web page requests the user to create a window. | 5287 5288**Example** 5289 5290 ```ts 5291 // xxx.ets 5292 import { webview } from '@kit.ArkWeb'; 5293 5294 // There are two Web components on the same page. When the WebComponent object opens a new window, the NewWebViewComp object is displayed. 5295 @CustomDialog 5296 struct NewWebViewComp { 5297 controller?: CustomDialogController; 5298 webviewController1: webview.WebviewController = new webview.WebviewController(); 5299 5300 build() { 5301 Column() { 5302 Web({ src: "", controller: this.webviewController1 }) 5303 .javaScriptAccess(true) 5304 .multiWindowAccess(false) 5305 .onWindowExit(() => { 5306 console.info("NewWebViewComp onWindowExit"); 5307 if (this.controller) { 5308 this.controller.close(); 5309 } 5310 }) 5311 } 5312 } 5313 } 5314 5315 @Entry 5316 @Component 5317 struct WebComponent { 5318 controller: webview.WebviewController = new webview.WebviewController(); 5319 dialogController: CustomDialogController | null = null; 5320 5321 build() { 5322 Column() { 5323 Web({ src: 'www.example.com', controller: this.controller }) 5324 .javaScriptAccess(true) 5325 // MultiWindowAccess needs to be enabled. 5326 .multiWindowAccess(true) 5327 .allowWindowOpenMethod(true) 5328 .onWindowNew((event) => { 5329 if (this.dialogController) { 5330 this.dialogController.close(); 5331 } 5332 let popController: webview.WebviewController = new webview.WebviewController(); 5333 this.dialogController = new CustomDialogController({ 5334 builder: NewWebViewComp({ webviewController1: popController }) 5335 }) 5336 this.dialogController.open(); 5337 // Return the WebviewController object corresponding to the new window to the Web kernel. 5338 // If the event.handler.setWebController API is not called, the render process will be blocked. 5339 // If no new window is created, set the value of event.handler.setWebController to null to notify the Web component that no new window is created. 5340 event.handler.setWebController(popController); 5341 }) 5342 } 5343 } 5344 } 5345 ``` 5346 5347### onWindowExit<sup>9+</sup> 5348 5349onWindowExit(callback: () => void) 5350 5351Called when this window is closed. This API works in the same way as [onWindowNew](#onwindownew9). For security, applications should notify users that the pages they interact with are closed. 5352 5353**System capability**: SystemCapability.Web.Webview.Core 5354 5355**Parameters** 5356 5357| Name | Type | Mandatory | Description | 5358| ------ | ------ | ---- | --------------------- | 5359| callback | () => void | Yes| Callback invoked when the window is closed.| 5360 5361**Example** 5362 5363 ```ts 5364 // xxx.ets 5365 import { webview } from '@kit.ArkWeb'; 5366 5367 @Entry 5368 @Component 5369 struct WebComponent { 5370 controller: webview.WebviewController = new webview.WebviewController(); 5371 5372 build() { 5373 Column() { 5374 Web({ src: 'www.example.com', controller: this.controller }) 5375 .onWindowExit(() => { 5376 console.log("onWindowExit..."); 5377 }) 5378 } 5379 } 5380 } 5381 ``` 5382 5383### onSearchResultReceive<sup>9+</sup> 5384 5385onSearchResultReceive(callback: Callback\<OnSearchResultReceiveEvent\>) 5386 5387Called to notify the caller of the search result on the web page. 5388 5389**System capability**: SystemCapability.Web.Webview.Core 5390 5391**Parameters** 5392 5393| Name | Type | Mandatory | Description | 5394| ------ | ------ | ---- | --------------------- | 5395| callback | Callback\<[OnSearchResultReceiveEvent](#onsearchresultreceiveevent12)\> | Yes| Callback invoked to notify the caller of the search result on the web page. | 5396 5397**Example** 5398 5399 ```ts 5400 // xxx.ets 5401 import { webview } from '@kit.ArkWeb'; 5402 5403 @Entry 5404 @Component 5405 struct WebComponent { 5406 controller: webview.WebviewController = new webview.WebviewController(); 5407 5408 build() { 5409 Column() { 5410 Web({ src: 'www.example.com', controller: this.controller }) 5411 .onSearchResultReceive(ret => { 5412 if (ret) { 5413 console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal + 5414 "[total]" + ret.numberOfMatches + "[isDone]" + ret.isDoneCounting); 5415 } 5416 }) 5417 } 5418 } 5419 } 5420 ``` 5421 5422### onDataResubmitted<sup>9+</sup> 5423 5424onDataResubmitted(callback: Callback\<OnDataResubmittedEvent\>) 5425 5426Called when the web form data can be resubmitted. 5427 5428**System capability**: SystemCapability.Web.Webview.Core 5429 5430**Parameters** 5431 5432| Name | Type | Mandatory | Description | 5433| ------ | ------ | ---- | --------------------- | 5434| callback | Callback\<[OnDataResubmittedEvent](#ondataresubmittedevent12)\> | Yes| Callback invoked when the web form data can be resubmitted.| 5435 5436**Example** 5437 5438 ```ts 5439 // xxx.ets 5440 import { webview } from '@kit.ArkWeb'; 5441 import { BusinessError } from '@kit.BasicServicesKit'; 5442 5443 @Entry 5444 @Component 5445 struct WebComponent { 5446 controller: webview.WebviewController = new webview.WebviewController(); 5447 5448 build() { 5449 Column() { 5450 // After you click Submit on the web page, you can click Refresh to trigger the function again. 5451 Button('refresh') 5452 .onClick(() => { 5453 try { 5454 this.controller.refresh(); 5455 } catch (error) { 5456 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5457 } 5458 }) 5459 Web({ src: $rawfile('index.html'), controller: this.controller }) 5460 .onDataResubmitted((event) => { 5461 console.log('onDataResubmitted'); 5462 event.handler.resend(); 5463 }) 5464 } 5465 } 5466 } 5467 ``` 5468 5469 HTML file to be loaded: 5470 ```html 5471 <!-- index.html --> 5472 <!DOCTYPE html> 5473 <html> 5474 <head> 5475 <meta charset="utf-8"> 5476 </head> 5477 <body> 5478 <form action="http://httpbin.org/post" method="post"> 5479 <input type="text" name="username"> 5480 <input type="submit" name="Submit"> 5481 </form> 5482 </body> 5483 </html> 5484 ``` 5485 5486### onPageVisible<sup>9+</sup> 5487 5488onPageVisible(callback: Callback\<OnPageVisibleEvent\>) 5489 5490Called when the old page is not displayed and the new page is about to be visible. 5491 5492**System capability**: SystemCapability.Web.Webview.Core 5493 5494**Parameters** 5495 5496| Name | Type | Mandatory | Description | 5497| ------ | ------ | ---- | --------------------- | 5498| callback | Callback\<[OnPageVisibleEvent](#onpagevisibleevent12)\> | Yes| Callback invoked when the old page is not displayed and the new page is about to be visible.| 5499 5500**Example** 5501 5502 ```ts 5503 // xxx.ets 5504 import { webview } from '@kit.ArkWeb'; 5505 5506 @Entry 5507 @Component 5508 struct WebComponent { 5509 controller: webview.WebviewController = new webview.WebviewController(); 5510 5511 build() { 5512 Column() { 5513 Web({ src: 'www.example.com', controller: this.controller }) 5514 .onPageVisible((event) => { 5515 console.log('onPageVisible url:' + event.url); 5516 }) 5517 } 5518 } 5519 } 5520 ``` 5521 5522### onInterceptKeyEvent<sup>9+</sup> 5523 5524onInterceptKeyEvent(callback: (event: KeyEvent) => boolean) 5525 5526Called when the key event is intercepted and before it is consumed by the webview. 5527 5528**System capability**: SystemCapability.Web.Webview.Core 5529 5530**Parameters** 5531 5532| Name | Type | Mandatory | Description | 5533| ------ | ------ | ---- | --------------------- | 5534| callback | (event:[KeyEvent](../apis-arkui/arkui-ts/ts-universal-events-key.md#keyevent)) => boolean| Yes| Key event that is triggered. Return value: Whether to continue to transfer the key event to the webview kernel.| 5535 5536**Example** 5537 5538 ```ts 5539 // xxx.ets 5540 import { webview } from '@kit.ArkWeb'; 5541 5542 @Entry 5543 @Component 5544 struct WebComponent { 5545 controller: webview.WebviewController = new webview.WebviewController(); 5546 5547 build() { 5548 Column() { 5549 Web({ src: 'www.example.com', controller: this.controller }) 5550 .onInterceptKeyEvent((event) => { 5551 if (event.keyCode == 2017 || event.keyCode == 2018) { 5552 console.info(`onInterceptKeyEvent get event.keyCode ${event.keyCode}`); 5553 return true; 5554 } 5555 return false; 5556 }) 5557 } 5558 } 5559 } 5560 ``` 5561 5562### onTouchIconUrlReceived<sup>9+</sup> 5563 5564onTouchIconUrlReceived(callback: Callback\<OnTouchIconUrlReceivedEvent\>) 5565 5566Called when an apple-touch-icon URL is received. 5567 5568**System capability**: SystemCapability.Web.Webview.Core 5569 5570**Parameters** 5571 5572| Name | Type | Mandatory | Description | 5573| ------ | ------ | ---- | --------------------- | 5574| callback | Callback\<[OnTouchIconUrlReceivedEvent](#ontouchiconurlreceivedevent12)\> | Yes| Callback invoked when an apple-touch-icon URL is received.| 5575 5576**Example** 5577 5578 ```ts 5579 // xxx.ets 5580 import { webview } from '@kit.ArkWeb'; 5581 5582 @Entry 5583 @Component 5584 struct WebComponent { 5585 controller: webview.WebviewController = new webview.WebviewController(); 5586 5587 build() { 5588 Column() { 5589 Web({ src: 'www.baidu.com', controller: this.controller }) 5590 .onTouchIconUrlReceived((event) => { 5591 console.log('onTouchIconUrlReceived:' + JSON.stringify(event)); 5592 }) 5593 } 5594 } 5595 } 5596 ``` 5597 5598### onFaviconReceived<sup>9+</sup> 5599 5600onFaviconReceived(callback: Callback\<OnFaviconReceivedEvent\>) 5601 5602Called when this web page receives a new favicon. 5603 5604**System capability**: SystemCapability.Web.Webview.Core 5605 5606**Parameters** 5607 5608| Name | Type | Mandatory | Description | 5609| ------ | ------ | ---- | --------------------- | 5610| callback | Callback\<[OnFaviconReceivedEvent](#onfaviconreceivedevent12)\> | Yes| Callback invoked when the current web page receives a new favicon.| 5611 5612**Example** 5613 5614 ```ts 5615 // xxx.ets 5616 import { webview } from '@kit.ArkWeb'; 5617 import { image } from '@kit.ImageKit'; 5618 5619 @Entry 5620 @Component 5621 struct WebComponent { 5622 controller: webview.WebviewController = new webview.WebviewController(); 5623 @State icon: image.PixelMap | undefined = undefined; 5624 5625 build() { 5626 Column() { 5627 Web({ src: 'www.example.com', controller: this.controller }) 5628 .onFaviconReceived((event) => { 5629 console.log('onFaviconReceived'); 5630 this.icon = event.favicon; 5631 }) 5632 } 5633 } 5634 } 5635 ``` 5636 5637### onAudioStateChanged<sup>10+</sup> 5638 5639onAudioStateChanged(callback: Callback\<OnAudioStateChangedEvent\>) 5640 5641Called when the audio playback status on the web page changes. 5642 5643**System capability**: SystemCapability.Web.Webview.Core 5644 5645**Parameters** 5646 5647| Name | Type | Mandatory | Description | 5648| ------ | ------ | ---- | --------------------- | 5649| callback | Callback\<[OnAudioStateChangedEvent](#onaudiostatechangedevent12)\> | Yes| Callback invoked when the audio playback status on the web page changes.| 5650 5651**Example** 5652 5653 ```ts 5654 // xxx.ets 5655 import { webview } from '@kit.ArkWeb'; 5656 5657 @Entry 5658 @Component 5659 struct WebComponent { 5660 controller: webview.WebviewController = new webview.WebviewController(); 5661 @State playing: boolean = false; 5662 5663 build() { 5664 Column() { 5665 Web({ src: 'www.example.com', controller: this.controller }) 5666 .onAudioStateChanged(event => { 5667 this.playing = event.playing; 5668 console.debug('onAudioStateChanged playing: ' + this.playing); 5669 }) 5670 } 5671 } 5672 } 5673 ``` 5674 5675### onFirstContentfulPaint<sup>10+</sup> 5676 5677 onFirstContentfulPaint(callback: Callback\<OnFirstContentfulPaintEvent\>) 5678 5679Called when the first content paint occurs on the web page. 5680 5681**System capability**: SystemCapability.Web.Webview.Core 5682 5683**Parameters** 5684 5685| Name | Type | Mandatory | Description | 5686| ------ | ------ | ---- | --------------------- | 5687| callback | Callback\<[OnFirstContentfulPaintEvent](#onfirstcontentfulpaintevent12)\> | Yes| Callback invoked when the first content paint occurs on the web page. | 5688 5689**Example** 5690 5691 ```ts 5692 // xxx.ets 5693 import { webview } from '@kit.ArkWeb'; 5694 5695 @Entry 5696 @Component 5697 struct WebComponent { 5698 controller: webview.WebviewController = new webview.WebviewController(); 5699 5700 build() { 5701 Column() { 5702 Web({ src: 'www.example.com', controller: this.controller }) 5703 .onFirstContentfulPaint(event => { 5704 if (event) { 5705 console.log("onFirstContentfulPaint:" + "[navigationStartTick]:" + 5706 event.navigationStartTick + ", [firstContentfulPaintMs]:" + 5707 event.firstContentfulPaintMs); 5708 } 5709 }) 5710 } 5711 } 5712 } 5713 ``` 5714 5715### onFirstMeaningfulPaint<sup>12+</sup> 5716 5717onFirstMeaningfulPaint(callback: [OnFirstMeaningfulPaintCallback](#onfirstmeaningfulpaintcallback12)) 5718 5719Called when the first meaningful paint occurs on the web page. 5720 5721**System capability**: SystemCapability.Web.Webview.Core 5722 5723**Parameters** 5724 5725| Name | Type | Mandatory | Description | 5726| ------ | ------ | ---- | --------------------- | 5727| callback | [OnFirstMeaningfulPaintCallback](#onfirstmeaningfulpaintcallback12) | Yes| Callback invoked when the First Meaningful Paint occurs on the web page.| 5728 5729**Example** 5730 5731 ```ts 5732 // xxx.ets 5733 import { webview } from '@kit.ArkWeb'; 5734 5735 @Entry 5736 @Component 5737 struct WebComponent { 5738 controller: webview.WebviewController = new webview.WebviewController(); 5739 5740 build() { 5741 Column() { 5742 Web({ src: 'www.example.com', controller: this.controller }) 5743 .onFirstMeaningfulPaint((details) => { 5744 console.log("onFirstMeaningfulPaint: [navigationStartTime]= " + details.navigationStartTime + 5745 ", [firstMeaningfulPaintTime]=" + details.firstMeaningfulPaintTime); 5746 }) 5747 } 5748 } 5749 } 5750 ``` 5751 5752### onLargestContentfulPaint<sup>12+</sup> 5753 5754onLargestContentfulPaint(callback: [OnLargestContentfulPaintCallback](#onlargestcontentfulpaintcallback12)) 5755 5756Called when the largest content paint occurs on the web page. 5757 5758**System capability**: SystemCapability.Web.Webview.Core 5759 5760**Parameters** 5761 5762| Name | Type | Mandatory | Description | 5763| ------ | ------ | ---- | --------------------- | 5764| callback | [OnLargestContentfulPaintCallback](#onlargestcontentfulpaintcallback12) | Yes| Callback invoked when the largest content paint occurs on the web page.| 5765 5766**Example** 5767 5768 ```ts 5769 // xxx.ets 5770 import { webview } from '@kit.ArkWeb'; 5771 5772 @Entry 5773 @Component 5774 struct WebComponent { 5775 controller: webview.WebviewController = new webview.WebviewController(); 5776 5777 build() { 5778 Column() { 5779 Web({ src: 'www.example.com', controller: this.controller }) 5780 .onLargestContentfulPaint((details) => { 5781 console.log("onLargestContentfulPaint: [navigationStartTime]= " + details.navigationStartTime + 5782 ", [largestImagePaintTime]=" + details.largestImagePaintTime + 5783 ", [largestTextPaintTime]=" + details.largestTextPaintTime + 5784 ", [largestImageLoadStartTime]=" + details.largestImageLoadStartTime + 5785 ", [largestImageLoadEndTime]=" + details.largestImageLoadEndTime + 5786 ", [imageBPP]=" + details.imageBPP); 5787 }) 5788 } 5789 } 5790 } 5791 ``` 5792 5793### onLoadIntercept<sup>10+</sup> 5794 5795onLoadIntercept(callback: Callback\<OnLoadInterceptEvent, boolean\>) 5796 5797Called when the **Web** component is about to access a URL. This API is used to determine whether to block the access, which is allowed by default. 5798 5799**System capability**: SystemCapability.Web.Webview.Core 5800 5801**Parameters** 5802 5803| Name | Type | Mandatory | Description | 5804| ------ | ------ | ---- | --------------------- | 5805| callback | Callback\<[OnLoadInterceptEvent](#onloadinterceptevent12), boolean\> | Yes| Callback invoked when the **Web** component is about to access a URL.<br>Return value: boolean<br> Returns **true** if the access is blocked; returns **false** otherwise.| 5806 5807**Example** 5808 5809 ```ts 5810 // xxx.ets 5811 import { webview } from '@kit.ArkWeb'; 5812 5813 @Entry 5814 @Component 5815 struct WebComponent { 5816 controller: webview.WebviewController = new webview.WebviewController(); 5817 5818 build() { 5819 Column() { 5820 Web({ src: 'www.example.com', controller: this.controller }) 5821 .onLoadIntercept((event) => { 5822 console.log('url:' + event.data.getRequestUrl()); 5823 console.log('isMainFrame:' + event.data.isMainFrame()); 5824 console.log('isRedirect:' + event.data.isRedirect()); 5825 console.log('isRequestGesture:' + event.data.isRequestGesture()); 5826 return true; 5827 }) 5828 } 5829 } 5830 } 5831 ``` 5832 5833### onRequestSelected 5834 5835onRequestSelected(callback: () => void) 5836 5837Called when the **Web** component obtains the focus. 5838 5839**System capability**: SystemCapability.Web.Webview.Core 5840 5841**Example** 5842 5843 ```ts 5844 // xxx.ets 5845 import { webview } from '@kit.ArkWeb'; 5846 5847 @Entry 5848 @Component 5849 struct WebComponent { 5850 controller: webview.WebviewController = new webview.WebviewController(); 5851 5852 build() { 5853 Column() { 5854 Web({ src: 'www.example.com', controller: this.controller }) 5855 .onRequestSelected(() => { 5856 console.log('onRequestSelected'); 5857 }) 5858 } 5859 } 5860 } 5861 ``` 5862### onScreenCaptureRequest<sup>10+</sup> 5863 5864onScreenCaptureRequest(callback: Callback\<OnScreenCaptureRequestEvent\>) 5865 5866Called when a screen capture request is received. 5867 5868**System capability**: SystemCapability.Web.Webview.Core 5869 5870**Parameters** 5871 5872| Name | Type | Mandatory | Description | 5873| ------ | ------ | ---- | --------------------- | 5874| callback | Callback\<[OnScreenCaptureRequestEvent](#onscreencapturerequestevent12)\> | Yes| Called when a screen capture request is received.| 5875 5876**Example** 5877 5878 ```ts 5879 // xxx.ets 5880 import { webview } from '@kit.ArkWeb'; 5881 5882 @Entry 5883 @Component 5884 struct WebComponent { 5885 controller: webview.WebviewController = new webview.WebviewController(); 5886 5887 build() { 5888 Column() { 5889 Web({ src: 'www.example.com', controller: this.controller }) 5890 .onScreenCaptureRequest((event) => { 5891 if (event) { 5892 AlertDialog.show({ 5893 title: 'title: ' + event.handler.getOrigin(), 5894 message: 'text', 5895 primaryButton: { 5896 value: 'deny', 5897 action: () => { 5898 event.handler.deny(); 5899 } 5900 }, 5901 secondaryButton: { 5902 value: 'onConfirm', 5903 action: () => { 5904 event.handler.grant({ captureMode: WebCaptureMode.HOME_SCREEN }); 5905 } 5906 }, 5907 cancel: () => { 5908 event.handler.deny(); 5909 } 5910 }) 5911 } 5912 }) 5913 } 5914 } 5915 } 5916 ``` 5917 5918### onOverScroll<sup>10+</sup> 5919 5920onOverScroll(callback: Callback\<OnOverScrollEvent\>) 5921 5922Called when the web page is overscrolled. It is used to notify the user of the offset of the overscroll. 5923 5924**System capability**: SystemCapability.Web.Webview.Core 5925 5926**Parameters** 5927 5928| Name | Type | Mandatory | Description | 5929| ------ | ------ | ---- | --------------------- | 5930| callback | Callback\<[OnOverScrollEvent](#onoverscrollevent12)\> | Yes| Callback invoked when the web page is overscrolled.| 5931 5932**Example** 5933 5934 ```ts 5935 // xxx.ets 5936 import { webview } from '@kit.ArkWeb'; 5937 5938 @Entry 5939 @Component 5940 struct WebComponent { 5941 controller: webview.WebviewController = new webview.WebviewController(); 5942 5943 build() { 5944 Column() { 5945 Web({ src: 'www.example.com', controller: this.controller }) 5946 .onOverScroll((event) => { 5947 console.info("x = " + event.xOffset); 5948 console.info("y = " + event.yOffset); 5949 }) 5950 } 5951 } 5952 } 5953 ``` 5954 5955### onControllerAttached<sup>10+</sup> 5956 5957onControllerAttached(callback: () => void) 5958 5959Called when the controller is successfully bound to the **Web** component. The controller must be WebviewController. Do not call APIs related to the **Web** component before this callback event. Otherwise, a js-error exception will be thrown. 5960As the web page is not yet loaded when this callback is called, APIs for operating the web page, for example, [zoomIn](js-apis-webview.md#zoomin) and [zoomOut](js-apis-webview.md#zoomout), cannot be used in the callback. Other APIs, such as [loadUrl](js-apis-webview.md#loadurl) and [getWebId](js-apis-webview.md#getwebid), which do not involve web page operations, can be used properly. 5961 5962For details about the component lifecycle, see [Lifecycle of Web Components](../../web/web-event-sequence.md). 5963 5964**System capability**: SystemCapability.Web.Webview.Core 5965 5966**Example** 5967 5968The following example uses **loadUrl** in the callback to load the web page. 5969 ```ts 5970 // xxx.ets 5971 import { webview } from '@kit.ArkWeb'; 5972 5973 @Entry 5974 @Component 5975 struct WebComponent { 5976 controller: webview.WebviewController = new webview.WebviewController(); 5977 5978 build() { 5979 Column() { 5980 Web({ src: '', controller: this.controller }) 5981 .onControllerAttached(() => { 5982 this.controller.loadUrl($rawfile("index.html")); 5983 }) 5984 } 5985 } 5986 } 5987 ``` 5988 5989The following example uses **getWebId** in the callback 5990 ```ts 5991 // xxx.ets 5992 import { webview } from '@kit.ArkWeb'; 5993 import { BusinessError } from '@kit.BasicServicesKit'; 5994 5995 @Entry 5996 @Component 5997 struct WebComponent { 5998 controller: webview.WebviewController = new webview.WebviewController(); 5999 6000 build() { 6001 Column() { 6002 Web({ src: $rawfile("index.html"), controller: this.controller }) 6003 .onControllerAttached(() => { 6004 try { 6005 let id = this.controller.getWebId(); 6006 console.log("id: " + id); 6007 } catch (error) { 6008 let code = (error as BusinessError).code; 6009 let message = (error as BusinessError).message; 6010 console.error(`ErrorCode: ${code}, Message: ${message}`); 6011 } 6012 }) 6013 } 6014 } 6015 } 6016 ``` 6017 HTML file to be loaded: 6018 ```html 6019 <!-- index.html --> 6020 <!DOCTYPE html> 6021 <html> 6022 <body> 6023 <p>Hello World</p> 6024 </body> 6025 </html> 6026 ``` 6027 6028### onNavigationEntryCommitted<sup>11+</sup> 6029 6030onNavigationEntryCommitted(callback: [OnNavigationEntryCommittedCallback](#onnavigationentrycommittedcallback11)) 6031 6032Called when a web page redirection request is submitted. 6033 6034**System capability**: SystemCapability.Web.Webview.Core 6035 6036**Parameters** 6037 6038| Name | Type | Mandatory | Description | 6039| ------ | ------ | ---- | --------------------- | 6040| callback | [OnNavigationEntryCommittedCallback](#onnavigationentrycommittedcallback11) | Yes| Callback invoked when a web page redirection request is submitted.| 6041 6042**Example** 6043 6044 ```ts 6045 // xxx.ets 6046 import { webview } from '@kit.ArkWeb'; 6047 6048 @Entry 6049 @Component 6050 struct WebComponent { 6051 controller: webview.WebviewController = new webview.WebviewController(); 6052 6053 build() { 6054 Column() { 6055 Web({ src: 'www.example.com', controller: this.controller }) 6056 .onNavigationEntryCommitted((details) => { 6057 console.log("onNavigationEntryCommitted: [isMainFrame]= " + details.isMainFrame + 6058 ", [isSameDocument]=" + details.isSameDocument + 6059 ", [didReplaceEntry]=" + details.didReplaceEntry + 6060 ", [navigationType]=" + details.navigationType + 6061 ", [url]=" + details.url); 6062 }) 6063 } 6064 } 6065 } 6066 ``` 6067 6068### onSafeBrowsingCheckResult<sup>11+</sup> 6069 6070onSafeBrowsingCheckResult(callback: OnSafeBrowsingCheckResultCallback) 6071 6072Called when the safe browsing check result is received. 6073 6074**System capability**: SystemCapability.Web.Webview.Core 6075 6076**Parameters** 6077 6078| Name | Type | Mandatory | Description | 6079| ------ | ------ | ---- | --------------------- | 6080| callback | [OnSafeBrowsingCheckResultCallback](#onsafebrowsingcheckresultcallback11) | Yes| Called when the safe browsing check result is received.| 6081 6082**Example** 6083 6084 ```ts 6085 // xxx.ets 6086 import { webview } from '@kit.ArkWeb'; 6087 6088 export enum ThreatType { 6089 UNKNOWN = -1, 6090 THREAT_ILLEGAL = 0, 6091 THREAT_FRAUD = 1, 6092 THREAT_RISK = 2, 6093 THREAT_WARNING = 3, 6094 } 6095 6096 export class OnSafeBrowsingCheckResultCallback { 6097 threatType: ThreatType = ThreatType.UNKNOWN; 6098 } 6099 6100 @Entry 6101 @Component 6102 struct WebComponent { 6103 controller: webview.WebviewController = new webview.WebviewController(); 6104 6105 build() { 6106 Column() { 6107 Web({ src: 'www.example.com', controller: this.controller }) 6108 .onSafeBrowsingCheckResult((callback) => { 6109 let jsonData = JSON.stringify(callback); 6110 let json: OnSafeBrowsingCheckResultCallback = JSON.parse(jsonData); 6111 console.log("onSafeBrowsingCheckResult: [threatType]= " + json.threatType); 6112 }) 6113 } 6114 } 6115 } 6116 ``` 6117 6118### onNativeEmbedLifecycleChange<sup>11+</sup> 6119 6120onNativeEmbedLifecycleChange(callback: (event: NativeEmbedDataInfo) => void) 6121 6122Called when the lifecycle of the same-layer **Embed** tag changes. 6123 6124**System capability**: SystemCapability.Web.Webview.Core 6125 6126**Parameters** 6127 6128| Name | Type | Mandatory | Description | 6129| ------ | ------ | ---- | --------------------- | 6130| callback | (event: [NativeEmbedDataInfo](#nativeembeddatainfo11)) => void | Yes| Callback invoked when the lifecycle of the same-layer tag changes.| 6131 6132**Example** 6133 6134```ts 6135// EntryAbility.ets 6136 6137import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 6138import { hilog } from '@kit.PerformanceAnalysisKit'; 6139import { window } from '@kit.ArkUI'; 6140import { webview } from '@kit.ArkWeb'; 6141 6142export default class EntryAbility extends UIAbility { 6143 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 6144 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); 6145 // Added in API version 12: feature to enable the back/forward cache for same-layer rendering. 6146 let features = new webview.BackForwardCacheSupportedFeatures(); 6147 features.nativeEmbed = true; 6148 features.mediaTakeOver = true; 6149 webview.WebviewController.enableBackForwardCache(features); 6150 webview.WebviewController.initializeWebEngine(); 6151 } 6152 6153 onDestroy(): void { 6154 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy'); 6155 } 6156 6157 onWindowStageCreate(windowStage: window.WindowStage): void { 6158 // Main window is created, set main page for this ability 6159 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 6160 6161 windowStage.loadContent('pages/Index', (err) => { 6162 if (err.code) { 6163 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 6164 return; 6165 } 6166 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.'); 6167 }); 6168 } 6169 6170 onWindowStageDestroy(): void { 6171 // Main window is destroyed, release UI related resources 6172 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy'); 6173 } 6174 6175 onForeground(): void { 6176 // Ability has brought to foreground 6177 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); 6178 } 6179 6180 onBackground(): void { 6181 // Ability has back to background 6182 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground'); 6183 } 6184} 6185``` 6186 6187 ```ts 6188 // xxx.ets 6189 import { webview } from '@kit.ArkWeb'; 6190 import { BusinessError } from '@kit.BasicServicesKit'; 6191 6192 @Entry 6193 @Component 6194 struct WebComponent { 6195 @State embedStatus: string = ''; 6196 controller: webview.WebviewController = new webview.WebviewController(); 6197 6198 build() { 6199 Column() { 6200 // Default behavior: Click the button to navigate to a new page, close the index page, and destroy the same-layer tag. 6201 // Added in API version 12: When BFCache is enabled for the page that supports same-layer rendering, clicking the button navigates to a new page, closes the index page, and puts the same-layer tag into BFCache. 6202 Button('Destroy') 6203 .onClick(() => { 6204 try { 6205 this.controller.loadUrl("www.example.com"); 6206 } catch (error) { 6207 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6208 } 6209 }) 6210 6211 // Added in API version 12: When BFCache is enabled for the page that supports same-layer rendering, clicking the button to return to the page causes the same-layer tag to exit BFCache. 6212 Button('backward') 6213 .onClick(() => { 6214 try { 6215 this.controller.backward(); 6216 } catch (error) { 6217 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6218 } 6219 }) 6220 6221 // Added in API version 12: When BFCache is enabled for the page that supports same-layer rendering, clicking a button to advance to the next page causes the same-layer tag to enter BFCache. 6222 Button('forward') 6223 .onClick(() => { 6224 try { 6225 this.controller.forward(); 6226 } catch (error) { 6227 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6228 } 6229 }) 6230 6231 6232 // Added in API version 12: The Web kernel does not allow web pages loaded with non-HTTP and non-HTTPS protocols to enter BFCache. 6233 // Therefore, to test the ENTER_BFCACHE/LEAVE_BFCACHE states, you need to place the index.html on a web server and load it using the HTTP or HTTPS protocol. Example: 6234 // Web({ src: "http://xxxx/index.html", controller: this.controller }) 6235 Web({ src: $rawfile("index.html"), controller: this.controller }) 6236 .enableNativeEmbedMode(true) 6237 .onNativeEmbedLifecycleChange((event) => { 6238 // The Create event is triggered when the same-layer tag is detected on the loaded page. 6239 if (event.status == NativeEmbedStatus.CREATE) { 6240 this.embedStatus = 'Create'; 6241 } 6242 // The Update event is triggered when the same-layer tag on the page is moved or scaled. 6243 if (event.status == NativeEmbedStatus.UPDATE) { 6244 this.embedStatus = 'Update'; 6245 } 6246 // The Destroy event is triggered when you exit the page. 6247 if (event.status == NativeEmbedStatus.DESTROY) { 6248 this.embedStatus = 'Destroy'; 6249 } 6250 // The Enter BFCache event is triggered when the page with the same-layer tag enters BFCache. 6251 if (event.status == NativeEmbedStatus.ENTER_BFCACHE) { 6252 this.embedStatus = 'Enter BFCache'; 6253 } 6254 // The Leave BFCache event is triggered when the page with the same-layer tag leaves BFCache. 6255 if (event.status == NativeEmbedStatus.LEAVE_BFCACHE) { 6256 this.embedStatus = 'Leave BFCache'; 6257 } 6258 console.log("status = " + this.embedStatus); 6259 console.log("surfaceId = " + event.surfaceId); 6260 console.log("embedId = " + event.embedId); 6261 if (event.info) { 6262 console.log("id = " + event.info.id); 6263 console.log("type = " + event.info.type); 6264 console.log("src = " + event.info.src); 6265 console.log("width = " + event.info.width); 6266 console.log("height = " + event.info.height); 6267 console.log("url = " + event.info.url); 6268 } 6269 }) 6270 } 6271 } 6272 } 6273 ``` 6274 6275 HTML file to be loaded: 6276 ``` 6277 <!-- index.html --> 6278 <!Document> 6279 <html> 6280 <head> 6281 <title>Same-layer rendering test HTML</title> 6282 <meta name="viewport"> 6283 </head> 6284 <body> 6285 <div> 6286 <div id="bodyId"> 6287 <embed id="nativeButton" type = "native/button" width="800" height="800" src="test? params1=1?" style = "background-color:red"/> 6288 </div> 6289 </div> 6290 </body> 6291 </html> 6292 ``` 6293 6294### onNativeEmbedGestureEvent<sup>11+</sup> 6295 6296onNativeEmbedGestureEvent(callback: (event: NativeEmbedTouchInfo) => void) 6297 6298Called when a finger touches a same-layer tag. 6299 6300**System capability**: SystemCapability.Web.Webview.Core 6301 6302**Parameters** 6303 6304| Name | Type | Mandatory | Description | 6305| ------ | ------ | ---- | --------------------- | 6306| callback | (event: [NativeEmbedTouchInfo](#nativeembedtouchinfo11)) => void | Yes| Callback invoked when a finger touches a same-layer tag.| 6307 6308**Example** 6309 6310 ```ts 6311 // xxx.ets 6312 import { webview } from '@kit.ArkWeb'; 6313 import { NodeController, BuilderNode, NodeRenderType, FrameNode, UIContext } from "@kit.ArkUI"; 6314 6315 declare class Params { 6316 text: string; 6317 width: number; 6318 height: number; 6319 } 6320 6321 declare class NodeControllerParams { 6322 surfaceId: string; 6323 renderType: NodeRenderType; 6324 width: number; 6325 height: number; 6326 } 6327 6328 class MyNodeController extends NodeController { 6329 private rootNode: BuilderNode<[Params]> | undefined | null; 6330 private surfaceId_: string = ""; 6331 private renderType_: NodeRenderType = NodeRenderType.RENDER_TYPE_DISPLAY; 6332 private width_: number = 0; 6333 private height_: number = 0; 6334 6335 setRenderOption(params: NodeControllerParams) { 6336 this.surfaceId_ = params.surfaceId; 6337 this.renderType_ = params.renderType; 6338 this.width_ = params.width; 6339 this.height_ = params.height; 6340 } 6341 6342 makeNode(uiContext: UIContext): FrameNode | null { 6343 this.rootNode = new BuilderNode(uiContext, { surfaceId: this.surfaceId_, type: this.renderType_ }); 6344 this.rootNode.build(wrapBuilder(ButtonBuilder), { text: "myButton", width: this.width_, height: this.height_ }); 6345 return this.rootNode.getFrameNode(); 6346 } 6347 6348 postEvent(event: TouchEvent | undefined): boolean { 6349 return this.rootNode?.postTouchEvent(event) as boolean; 6350 } 6351 } 6352 6353 @Component 6354 struct ButtonComponent { 6355 @Prop params: Params; 6356 @State bkColor: Color = Color.Red; 6357 6358 build() { 6359 Column() { 6360 Button(this.params.text) 6361 .height(50) 6362 .width(200) 6363 .border({ width: 2, color: Color.Red }) 6364 .backgroundColor(this.bkColor) 6365 6366 } 6367 .width(this.params.width) 6368 .height(this.params.height) 6369 } 6370 } 6371 6372 @Builder 6373 function ButtonBuilder(params: Params) { 6374 ButtonComponent({ params: params }) 6375 .backgroundColor(Color.Green) 6376 } 6377 6378 @Entry 6379 @Component 6380 struct WebComponent { 6381 @State eventType: string = ''; 6382 controller: webview.WebviewController = new webview.WebviewController(); 6383 private nodeController: MyNodeController = new MyNodeController(); 6384 6385 build() { 6386 Column() { 6387 Stack() { 6388 NodeContainer(this.nodeController) 6389 Web({ src: $rawfile("index.html"), controller: this.controller }) 6390 .enableNativeEmbedMode(true) 6391 .onNativeEmbedLifecycleChange((embed) => { 6392 if (embed.status == NativeEmbedStatus.CREATE) { 6393 this.nodeController.setRenderOption({ 6394 surfaceId: embed.surfaceId as string, 6395 renderType: NodeRenderType.RENDER_TYPE_TEXTURE, 6396 width: px2vp(embed.info?.width), 6397 height: px2vp(embed.info?.height) 6398 }); 6399 this.nodeController.rebuild(); 6400 } 6401 }) 6402 .onNativeEmbedGestureEvent((event) => { 6403 if (event && event.touchEvent) { 6404 if (event.touchEvent.type == TouchType.Down) { 6405 this.eventType = 'Down' 6406 } 6407 if (event.touchEvent.type == TouchType.Up) { 6408 this.eventType = 'Up' 6409 } 6410 if (event.touchEvent.type == TouchType.Move) { 6411 this.eventType = 'Move' 6412 } 6413 if (event.touchEvent.type == TouchType.Cancel) { 6414 this.eventType = 'Cancel' 6415 } 6416 let ret = this.nodeController.postEvent(event.touchEvent) 6417 if (event.result) { 6418 event.result.setGestureEventResult(ret, true); 6419 } 6420 console.log("embedId = " + event.embedId); 6421 console.log("touchType = " + this.eventType); 6422 console.log("x = " + event.touchEvent.touches[0].x); 6423 console.log("y = " + event.touchEvent.touches[0].y); 6424 console.log("Component globalPos:(" + event.touchEvent.target.area.globalPosition.x + "," + event.touchEvent.target.area.globalPosition.y + ")"); 6425 console.log("width = " + event.touchEvent.target.area.width); 6426 console.log("height = " + event.touchEvent.target.area.height); 6427 } 6428 }) 6429 } 6430 } 6431 } 6432 } 6433 ``` 6434HTML file to be loaded: 6435 ``` 6436 <!-- index.html --> 6437 <!Document> 6438<html> 6439<head> 6440 <title>Same-layer rendering test HTML</title> 6441 <meta name="viewport"> 6442</head> 6443<body> 6444<div> 6445 <div id="bodyId"> 6446 <embed id="nativeButton" type = "native/button" width="800" height="800" src="test?params1=1?" style = "background-color:red"/> 6447 </div> 6448</div> 6449</body> 6450</html> 6451 ``` 6452 6453### onIntelligentTrackingPreventionResult<sup>12+</sup> 6454 6455onIntelligentTrackingPreventionResult(callback: OnIntelligentTrackingPreventionCallback) 6456 6457Called when the intelligent tracking prevention feature is enabled and the tracker cookie is blocked. 6458 6459**System capability**: SystemCapability.Web.Webview.Core 6460 6461**Parameters** 6462 6463| Name | Type | Mandatory | Description | 6464| ------ | ------ | ---- | --------------------- | 6465| callback | [OnIntelligentTrackingPreventionCallback](#onintelligenttrackingpreventioncallback12) | Yes| Callback invoked when the intelligent tracking prevention feature is enabled and the tracker cookie is blocked.| 6466 6467**Example** 6468 6469 ```ts 6470 // xxx.ets 6471 import { webview } from '@kit.ArkWeb'; 6472 import { BusinessError } from '@kit.BasicServicesKit'; 6473 6474 @Entry 6475 @Component 6476 struct WebComponent { 6477 controller: webview.WebviewController = new webview.WebviewController(); 6478 6479 build() { 6480 Column() { 6481 // The onIntelligentTrackingPreventionResult callback is triggered only when the intelligent tracking prevention is enabled. 6482 Button('enableIntelligentTrackingPrevention') 6483 .onClick(() => { 6484 try { 6485 this.controller.enableIntelligentTrackingPrevention(true); 6486 } catch (error) { 6487 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6488 } 6489 }) 6490 Web({ src: 'www.example.com', controller: this.controller }) 6491 .onIntelligentTrackingPreventionResult((details) => { 6492 console.log("onIntelligentTrackingPreventionResult: [websiteHost]= " + details.host + 6493 ", [trackerHost]=" + details.trackerHost); 6494 }) 6495 } 6496 } 6497 } 6498 ``` 6499 6500### onOverrideUrlLoading<sup>12+</sup> 6501 6502onOverrideUrlLoading(callback: OnOverrideUrlLoadingCallback) 6503 6504Called to enable the host application to obtain control when the URL is about to be loaded to this **Web** component. If the callback returns **true**, the **Web** component stops loading the URL. If the callback returns **false**, the **Web** component continues to load the URL. 6505 6506POST requests do not trigger this callback. 6507 6508This callback is triggered when the **iframe** loads the redirection of a non-HTTP(s) protocol, but is not triggered when the **iframe** loads the HTTP(s) protocol or **about:blank** and when the redirection initiated by **loadUrl(String)** is called. 6509 6510Do not use the same URL to call the **loadUrl(String)** API and then return **true**. Doing so would unnecessarily cancel the current loading and start a new load with the same URL. The correct way to continue loading the given URL is to simply return **false**, rather than calling **loadUrl(String)**. 6511 6512**System capability**: SystemCapability.Web.Webview.Core 6513 6514**Parameters** 6515 6516| Name | Type | Mandatory | Description | 6517| ------ | ------ | ---- | --------------------- | 6518| callback | [OnOverrideUrlLoadingCallback](#onoverrideurlloadingcallback12) | Yes| Callback for **onOverrideUrlLoading**.| 6519 6520**Example** 6521 6522 ```ts 6523 // xxx.ets 6524 import { webview } from '@kit.ArkWeb'; 6525 6526 @Entry 6527 @Component 6528 struct WebComponent { 6529 controller: webview.WebviewController = new webview.WebviewController(); 6530 6531 build() { 6532 Column() { 6533 Web({ src: $rawfile("index.html"), controller: this.controller }) 6534 .onOverrideUrlLoading((webResourceRequest: WebResourceRequest) => { 6535 if (webResourceRequest && webResourceRequest.getRequestUrl() == "about:blank") { 6536 return true; 6537 } 6538 return false; 6539 }) 6540 } 6541 } 6542 } 6543 ``` 6544 6545 HTML file to be loaded: 6546 ```html 6547 <!--index.html--> 6548 <!DOCTYPE html> 6549 <html> 6550 <head> 6551 <title>Test Web Page</title> 6552 </head> 6553 <body> 6554 <h1>onOverrideUrlLoading Demo</h1> 6555 <a href="about:blank">Click here</a>// to visit about:blank. 6556 </body> 6557 </html> 6558 ``` 6559 6560### onViewportFitChanged<sup>12+</sup> 6561 6562onViewportFitChanged(callback: OnViewportFitChangedCallback) 6563 6564Called when the **viewport-fit** configuration in the web page's **\<meta>** tag changes. The application can adapt its layout to the viewport within this callback. 6565 6566**System capability**: SystemCapability.Web.Webview.Core 6567 6568**Parameters** 6569 6570| Name | Type | Mandatory | Description | 6571| ------ | ------ | ---- | --------------------- | 6572| callback | [OnViewportFitChangedCallback](#onviewportfitchangedcallback12) | Yes| Callback invoked when the **viewport-fit** configuration in the web page's **\<meta>** tag changes.| 6573 6574**Example** 6575 6576 ```ts 6577 // xxx.ets 6578 import { webview } from '@kit.ArkWeb'; 6579 6580 @Entry 6581 @Component 6582 struct WebComponent { 6583 controller: webview.WebviewController = new webview.WebviewController(); 6584 6585 build() { 6586 Column() { 6587 Web({ src: $rawfile('index.html'), controller: this.controller }) 6588 .onViewportFitChanged((data) => { 6589 let jsonData = JSON.stringify(data); 6590 let viewportFit: ViewportFit = JSON.parse(jsonData).viewportFit; 6591 if (viewportFit === ViewportFit.COVER) { 6592 // The index.html web page supports immersive layout. You can call expandSafeArea to adjust the Web component layout viewport to cover the safe area (status bar or navigation bar). 6593 } else if (viewportFit === ViewportFit.CONTAINS) { 6594 // The index.html web page does not support immersive layout. You can call expandSafeArea to adjust the Web component layout viewport as a safe area. 6595 } else { 6596 // Default value. No processing is required. 6597 } 6598 }) 6599 } 6600 } 6601 } 6602 ``` 6603 6604 HTML file to be loaded: 6605 ```html 6606 <!-- index.html --> 6607 <!DOCTYPE html> 6608 <html> 6609 <head> 6610 <meta name="viewport" content="width=device-width,viewport-fit=cover"> 6611 </head> 6612 <body> 6613 <div style="position: absolute; bottom: 0; margin-bottom: env(safe-area-inset-bottom)"></div> 6614 </body> 6615 </html> 6616 ``` 6617 6618### onInterceptKeyboardAttach<sup>12+</sup> 6619 6620onInterceptKeyboardAttach(callback: WebKeyboardCallback) 6621 6622Called before any editable element (such as the **\<input>** tag) on the web page invokes the soft keyboard. The application can use this API to intercept the display of the system's soft keyboard and configure a custom soft keyboard. (With this API, the application can determine whether to use the system's default soft keyboard, a system soft keyboard with a custom Enter key, or a completely application-defined soft keyboard). 6623 6624**System capability**: SystemCapability.Web.Webview.Core 6625 6626**Parameters** 6627 6628| Name | Type | Mandatory | Description | 6629| ------ | ------ | ---- | --------------------- | 6630| callback | [WebKeyboardCallback](#webkeyboardcallback12) | Yes| Callback invoked for intercepting the soft keyboard invoking in the web page.| 6631 6632**Example** 6633 6634 ```ts 6635 // xxx.ets 6636 import { webview } from '@kit.ArkWeb'; 6637 import { inputMethodEngine } from '@kit.IMEKit'; 6638 6639 @Entry 6640 @Component 6641 struct WebComponent { 6642 controller: webview.WebviewController = new webview.WebviewController(); 6643 webKeyboardController: WebKeyboardController = new WebKeyboardController() 6644 inputAttributeMap: Map<string, number> = new Map([ 6645 ['UNSPECIFIED', inputMethodEngine.ENTER_KEY_TYPE_UNSPECIFIED], 6646 ['GO', inputMethodEngine.ENTER_KEY_TYPE_GO], 6647 ['SEARCH', inputMethodEngine.ENTER_KEY_TYPE_SEARCH], 6648 ['SEND', inputMethodEngine.ENTER_KEY_TYPE_SEND], 6649 ['NEXT', inputMethodEngine.ENTER_KEY_TYPE_NEXT], 6650 ['DONE', inputMethodEngine.ENTER_KEY_TYPE_DONE], 6651 ['PREVIOUS', inputMethodEngine.ENTER_KEY_TYPE_PREVIOUS] 6652 ]) 6653 6654 /** 6655 * Builder for a custom keyboard component 6656 */ 6657 @Builder 6658 customKeyboardBuilder() { 6659 // Implement a custom keyboard component and connect to the WebKeyboardController to implement operations such as input, deletion, and close. 6660 Row() { 6661 Text("Finish") 6662 .fontSize(20) 6663 .fontColor(Color.Blue) 6664 .onClick(() => { 6665 this.webKeyboardController.close(); 6666 }) 6667 // Insert characters. 6668 Button("insertText").onClick(() => { 6669 this.webKeyboardController.insertText('insert '); 6670 }).margin({ 6671 bottom: 200, 6672 }) 6673 // Delete characters from the end to the beginning for the length specified by the length parameter. 6674 Button("deleteForward").onClick(() => { 6675 this.webKeyboardController.deleteForward(1); 6676 }).margin({ 6677 bottom: 200, 6678 }) 6679 // Delete characters from the beginning to the end for the length specified by the length parameter. 6680 Button("deleteBackward").onClick(() => { 6681 this.webKeyboardController.deleteBackward(1); 6682 }).margin({ 6683 left: -220, 6684 }) 6685 // Insert a function key. 6686 Button("sendFunctionKey").onClick(() => { 6687 this.webKeyboardController.sendFunctionKey(6); 6688 }) 6689 } 6690 } 6691 6692 build() { 6693 Column() { 6694 Web({ src: $rawfile('index.html'), controller: this.controller }) 6695 .onInterceptKeyboardAttach((KeyboardCallbackInfo) => { 6696 // Initialize option. By default, the default keyboard is used. 6697 let option: WebKeyboardOptions = { 6698 useSystemKeyboard: true, 6699 }; 6700 if (!KeyboardCallbackInfo) { 6701 return option; 6702 } 6703 6704 // Save the WebKeyboardController. When using a custom keyboard, this handler is required to control behaviors such as input, deletion, and closing of the soft keyboard. 6705 this.webKeyboardController = KeyboardCallbackInfo.controller 6706 let attributes: Record<string, string> = KeyboardCallbackInfo.attributes 6707 // Traverse attributes. 6708 let attributeKeys = Object.keys(attributes) 6709 for (let i = 0; i < attributeKeys.length; i++) { 6710 console.log('WebCustomKeyboard key = ' + attributeKeys[i] + ', value = ' + attributes[attributeKeys[i]]) 6711 } 6712 6713 if (attributes) { 6714 if (attributes['data-keyboard'] == 'customKeyboard') { 6715 // Determine the soft keyboard to use based on the attributes of editable HTML elements. For example, if the attribute includes data-keyboard and its value is customKeyboard, use a custom keyboard. 6716 console.log('WebCustomKeyboard use custom keyboard') 6717 option.useSystemKeyboard = false; 6718 // Sets the custom keyboard builder. 6719 option.customKeyboard = () => { 6720 this.customKeyboardBuilder() 6721 } 6722 return option; 6723 } 6724 6725 if (attributes['keyboard-return'] != undefined) { 6726 // Determine the soft keyboard to use based on the attributes of editable HTML elements. For example, if the attribute includes keyboard-return, use the system keyboard and specify the type of the system soft keyboard's Enter key. 6727 option.useSystemKeyboard = true; 6728 let enterKeyType: number | undefined = this.inputAttributeMap.get(attributes['keyboard-return']) 6729 if (enterKeyType != undefined) { 6730 option.enterKeyType = enterKeyType 6731 } 6732 return option; 6733 } 6734 } 6735 6736 return option; 6737 }) 6738 } 6739 } 6740 } 6741 ``` 6742 6743 HTML file to be loaded: 6744 ```html 6745 <!-- index.html --> 6746 <!DOCTYPE html> 6747 <html> 6748 6749 <head> 6750 <meta charset="utf-8"> 6751 <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0"> 6752 </head> 6753 6754 <body> 6755 6756 <p style="font-size:12px">input tag. Original default behavior: </p> 6757 <input type="text" style="width: 300px; height: 20px"><br> 6758 <hr style="height:2px;border-width:0;color:gray;background-color:gray"> 6759 6760 <p style="font-size:12px">input tag. System keyboard with enterKeyType as UNSPECIFIED: </p> 6761 <input type="text" keyboard-return="UNSPECIFIED" style="width: 300px; height: 20px"><br> 6762 <hr style="height:2px;border-width:0;color:gray;background-color:gray"> 6763 6764 <p style="font-size:12px">input tag. System keyboard with enterKeyType as GO: </p> 6765 <input type="text" keyboard-return="GO" style="width: 300px; height: 20px"><br> 6766 <hr style="height:2px;border-width:0;color:gray;background-color:gray"> 6767 6768 <p style="font-size:12px">input tag. System keyboard with enterKeyType as SEARCH: </p> 6769 <input type="text" keyboard-return="SEARCH" style="width: 300px; height: 20px"><br> 6770 <hr style="height:2px;border-width:0;color:gray;background-color:gray"> 6771 6772 <p style="font-size:12px">input tag. System keyboard with enterKeyType as SEND: </p> 6773 <input type="text" keyboard-return="SEND" style="width: 300px; height: 20px"><br> 6774 <hr style="height:2px;border-width:0;color:gray;background-color:gray"> 6775 6776 <p style="font-size:12px">input tag. System keyboard with enterKeyType as NEXT: </p> 6777 <input type="text" keyboard-return="NEXT" style="width: 300px; height: 20px"><br> 6778 <hr style="height:2px;border-width:0;color:gray;background-color:gray"> 6779 6780 <p style="font-size:12px">input tag. System keyboard with enterKeyType as DONE: </p> 6781 <input type="text" keyboard-return="DONE" style="width: 300px; height: 20px"><br> 6782 <hr style="height:2px;border-width:0;color:gray;background-color:gray"> 6783 6784 <p style="font-size:12px">input tag. System keyboard with enterKeyType as PREVIOUS: </p> 6785 <input type="text" keyboard-return="PREVIOUS" style="width: 300px; height: 20px"><br> 6786 <hr style="height:2px;border-width:0;color:gray;background-color:gray"> 6787 6788 <p style="font-size:12px">input tag. Custom keyboard: </p> 6789 <input type="text" data-keyboard="customKeyboard" style="width: 300px; height: 20px"><br> 6790 6791 </body> 6792 6793 </html> 6794 ``` 6795 6796### onNativeEmbedVisibilityChange<sup>12+</sup> 6797 6798onNativeEmbedVisibilityChange(callback: OnNativeEmbedVisibilityChangeCallback) 6799 6800Called when the visibility of a same-layer tag (such as an **Embed** tag or an **Object** tag) on a web page changes in the viewport. By default, the same-layer tag is invisible. If the rendering tag is visible when you access the page for the first time, the callback is triggered; otherwise, it is not triggered. That is, if the same-layer tag changes from a non-zero value to **0 x 0**, the callback is triggered. If the rendering tag size changes from **0 x 0** to a non-zero value, the callback is not triggered. If all the same-layer tags are invisible, they are reported as invisible. If all the same-layer rendering tags or part of them are visible, they are reported as invisible. 6801 6802**System capability**: SystemCapability.Web.Webview.Core 6803 6804**Parameters** 6805 6806| Name | Type | Mandatory | Description | 6807| ------ | ------ | ---- | --------------------- | 6808| callback | [OnNativeEmbedVisibilityChangeCallback](#onnativeembedvisibilitychangecallback12) | Yes| Called when the visibility of a same-layer tag changes.| 6809 6810**Example** 6811 6812 ```ts 6813 // xxx.ets 6814 import { webview } from '@kit.ArkWeb'; 6815 import { NodeController, BuilderNode, NodeRenderType, FrameNode, UIContext } from "@kit.ArkUI"; 6816 6817 declare class Params { 6818 text: string; 6819 width: number; 6820 height: number; 6821 } 6822 6823 declare class NodeControllerParams { 6824 surfaceId: string; 6825 renderType: NodeRenderType; 6826 width: number; 6827 height: number; 6828 } 6829 6830 class MyNodeController extends NodeController { 6831 private rootNode: BuilderNode<[Params]> | undefined | null; 6832 private surfaceId_: string = ""; 6833 private renderType_: NodeRenderType = NodeRenderType.RENDER_TYPE_DISPLAY; 6834 private width_: number = 0; 6835 private height_: number = 0; 6836 6837 setRenderOption(params: NodeControllerParams) { 6838 this.surfaceId_ = params.surfaceId; 6839 this.renderType_ = params.renderType; 6840 this.width_ = params.width; 6841 this.height_ = params.height; 6842 } 6843 6844 makeNode(uiContext: UIContext): FrameNode | null { 6845 this.rootNode = new BuilderNode(uiContext, { surfaceId: this.surfaceId_, type: this.renderType_ }); 6846 this.rootNode.build(wrapBuilder(ButtonBuilder), { text: "myButton", width: this.width_, height: this.height_ }); 6847 return this.rootNode.getFrameNode(); 6848 } 6849 6850 postEvent(event: TouchEvent | undefined): boolean { 6851 return this.rootNode?.postTouchEvent(event) as boolean; 6852 } 6853 } 6854 6855 @Component 6856 struct ButtonComponent { 6857 @Prop params: Params; 6858 @State bkColor: Color = Color.Red; 6859 6860 build() { 6861 Column() { 6862 Button(this.params.text) 6863 .height(50) 6864 .width(200) 6865 .border({ width: 2, color: Color.Red }) 6866 .backgroundColor(this.bkColor) 6867 6868 } 6869 .width(this.params.width) 6870 .height(this.params.height) 6871 } 6872 } 6873 6874 @Builder 6875 function ButtonBuilder(params: Params) { 6876 ButtonComponent({ params: params }) 6877 .backgroundColor(Color.Green) 6878 } 6879 6880 @Entry 6881 @Component 6882 struct WebComponent { 6883 @State embedVisibility: string = ''; 6884 controller: webview.WebviewController = new webview.WebviewController(); 6885 private nodeController: MyNodeController = new MyNodeController(); 6886 6887 build() { 6888 Column() { 6889 Stack() { 6890 NodeContainer(this.nodeController) 6891 Web({ src: $rawfile("index.html"), controller: this.controller }) 6892 .enableNativeEmbedMode(true) 6893 .onNativeEmbedLifecycleChange((embed) => { 6894 if (embed.status == NativeEmbedStatus.CREATE) { 6895 this.nodeController.setRenderOption({ 6896 surfaceId: embed.surfaceId as string, 6897 renderType: NodeRenderType.RENDER_TYPE_TEXTURE, 6898 width: px2vp(embed.info?.width), 6899 height: px2vp(embed.info?.height) 6900 }); 6901 this.nodeController.rebuild(); 6902 } 6903 }) 6904 .onNativeEmbedVisibilityChange((embed) => { 6905 if (embed.visibility) { 6906 this.embedVisibility = 'Visible'; 6907 } else { 6908 this.embedVisibility = 'Hidden'; 6909 } 6910 console.log("embedId = " + embed.embedId); 6911 console.log("visibility = " + embed.visibility); 6912 }) 6913 } 6914 } 6915 } 6916 } 6917 ``` 6918 6919 HTML file to be loaded: 6920 ```html 6921 <!-- index.html --> 6922 <!DOCTYPE html> 6923 <html> 6924 <head> 6925 <title>Same-layer rendering test HTML</title> 6926 <meta name="viewport"> 6927 </head> 6928 <body> 6929 <div> 6930 <div id="bodyId"> 6931 <embed id="nativeButton" type = "native/button" width="800" height="800" src="test?params1=1?" style = "background-color:red"/> 6932 </div> 6933 </div> 6934 </body> 6935 </html> 6936 ``` 6937 6938## WebKeyboardCallback<sup>12+</sup> 6939 6940type WebKeyboardCallback = (keyboardCallbackInfo: WebKeyboardCallbackInfo) => WebKeyboardOptions 6941 6942Called to intercept the soft keyboard from editable elements on a web page. This event is typically called when the **\<input>** tag on the web page is clicked. 6943 6944**System capability**: SystemCapability.Web.Webview.Core 6945 6946**Parameters** 6947 6948| Name | Type | Mandatory | Description | 6949| ------------- | ------ | ---- | ------------------ | 6950| keyboardCallbackInfo | [WebKeyboardCallbackInfo](#webkeyboardcallbackinfo12) | Yes | Input parameter of the callback for intercepting the soft keyboard from editable elements on a web page, including [WebKeyboardController](#webkeyboardcontroller12) and editable element attributes. | 6951 6952**Return value** 6953 6954| Type | Description | 6955| ------------------ | ------------------------------------------------------------ | 6956| [WebKeyboardOptions](#webkeyboardoptions12) | [WebKeyboardOptions](#webkeyboardoptions12) instance, which is used to determine which type of soft keyboard to start by the ArkWeb rendering engine.| 6957 6958## WebKeyboardCallbackInfo<sup>12+</sup> 6959 6960Represents the input parameter of the callback for intercepting the soft keyboard from editable elements on a web page, including [WebKeyboardController](#webkeyboardcontroller12) and editable element attributes. 6961 6962**System capability**: SystemCapability.Web.Webview.Core 6963 6964| Name | Type | Mandatory | Description | 6965| -------------- | ------- | ---- | ---------------------------------------- | 6966| controller | [WebKeyboardController](#webkeyboardcontroller12) | Yes | Controller used to control the input, deletion, and closure of the custom keyboard.| 6967| attributes | Record<string, string> | Yes | Attributes of the web page element that triggered the soft keyboard to pop up. 6968 6969## WebKeyboardOptions<sup>12+</sup> 6970 6971Represents the return value of the callback that intercepts the soft keyboard from editable elements on the web page. You can specify the type of the keyboard to be used, and it is returned to the Web kernel to display a keyboard of the corresponding type. 6972 6973**System capability**: SystemCapability.Web.Webview.Core 6974 6975| Name | Type | Mandatory | Description | 6976| -------------- | ------- | ---- | ---------------------------------------- | 6977| useSystemKeyboard | boolean | Yes | Whether to use the system's default soft keyboard.| 6978| enterKeyType | number | No | Type of the Enter key of the system soft keyboard. For details about the value range, see [EnterKeyType](../apis-ime-kit/js-apis-inputmethod.md#enterkeytype10). This parameter has effect only when **useSystemKeyboard** is set to **true** and **enterKeyType** is set to a valid value.| 6979| customKeyboard | [CustomBuilder](../apis-arkui/arkui-ts/ts-types.md#custombuilder8) | No | Builder of a custom keyboard. This parameter is required when **useSystemKeyboard** is set to **false**. After it is set, the **Web** component starts the custom keyboard as configured. 6980 6981## WebKeyboardController<sup>12+</sup> 6982 6983Implements a controller to control the input, deletion, and closure of the custom keyboard. For details about the sample code, see [onInterceptKeyboardAttach](#oninterceptkeyboardattach12). 6984 6985### constructor<sup>12+</sup> 6986 6987constructor() 6988 6989Constructs the **WebKeyboardController** API. 6990 6991**System capability**: SystemCapability.Web.Webview.Core 6992 6993### insertText<sup>12+</sup> 6994 6995insertText(text: string): void 6996 6997Inserts a character. 6998 6999**System capability**: SystemCapability.Web.Webview.Core 7000 7001**Parameters** 7002 7003| Name| Type| Mandatory| Description| 7004| ------ | -------- | ---- | --------------------- | 7005| text | string | Yes| Character to insert into the **Web** component text box.| 7006 7007### deleteForward<sup>12+</sup> 7008 7009deleteForward(length: number): void 7010 7011Deletes characters from the end to the beginning for the length specified by the **length** parameter. 7012 7013**System capability**: SystemCapability.Web.Webview.Core 7014 7015**Parameters** 7016 7017| Name| Type| Mandatory| Description | 7018| ------ | -------- | ---- | ------------------------ | 7019| length | number | Yes | Length of characters to be deleted from the end to the beginning.| 7020 7021### deleteBackward12+</sup> 7022 7023deleteBackward(length: number): void 7024 7025Deletes characters from the beginning to the end for the length specified by the **length** parameter. 7026 7027**System capability**: SystemCapability.Web.Webview.Core 7028 7029**Parameters** 7030 7031| Name| Type| Mandatory| Description | 7032| ------ | -------- | ---- | ------------------------ | 7033| length | number | Yes | Length of characters to be deleted from the beginning to the end.| 7034 7035### sendFunctionKey<sup>12+</sup> 7036 7037sendFunctionKey(key: number): void 7038 7039Inserts a function key. Currently, only the Enter key type is supported. For details about the value, see [EnterKeyType](../apis-ime-kit/js-apis-inputmethod.md#enterkeytype10). 7040 7041**System capability**: SystemCapability.Web.Webview.Core 7042 7043**Parameters** 7044 7045| Name| Type| Mandatory| Description | 7046| ------ | -------- | ---- | ------------------------------------------ | 7047| key | number | Yes | Function key to insert into the **Web** component text box. Currently, only the Enter key is supported.| 7048 7049### close<sup>12+</sup> 7050 7051close(): void 7052 7053Closes this custom keyboard. 7054 7055**System capability**: SystemCapability.Web.Webview.Core 7056 7057## ConsoleMessage 7058 7059Implements the **ConsoleMessage** object. For the sample code, see [onConsole](#onconsole). 7060 7061### constructor 7062 7063constructor(message: string, sourceId: string, lineNumber: number, messageLevel: MessageLevel) 7064 7065Constructs the **ConsoleMessage** object. 7066 7067> **NOTE** 7068> 7069> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor](#constructor9) instead. 7070 7071**System capability**: SystemCapability.Web.Webview.Core 7072 7073### constructor<sup>9+</sup> 7074 7075constructor() 7076 7077Constructs the **ConsoleMessage** object. 7078 7079**System capability**: SystemCapability.Web.Webview.Core 7080 7081### getLineNumber 7082 7083getLineNumber(): number 7084 7085Obtains the number of rows in this console message. 7086 7087**System capability**: SystemCapability.Web.Webview.Core 7088 7089**Return value** 7090 7091| Type | Description | 7092| ------ | -------------------- | 7093| number | Number of rows in the console message.| 7094 7095### getMessage 7096 7097getMessage(): string 7098 7099Obtains the log information of this console message. 7100 7101**System capability**: SystemCapability.Web.Webview.Core 7102 7103**Return value** 7104 7105| Type | Description | 7106| ------ | ---------------------- | 7107| string | Log information of the console message.| 7108 7109### getMessageLevel 7110 7111getMessageLevel(): MessageLevel 7112 7113Obtains the level of this console message. 7114 7115**System capability**: SystemCapability.Web.Webview.Core 7116 7117**Return value** 7118 7119| Type | Description | 7120| --------------------------------- | ---------------------- | 7121| [MessageLevel](#messagelevel)| Level of the console message.| 7122 7123### getSourceId 7124 7125getSourceId(): string 7126 7127Obtains the path and name of the web page source file. 7128 7129**System capability**: SystemCapability.Web.Webview.Core 7130 7131**Return value** 7132 7133| Type | Description | 7134| ------ | ------------- | 7135| string | Path and name of the web page source file.| 7136 7137## JsResult 7138 7139Implements the **JsResult** object, which indicates the result returned to the **Web** component to indicate the user operation performed in the dialog box. For the sample code, see [onAlert Event](#onalert). 7140 7141### constructor 7142 7143constructor() 7144 7145Constructs the **JsResult** object. 7146 7147**System capability**: SystemCapability.Web.Webview.Core 7148 7149### handleCancel 7150 7151handleCancel(): void 7152 7153Notifies the **Web** component of the user's cancel operation in the dialog box. 7154 7155**System capability**: SystemCapability.Web.Webview.Core 7156 7157### handleConfirm 7158 7159handleConfirm(): void 7160 7161Notifies the **Web** component of the user's confirm operation in the dialog box. 7162 7163**System capability**: SystemCapability.Web.Webview.Core 7164 7165### handlePromptConfirm<sup>9+</sup> 7166 7167handlePromptConfirm(result: string): void 7168 7169Notifies the **Web** component of the user's confirm operation in the dialog box as well as the dialog box content. 7170 7171**System capability**: SystemCapability.Web.Webview.Core 7172 7173**Parameters** 7174 7175| Name | Type | Mandatory | Description | 7176| ------ | ------ | ---- | ----------- | 7177| result | string | Yes | User input in the dialog box.| 7178 7179## FullScreenExitHandler<sup>9+</sup> 7180 7181Implements a **FullScreenExitHandler** object for listening for exiting full screen mode. For the sample code, see [onFullScreenEnter](#onfullscreenenter9). 7182 7183### constructor<sup>9+</sup> 7184 7185constructor() 7186 7187Constructs the **FullScreenExitHandler** API. 7188 7189**System capability**: SystemCapability.Web.Webview.Core 7190 7191### exitFullScreen<sup>9+</sup> 7192 7193exitFullScreen(): void 7194 7195Called when the **Web** component exits full screen mode. 7196 7197**System capability**: SystemCapability.Web.Webview.Core 7198 7199## ControllerHandler<sup>9+</sup> 7200 7201Implements a **WebviewController** object for new **Web** components. For the sample code, see [onWindowNew](#onwindownew9). 7202 7203**System capability**: SystemCapability.Web.Webview.Core 7204 7205### constructor<sup>9+</sup> 7206 7207constructor() 7208 7209Constructs the **ControllerHandler** API. 7210 7211**System capability**: SystemCapability.Web.Webview.Core 7212 7213### setWebController<sup>9+</sup> 7214 7215setWebController(controller: WebviewController): void 7216 7217Sets a **WebviewController** object. If opening a new window is not needed, set the parameter to **null**. 7218 7219**System capability**: SystemCapability.Web.Webview.Core 7220 7221**Parameters** 7222 7223| Name | Type | Mandatory| Description | 7224| ---------- | ---------------------------------------- | ---- | ---------------------------------------- | 7225| controller | [WebviewController](js-apis-webview.md#webviewcontroller) | Yes | **WebviewController** object of the **Web** component. If opening a new window is not needed, set it to **null**.| 7226 7227## WebResourceError 7228 7229Implements the **WebResourceError** object. For the sample code, see [onErrorReceive](#onerrorreceive). 7230 7231### constructor 7232 7233constructor() 7234 7235Constructs the **WebResourceError** object. 7236 7237**System capability**: SystemCapability.Web.Webview.Core 7238 7239### getErrorCode 7240 7241getErrorCode(): number 7242 7243Obtains the error code for resource loading. 7244 7245**System capability**: SystemCapability.Web.Webview.Core 7246 7247**Return value** 7248 7249| Type | Description | 7250| ------ | ----------- | 7251| number | Error code for resource loading. For details about error codes, see [WebNetErrorList](js-apis-netErrorList.md).| 7252 7253### getErrorInfo 7254 7255getErrorInfo(): string 7256 7257Obtains error information about resource loading. 7258 7259**System capability**: SystemCapability.Web.Webview.Core 7260 7261**Return value** 7262 7263| Type | Description | 7264| ------ | ------------ | 7265| string | Error information about resource loading.| 7266 7267## WebResourceRequest 7268 7269Implements the **WebResourceRequest** object. For the sample code, see [onErrorReceive](#onerrorreceive). 7270 7271### constructor 7272 7273constructor() 7274 7275Constructs the **WebResourceRequest** object. 7276 7277**System capability**: SystemCapability.Web.Webview.Core 7278 7279### getRequestHeader 7280 7281getRequestHeader(): Array\<Header\> 7282 7283Obtains the information about the resource request header. 7284 7285**System capability**: SystemCapability.Web.Webview.Core 7286 7287**Return value** 7288 7289| Type | Description | 7290| -------------------------- | ---------- | 7291| Array\<[Header](#header)\> | Information about the resource request header.| 7292 7293### getRequestUrl 7294 7295getRequestUrl(): string 7296 7297Obtains the URL of the resource request. 7298 7299**System capability**: SystemCapability.Web.Webview.Core 7300 7301**Return value** 7302 7303| Type | Description | 7304| ------ | ------------- | 7305| string | URL of the resource request.| 7306 7307### isMainFrame 7308 7309isMainFrame(): boolean 7310 7311Checks whether the resource request is in the main frame. 7312 7313**System capability**: SystemCapability.Web.Webview.Core 7314 7315**Return value** 7316 7317| Type | Description | 7318| ------- | ---------------- | 7319| boolean | Whether the resource request is in the main frame.| 7320 7321### isRedirect 7322 7323isRedirect(): boolean 7324 7325Checks whether the resource request is redirected by the server. 7326 7327**System capability**: SystemCapability.Web.Webview.Core 7328 7329**Return value** 7330 7331| Type | Description | 7332| ------- | ---------------- | 7333| boolean | Whether the resource request is redirected by the server.| 7334 7335### isRequestGesture 7336 7337isRequestGesture(): boolean 7338 7339Checks whether the resource request is associated with a gesture (for example, a tap). 7340 7341**System capability**: SystemCapability.Web.Webview.Core 7342 7343**Return value** 7344 7345| Type | Description | 7346| ------- | -------------------- | 7347| boolean | Whether the resource request is associated with a gesture (for example, a tap).| 7348 7349### getRequestMethod<sup>9+</sup> 7350 7351getRequestMethod(): string 7352 7353Obtains the request method. 7354 7355**System capability**: SystemCapability.Web.Webview.Core 7356 7357**Return value** 7358 7359| Type | Description | 7360| ------ | ------- | 7361| string | Request method.| 7362 7363## Header 7364 7365Describes the request/response header returned by the **Web** component. 7366 7367**System capability**: SystemCapability.Web.Webview.Core 7368 7369| Name | Type | Mandatory | Description | 7370| ----------- | ------ | ---- | ------------- | 7371| headerKey | string | Yes | Key of the request/response header. | 7372| headerValue | string | Yes | Value of the request/response header.| 7373 7374## WebResourceResponse 7375 7376Implements the **WebResourceResponse** object. For the sample code, see [onHttpErrorReceive](#onhttperrorreceive). 7377 7378### constructor 7379 7380constructor() 7381 7382Constructs the **WebResourceResponse**. 7383 7384**System capability**: SystemCapability.Web.Webview.Core 7385 7386### getReasonMessage 7387 7388getReasonMessage(): string 7389 7390Obtains the status code description of the resource response. 7391 7392**System capability**: SystemCapability.Web.Webview.Core 7393 7394**Return value** 7395 7396| Type | Description | 7397| ------ | ------------- | 7398| string | Status code description of the resource response.| 7399 7400### getResponseCode 7401 7402getResponseCode(): number 7403 7404Obtains the status code of the resource response. 7405 7406**System capability**: SystemCapability.Web.Webview.Core 7407 7408**Return value** 7409 7410| Type | Description | 7411| ------ | ----------- | 7412| number | Status code of the resource response.| 7413 7414### getResponseData 7415 7416getResponseData(): string 7417 7418Obtains the data in the resource response. 7419 7420**System capability**: SystemCapability.Web.Webview.Core 7421 7422**Return value** 7423 7424| Type | Description | 7425| ------ | --------- | 7426| string | Data in the resource response.| 7427 7428### getResponseEncoding 7429 7430getResponseEncoding(): string 7431 7432Obtains the encoding string of the resource response. 7433 7434**System capability**: SystemCapability.Web.Webview.Core 7435 7436**Return value** 7437 7438| Type | Description | 7439| ------ | ---------- | 7440| string | Encoding string of the resource response.| 7441 7442### getResponseHeader 7443 7444getResponseHeader() : Array\<Header\> 7445 7446Obtains the resource response header. 7447 7448**System capability**: SystemCapability.Web.Webview.Core 7449 7450**Return value** 7451 7452| Type | Description | 7453| -------------------------- | -------- | 7454| Array\<[Header](#header)\> | Resource response header.| 7455 7456### getResponseMimeType 7457 7458getResponseMimeType(): string 7459 7460Obtains the MIME type of the resource response. 7461 7462**System capability**: SystemCapability.Web.Webview.Core 7463 7464**Return value** 7465 7466| Type | Description | 7467| ------ | ------------------ | 7468| string | MIME type of the resource response.| 7469 7470### getResponseDataEx<sup>13+</sup> 7471 7472getResponseDataEx(): string | number | ArrayBuffer | Resource | undefined 7473 7474Obtains the data in the resource response. Multiple data types are supported. 7475 7476**System capability**: SystemCapability.Web.Webview.Core 7477 7478**Return value** 7479 7480|Type|Description| 7481|---|---| 7482|string|String in HTML format.| 7483|number|Handle to the file.| 7484|ArrayBuffer|Binary data.| 7485|[Resource](../apis-arkui/arkui-ts/ts-types.md)|Resource referenced by **$rawfile()**.| 7486|undefined|No available data.| 7487 7488### getResponseIsReady<sup>13+</sup> 7489 7490getResponseIsReady(): boolean 7491 7492Obtains whether the response data is ready. 7493 7494**System capability**: SystemCapability.Web.Webview.Core 7495 7496**Return value** 7497 7498|Type|Description| 7499|---|---| 7500|boolean|**true** indicates that the response data is ready, and **false** indicates that the response data is not ready.| 7501 7502### setResponseData<sup>9+</sup> 7503 7504setResponseData(data: string \| number \| Resource \| ArrayBuffer): void 7505 7506Sets the data in the resource response. 7507 7508**System capability**: SystemCapability.Web.Webview.Core 7509 7510**Parameters** 7511 7512| Name | Type | Mandatory | Description | 7513| ---- | ---------------------------------------- | ---- | ---------------------------------------- | 7514| data | string \| number \| [Resource](../apis-arkui/arkui-ts/ts-types.md)<sup>10+</sup> \| ArrayBuffer<sup>11+</sup> | Yes | Resource response data to set. When set to a string, the value indicates a string in HTML format. When set to a number, the value indicates a file handle, which is closed by the system **Web** component. When set to a **Resource** object, the value indicates the file resources in the **rawfile** directory of the application. When set to an **ArrayBuffer** object, the value indicates the original binary data of a resource.| 7515 7516### setResponseEncoding<sup>9+</sup> 7517 7518setResponseEncoding(encoding: string): void 7519 7520Sets the encoding string of the resource response. 7521 7522**System capability**: SystemCapability.Web.Webview.Core 7523 7524**Parameters** 7525 7526| Name | Type | Mandatory | Description | 7527| -------- | ------ | ---- | ------------ | 7528| encoding | string | Yes | Encoding string to set.| 7529 7530### setResponseMimeType<sup>9+</sup> 7531 7532setResponseMimeType(mimeType: string): void 7533 7534Sets the MIME type of the resource response. 7535 7536**System capability**: SystemCapability.Web.Webview.Core 7537 7538**Parameters** 7539 7540| Name | Type | Mandatory | Description | 7541| -------- | ------ | ---- | -------------------- | 7542| mimeType | string | Yes | MIME type to set.| 7543 7544### setReasonMessage<sup>9+</sup> 7545 7546setReasonMessage(reason: string): void 7547 7548Sets the status code description of the resource response. 7549 7550**System capability**: SystemCapability.Web.Webview.Core 7551 7552**Parameters** 7553 7554| Name | Type | Mandatory | Description | 7555| ------ | ------ | ---- | --------------- | 7556| reason | string | Yes | Status code description to set.| 7557 7558### setResponseHeader<sup>9+</sup> 7559 7560setResponseHeader(header: Array\<Header\>): void 7561 7562Sets the resource response header. 7563 7564**System capability**: SystemCapability.Web.Webview.Core 7565 7566**Parameters** 7567 7568| Name | Type | Mandatory | Description | 7569| ------ | -------------------------- | ---- | ---------- | 7570| header | Array\<[Header](#header)\> | Yes | Resource response header to set.| 7571 7572### setResponseCode<sup>9+</sup> 7573 7574setResponseCode(code: number): void 7575 7576Sets the status code of the resource response. 7577 7578**System capability**: SystemCapability.Web.Webview.Core 7579 7580**Parameters** 7581 7582| Name | Type | Mandatory | Description | 7583| ---- | ------ | ---- | ------------- | 7584| code | number | Yes | Status code to set. If the resource ends with an error, set the error code by referring to [@ohos.web.netErrorList](js-apis-netErrorList.md). Do not set the error code to **ERR_IO_PENDING**, which may block the synchronous **XMLHttpRequest**.| 7585 7586### setResponseIsReady<sup>9+</sup> 7587 7588setResponseIsReady(IsReady: boolean): void 7589 7590Sets whether the resource response data is ready. 7591 7592**System capability**: SystemCapability.Web.Webview.Core 7593 7594**Parameters** 7595 7596| Name | Type | Mandatory | Description | 7597| ------- | ------- | ---- | ------------- | 7598| IsReady | boolean | Yes | Whether the resource response data is ready. Default value: **true**| 7599 7600## FileSelectorResult<sup>9+</sup> 7601 7602Notifies the **Web** component of the file selection result. For the sample code, see [onShowFileSelector](#onshowfileselector9). 7603 7604### constructor<sup>9+</sup> 7605 7606constructor() 7607 7608Constructs the **FileSelectorResult**. 7609 7610**System capability**: SystemCapability.Web.Webview.Core 7611 7612### handleFileList<sup>9+</sup> 7613 7614handleFileList(fileList: Array\<string\>): void 7615 7616Instructs the **Web** component to select a file. 7617 7618**System capability**: SystemCapability.Web.Webview.Core 7619 7620**Parameters** 7621 7622| Name | Type | Mandatory | Description | 7623| -------- | --------------- | ---- | ------------ | 7624| fileList | Array\<string\> | Yes | List of files to operate.| 7625 7626## FileSelectorParam<sup>9+</sup> 7627 7628Implements the **FileSelectorParam** object. For the sample code, see [onShowFileSelector](#onshowfileselector9). 7629 7630### constructor<sup>9+</sup> 7631 7632constructor() 7633 7634Constructs the **FileSelectorParam**. 7635 7636**System capability**: SystemCapability.Web.Webview.Core 7637 7638### getTitle<sup>9+</sup> 7639 7640getTitle(): string 7641 7642Obtains the title of this file selector. 7643 7644**System capability**: SystemCapability.Web.Webview.Core 7645 7646**Return value** 7647 7648| Type | Description | 7649| ------ | ---------- | 7650| string | Title of the file selector.| 7651 7652### getMode<sup>9+</sup> 7653 7654getMode(): FileSelectorMode 7655 7656Obtains the mode of the file selector. 7657 7658**System capability**: SystemCapability.Web.Webview.Core 7659 7660**Return value** 7661 7662| Type | Description | 7663| ---------------------------------------- | ----------- | 7664| [FileSelectorMode](#fileselectormode9) | Mode of the file selector.| 7665 7666### getAcceptType<sup>9+</sup> 7667 7668getAcceptType(): Array\<string\> 7669 7670Obtains the file filtering type. 7671 7672**System capability**: SystemCapability.Web.Webview.Core 7673 7674**Return value** 7675 7676| Type | Description | 7677| --------------- | --------- | 7678| Array\<string\> | File filtering type.| 7679 7680### isCapture<sup>9+</sup> 7681 7682isCapture(): boolean 7683 7684Checks whether multimedia capabilities are invoked. 7685 7686**System capability**: SystemCapability.Web.Webview.Core 7687 7688**Return value** 7689 7690| Type | Description | 7691| ------- | ------------ | 7692| boolean | Whether multimedia capabilities are invoked.| 7693 7694## HttpAuthHandler<sup>9+</sup> 7695 7696Implements the **HttpAuthHandler** object. For the sample code, see [onHttpAuthRequest](#onhttpauthrequest9). 7697 7698### constructor<sup>9+</sup> 7699 7700constructor() 7701 7702Constructs the **HttpAuthHandler**. 7703 7704**System capability**: SystemCapability.Web.Webview.Core 7705 7706### cancel<sup>9+</sup> 7707 7708cancel(): void 7709 7710Cancels HTTP authentication as requested by the user. 7711 7712**System capability**: SystemCapability.Web.Webview.Core 7713 7714### confirm<sup>9+</sup> 7715 7716confirm(userName: string, password: string): boolean 7717 7718Performs HTTP authentication with the user name and password provided by the user. 7719 7720**System capability**: SystemCapability.Web.Webview.Core 7721 7722**Parameters** 7723 7724| Name | Type | Mandatory | Description | 7725| -------- | ------ | ---- | ---------- | 7726| userName | string | Yes | HTTP authentication user name.| 7727| password | string | Yes | HTTP authentication password. | 7728 7729**Return value** 7730 7731| Type | Description | 7732| ------- | --------------------- | 7733| boolean | Returns **true** if the authentication is successful; returns **false** otherwise.| 7734 7735### isHttpAuthInfoSaved<sup>9+</sup> 7736 7737isHttpAuthInfoSaved(): boolean 7738 7739Sets whether to use the account name and password cached on the server for authentication. 7740 7741**System capability**: SystemCapability.Web.Webview.Core 7742 7743**Return value** 7744 7745| Type | Description | 7746| ------- | ------------------------- | 7747| boolean | Returns **true** if the authentication is successful; returns **false** otherwise.| 7748 7749## SslErrorHandler<sup>9+</sup> 7750 7751Implements an **SslErrorHandler** object. For the sample code, see [onSslErrorEventReceive Event](#onsslerroreventreceive9). 7752 7753### constructor<sup>9+</sup> 7754 7755constructor() 7756 7757Constructs the **SslErrorHandler**. 7758 7759**System capability**: SystemCapability.Web.Webview.Core 7760 7761### handleCancel<sup>9+</sup> 7762 7763handleCancel(): void 7764 7765Cancels this request. 7766 7767**System capability**: SystemCapability.Web.Webview.Core 7768 7769### handleConfirm<sup>9+</sup> 7770 7771handleConfirm(): void 7772 7773Continues using the SSL certificate. 7774 7775**System capability**: SystemCapability.Web.Webview.Core 7776 7777## ClientAuthenticationHandler<sup>9+</sup> 7778 7779Implements a **ClientAuthenticationHandler** object returned by the **Web** component. For the sample code, see [onClientAuthenticationRequest](#onclientauthenticationrequest9). 7780 7781### constructor<sup>9+</sup> 7782 7783constructor() 7784 7785Constructs the **ClientAuthenticationHandler**. 7786 7787**System capability**: SystemCapability.Web.Webview.Core 7788 7789### confirm<sup>9+</sup> 7790 7791confirm(priKeyFile : string, certChainFile : string): void 7792 7793Uses the specified private key and client certificate chain. 7794 7795**System capability**: SystemCapability.Web.Webview.Core 7796 7797**Parameters** 7798 7799| Name | Type | Mandatory | Description | 7800| ------------- | ------ | ---- | ------------------ | 7801| priKeyFile | string | Yes | File that stores the private key, which is a directory including the file name. | 7802| certChainFile | string | Yes | File that stores the certificate chain, which is a directory including the file name.| 7803 7804### confirm<sup>10+</sup> 7805 7806confirm(authUri : string): void 7807 7808Instructs the **Web** component to use the specified credentials (obtained from the certificate management module). 7809 7810> **NOTE** 7811> 7812> The **ohos.permission.ACCESS_CERT_MANAGER** permission must be declared. 7813 7814**System capability**: SystemCapability.Web.Webview.Core 7815 7816**Parameters** 7817 7818| Name | Type | Mandatory | Description | 7819| ------- | ------ | ---- | ------- | 7820| authUri | string | Yes | Key value of the credentials.| 7821 7822### cancel<sup>9+</sup> 7823 7824cancel(): void 7825 7826Cancels the client certificate request sent by the same host and port server. No additional event will be reported for requests from the same host and port server. 7827 7828**System capability**: SystemCapability.Web.Webview.Core 7829 7830### ignore<sup>9+</sup> 7831 7832ignore(): void 7833 7834Ignores this request. 7835 7836**System capability**: SystemCapability.Web.Webview.Core 7837 7838## PermissionRequest<sup>9+</sup> 7839 7840Implements the **PermissionRequest** object. For the sample code, see [onPermissionRequest](#onpermissionrequest9). 7841 7842### constructor<sup>9+</sup> 7843 7844constructor() 7845 7846Constructs the **PermissionRequest** object. 7847 7848**System capability**: SystemCapability.Web.Webview.Core 7849 7850### deny<sup>9+</sup> 7851 7852deny(): void 7853 7854Denies the permission requested by the web page. 7855 7856**System capability**: SystemCapability.Web.Webview.Core 7857 7858### getOrigin<sup>9+</sup> 7859 7860getOrigin(): string 7861 7862Obtains the origin of this web page. 7863 7864**System capability**: SystemCapability.Web.Webview.Core 7865 7866**Return value** 7867 7868| Type | Description | 7869| ------ | ------------ | 7870| string | Origin of the web page that requests the permission.| 7871 7872### getAccessibleResource<sup>9+</sup> 7873 7874getAccessibleResource(): Array\<string\> 7875 7876Obtains the list of accessible resources requested for the web page. For details about the resource types, see [ProtectedResourceType](#protectedresourcetype9). 7877 7878**System capability**: SystemCapability.Web.Webview.Core 7879 7880**Return value** 7881 7882| Type | Description | 7883| --------------- | ------------- | 7884| Array\<string\> | List of accessible resources requested by the web page.| 7885 7886### grant<sup>9+</sup> 7887 7888grant(resources: Array\<string\>): void 7889 7890Grants the permission for resources requested by the web page. 7891 7892**System capability**: SystemCapability.Web.Webview.Core 7893 7894**Parameters** 7895 7896| Name | Type | Mandatory | Description | 7897| --------- | --------------- | ---- | --------------- | 7898| resources | Array\<string\> | Yes | List of resources that can be requested by the web page with the permission to grant.| 7899 7900## ScreenCaptureHandler<sup>10+</sup> 7901 7902Implements the **ScreenCaptureHandler** object for accepting or rejecting a screen capture request. For the sample code, see [onScreenCaptureRequest Event](#onscreencapturerequest10). 7903 7904### constructor<sup>10+</sup> 7905 7906constructor() 7907 7908Constructs the **ScreenCaptureHandler** object. 7909 7910**System capability**: SystemCapability.Web.Webview.Core 7911 7912### deny<sup>10+</sup> 7913 7914deny(): void 7915 7916Rejects this screen capture request. 7917 7918**System capability**: SystemCapability.Web.Webview.Core 7919 7920### getOrigin<sup>10+</sup> 7921 7922getOrigin(): string 7923 7924Obtains the origin of this web page. 7925 7926**System capability**: SystemCapability.Web.Webview.Core 7927 7928**Return value** 7929 7930| Type | Description | 7931| ------ | ------------ | 7932| string | Origin of the web page that requests the permission.| 7933 7934### grant<sup>10+</sup> 7935 7936grant(config: ScreenCaptureConfig): void 7937 7938Grants the screen capture permission. 7939 7940> **NOTE** 7941> 7942> The **ohos.permission.MICROPHONE** permission must be declared. 7943 7944**System capability**: SystemCapability.Web.Webview.Core 7945 7946**Parameters** 7947 7948| Name | Type | Mandatory | Description | 7949| ------ | ---------------------------------------- | ---- | ------- | 7950| config | [ScreenCaptureConfig](#screencaptureconfig10) | Yes | Screen capture configuration.| 7951 7952## EventResult<sup>12+</sup> 7953 7954Represents the event consumption result sent to the **Web** component. For details about the supported events, see [TouchType](../apis-arkui/arkui-ts/ts-appendix-enums.md#touchtype). If the application does not consume the event, set this parameter to **false**, and the event will be consumed by the **Web** component. If the application has consumed the event, set this parameter to **true**, and the event will not be consumed by the **Web** component. For the sample code, see [onNativeEmbedGestureEvent](#onnativeembedgestureevent11). 7955 7956### constructor<sup>12+</sup> 7957 7958constructor() 7959 7960Constructs the EventResult object. 7961 7962**System capability**: SystemCapability.Web.Webview.Core 7963 7964### setGestureEventResult<sup>12+</sup> 7965 7966Sets the gesture event consumption result. 7967 7968setGestureEventResult(result: boolean): void 7969 7970**System capability**: SystemCapability.Web.Webview.Core 7971 7972**Parameters** 7973 7974| Name | Type| Mandatory | Description | 7975| --------------- | -------- | ---- |------- | 7976| result | boolean | Yes | Whether to consume the gesture event. Default value: **true**| 7977 7978**Example** 7979 7980See [onNativeEmbedGestureEvent](#onnativeembedgestureevent11). 7981 7982### setGestureEventResult<sup>14+</sup> 7983 7984Sets the gesture event consumption result. 7985 7986setGestureEventResult(result: boolean, stopPropagation?: boolean): void 7987 7988**System capability**: SystemCapability.Web.Webview.Core 7989 7990**Parameters** 7991 7992| Name | Type| Mandatory | Description | 7993| --------------- | -------- | ---- |------- | 7994| result | boolean | Yes | Whether to consume the gesture event. Default value: **true**| 7995| stopPropagation<sup>14+</sup>| boolean | No | Whether to stop propagation. This parameter is valid only when **result** is set to **true**. Default value: **true**| 7996 7997**Example** 7998 7999See [onNativeEmbedGestureEvent](#onnativeembedgestureevent11). 8000 8001## ContextMenuSourceType<sup>9+</sup> 8002 8003**System capability**: SystemCapability.Web.Webview.Core 8004 8005| Name | Value| Description | 8006| --------- | -- |------------ | 8007| None | 0 | Other event sources.| 8008| Mouse | 1 | Mouse event. | 8009| LongPress | 2 | Long press event. | 8010 8011## ContextMenuMediaType<sup>9+</sup> 8012 8013**System capability**: SystemCapability.Web.Webview.Core 8014 8015| Name | Value| Description | 8016| ----- | -- | ------------- | 8017| None | 0 | Non-special media or other media types.| 8018| Image | 1 | Image. | 8019 8020## ContextMenuInputFieldType<sup>9+</sup> 8021 8022**System capability**: SystemCapability.Web.Webview.Core 8023 8024| Name | Value| Description | 8025| --------- | -- | --------------------------- | 8026| None | 0 | Non-input field. | 8027| PlainText | 1 | Plain text field, such as the text, search, or email field.| 8028| Password | 2 | Password field. | 8029| Number | 3 | Numeric field. | 8030| Telephone | 4 | Phone number field. | 8031| Other | 5 | Field of any other type. | 8032 8033## ContextMenuEditStateFlags<sup>9+</sup> 8034 8035Supports using with a bitwise OR operator. For example, to support CAN_CUT, CAN_COPY, and CAN_SELECT_ALL at the same time, use CAN_CUT | CAN_COPY | CAN_SELECT_ALL or 11. 8036 8037**System capability**: SystemCapability.Web.Webview.Core 8038 8039| Name | Value| Description | 8040| -------------- | -- | -------- | 8041| NONE | 0 | Editing is not allowed.| 8042| CAN_CUT | 1 | The cut operation is allowed.| 8043| CAN_COPY | 2 | The copy operation is allowed.| 8044| CAN_PASTE | 4 | The paste operation is allowed.| 8045| CAN_SELECT_ALL | 8 | The select all operation is allowed.| 8046 8047## WebContextMenuParam<sup>9+</sup> 8048 8049Implements a context menu, which is displayed after the user clicks the right mouse button or long presses a specific element, such as an image or a link. For the sample code, see [onContextMenuShow](#oncontextmenushow9). 8050 8051### constructor<sup>9+</sup> 8052 8053constructor() 8054 8055Constructs the **WebContextMenuParam** object. 8056 8057**System capability**: SystemCapability.Web.Webview.Core 8058 8059### x<sup>9+</sup> 8060 8061x(): number 8062 8063Obtains the X coordinate of the context menu. 8064 8065**System capability**: SystemCapability.Web.Webview.Core 8066 8067**Return value** 8068 8069| Type | Description | 8070| ------ | ------------------ | 8071| number | If the display is normal, a non-negative integer is returned. Otherwise, **-1** is returned.| 8072 8073### y<sup>9+</sup> 8074 8075y(): number 8076 8077Obtains the Y coordinate of the context menu. 8078 8079**System capability**: SystemCapability.Web.Webview.Core 8080 8081**Return value** 8082 8083| Type | Description | 8084| ------ | ------------------ | 8085| number | If the display is normal, a non-negative integer is returned. Otherwise, **-1** is returned.| 8086 8087### getLinkUrl<sup>9+</sup> 8088 8089getLinkUrl(): string 8090 8091Obtains the URL of the destination link. 8092 8093**System capability**: SystemCapability.Web.Webview.Core 8094 8095**Return value** 8096 8097| Type | Description | 8098| ------ | ------------------------- | 8099| string | If it is a link that is being long pressed, the URL that has passed the security check is returned.| 8100 8101### getUnfilteredLinkUrl<sup>9+</sup> 8102 8103getUnfilteredLinkUrl(): string 8104 8105Obtains the URL of the destination link. 8106 8107**System capability**: SystemCapability.Web.Webview.Core 8108 8109**Return value** 8110 8111| Type | Description | 8112| ------ | --------------------- | 8113| string | If it is a link that is being long pressed, the original URL is returned.| 8114 8115### getSourceUrl<sup>9+</sup> 8116 8117getSourceUrl(): string 8118 8119Obtain the source URL. 8120 8121**System capability**: SystemCapability.Web.Webview.Core 8122 8123**Return value** 8124 8125| Type | Description | 8126| ------ | ------------------------ | 8127| string | If the selected element has the **src** attribute, the URL in the **src** is returned.| 8128 8129### existsImageContents<sup>9+</sup> 8130 8131existsImageContents(): boolean 8132 8133Checks whether image content exists. 8134 8135**System capability**: SystemCapability.Web.Webview.Core 8136 8137**Return value** 8138 8139| Type | Description | 8140| ------- | ------------------------- | 8141| boolean | The value **true** means that there is image content in the element being long pressed, and **false** means the opposite.| 8142 8143### getMediaType<sup>9+</sup> 8144 8145getMediaType(): ContextMenuMediaType 8146 8147Obtains the media type of this web page element. 8148 8149**System capability**: SystemCapability.Web.Webview.Core 8150 8151**Return value** 8152 8153| Type | Description | 8154| ---------------------------------------- | --------- | 8155| [ContextMenuMediaType](#contextmenumediatype9) | Media type of the web page element.| 8156 8157### getSelectionText<sup>9+</sup> 8158 8159getSelectionText(): string 8160 8161Obtains the selected text. 8162 8163**System capability**: SystemCapability.Web.Webview.Core 8164 8165**Return value** 8166 8167| Type | Description | 8168| ------ | -------------------- | 8169| string | Selected text for the context menu. If no text is selected, null is returned.| 8170 8171### getSourceType<sup>9+</sup> 8172 8173getSourceType(): ContextMenuSourceType 8174 8175Obtains the event source of the context menu. 8176 8177**System capability**: SystemCapability.Web.Webview.Core 8178 8179**Return value** 8180 8181| Type | Description | 8182| ---------------------------------------- | ------- | 8183| [ContextMenuSourceType](#contextmenusourcetype9) | Event source of the context menu.| 8184 8185### getInputFieldType<sup>9+</sup> 8186 8187getInputFieldType(): ContextMenuInputFieldType 8188 8189Obtains the input field type of this web page element. 8190 8191**System capability**: SystemCapability.Web.Webview.Core 8192 8193**Return value** 8194 8195| Type | Description | 8196| ---------------------------------------- | ------ | 8197| [ContextMenuInputFieldType](#contextmenuinputfieldtype9) | Input field type.| 8198 8199### isEditable<sup>9+</sup> 8200 8201isEditable(): boolean 8202 8203Checks whether this web page element is editable. 8204 8205**System capability**: SystemCapability.Web.Webview.Core 8206 8207**Return value** 8208 8209| Type | Description | 8210| ------- | -------------------------- | 8211| boolean | Returns **true** if the web page element is editable; returns **false** otherwise.| 8212 8213### getEditStateFlags<sup>9+</sup> 8214 8215getEditStateFlags(): number 8216 8217Obtains the edit state flag of this web page element. 8218 8219**System capability**: SystemCapability.Web.Webview.Core 8220 8221**Return value** 8222 8223| Type | Description | 8224| ------ | ---------------------------------------- | 8225| number | Edit state flag of the web page element. For details, see [ContextMenuEditStateFlags](#contextmenueditstateflags9).| 8226 8227### getPreviewWidth<sup>13+</sup> 8228 8229getPreviewWidth(): number 8230 8231Obtains the width of a preview image. 8232 8233**System capability**: SystemCapability.Web.Webview.Core 8234 8235**Return value** 8236 8237| Type | Description | 8238| ------ | ----------- | 8239| number | Width of a preview image.| 8240 8241### getPreviewHeight<sup>13+</sup> 8242 8243getPreviewHeight(): number 8244 8245Obtains the height of a preview image. 8246 8247**System capability**: SystemCapability.Web.Webview.Core 8248 8249**Return value** 8250 8251| Type | Description | 8252| ------ | ---------- | 8253| number | Height of a preview image.| 8254 8255## WebContextMenuResult<sup>9+</sup> 8256 8257Implements a **WebContextMenuResult** object. For the sample code, see [onContextMenuShow](#oncontextmenushow9). 8258 8259### constructor<sup>9+</sup> 8260 8261constructor() 8262 8263Constructs the **WebContextMenuResult** object. 8264 8265**System capability**: SystemCapability.Web.Webview.Core 8266 8267### closeContextMenu<sup>9+</sup> 8268 8269closeContextMenu(): void 8270 8271Closes this context menu. This API must be called when no operations in **WebContextMenuResult** are performed. 8272 8273**System capability**: SystemCapability.Web.Webview.Core 8274 8275### copyImage<sup>9+</sup> 8276 8277copyImage(): void 8278 8279Copies the image specified in **WebContextMenuParam**. 8280 8281**System capability**: SystemCapability.Web.Webview.Core 8282 8283### copy<sup>9+</sup> 8284 8285copy(): void 8286 8287Copies text related to this context menu. 8288 8289**System capability**: SystemCapability.Web.Webview.Core 8290 8291### paste<sup>9+</sup> 8292 8293paste(): void 8294 8295Performs the paste operation related to this context menu. 8296 8297> **NOTE** 8298> 8299> The **ohos.permission.READ_PASTEBOARD** permission must be declared. 8300 8301**System capability**: SystemCapability.Web.Webview.Core 8302 8303### cut<sup>9+</sup> 8304 8305cut(): void 8306 8307Performs the cut operation related to this context menu. 8308 8309**System capability**: SystemCapability.Web.Webview.Core 8310 8311### selectAll<sup>9+</sup> 8312 8313selectAll(): void 8314 8315Performs the select all operation related to this context menu. 8316 8317**System capability**: SystemCapability.Web.Webview.Core 8318 8319## JsGeolocation 8320 8321Implements the **PermissionRequest** object. For the sample code, see [onGeolocationShow Event](#ongeolocationshow). 8322 8323### constructor 8324 8325constructor() 8326 8327Constructs the **JsGeolocation** object. 8328 8329**System capability**: SystemCapability.Web.Webview.Core 8330 8331### invoke 8332 8333invoke(origin: string, allow: boolean, retain: boolean): void 8334 8335Sets the geolocation permission status of a web page. 8336 8337**System capability**: SystemCapability.Web.Webview.Core 8338 8339**Parameters** 8340 8341| Name | Type | Mandatory | Description | 8342| ------ | ------- | ---- | ---------------------------------------- | 8343| origin | string | Yes | Index of the origin. | 8344| allow | boolean | Yes | Geolocation permission status. | 8345| retain | boolean | Yes | Whether the geolocation permission status can be saved to the system. You can manage the geolocation permissions saved to the system through [GeolocationPermissions<sup>9+</sup>](js-apis-webview.md#geolocationpermissions).| 8346 8347## MessageLevel 8348 8349**System capability**: SystemCapability.Web.Webview.Core 8350 8351| Name | Value| Description | 8352| ----- | -- | ---- | 8353| Debug | 1 | Debug level.| 8354| Error | 4 | Error level.| 8355| Info | 2 | Information level.| 8356| Log | 5 | Log level.| 8357| Warn | 3 | Warning level.| 8358 8359## RenderExitReason<sup>9+</sup> 8360 8361Enumerates the reasons why the rendering process exits. 8362 8363**System capability**: SystemCapability.Web.Webview.Core 8364 8365| Name | Value| Description | 8366| -------------------------- | -- | ----------------- | 8367| ProcessAbnormalTermination | 0 | The rendering process exits abnormally. | 8368| ProcessWasKilled | 1 | The rendering process receives a SIGKILL message or is manually terminated.| 8369| ProcessCrashed | 2 | The rendering process crashes due to segmentation or other errors. | 8370| ProcessOom | 3 | The program memory is running low. | 8371| ProcessExitUnknown | 4 | Other reason. | 8372 8373## MixedMode 8374 8375**System capability**: SystemCapability.Web.Webview.Core 8376 8377| Name | Value| Description | 8378| ---------- | -- | ---------------------------------- | 8379| All | 0 | HTTP and HTTPS hybrid content can be loaded. This means that all insecure content can be loaded.| 8380| Compatible | 1 | HTTP and HTTPS hybrid content can be loaded in compatibility mode. This means that some insecure content may be loaded. | 8381| None | 2 | HTTP and HTTPS hybrid content cannot be loaded. | 8382 8383## CacheMode 8384 8385**System capability**: SystemCapability.Web.Webview.Core 8386 8387| Name | Value| Description | 8388| ------- | -- | ------------------------------------ | 8389| Default<sup>9+</sup> | 0 | The cache that has not expired is preferentially used to load resources. If the cache is invalid or no cache is available, resources are obtained from the network.| 8390| None | 1 | The cache (including expired caches) is preferentially used to load resources. If no cache is available, resources are obtained from the network. | 8391| Online | 2 | The latest resources are forcibly obtained from the network without using any cache. | 8392| Only | 3 | Only the local cache is used to load resources. | 8393 8394## FileSelectorMode<sup>9+</sup> 8395 8396**System capability**: SystemCapability.Web.Webview.Core 8397 8398| Name | Value| Description | 8399| -------------------- | -- | ---------- | 8400| FileOpenMode | 0 | Open and upload a file. | 8401| FileOpenMultipleMode | 1 | Open and upload multiple files. | 8402| FileOpenFolderMode | 2 | Open and upload a folder.| 8403| FileSaveMode | 3 | Save a file. | 8404 8405 ## HitTestType 8406 8407 **System capability**: SystemCapability.Web.Webview.Core 8408 8409| Name | Value| Description | 8410| ------------- | -- | ------------------------ | 8411| EditText | 0 | Editable area. | 8412| Email | 1 | Email address. | 8413| HttpAnchor | 2 | Hyperlink whose **src** is **http**. | 8414| HttpAnchorImg | 3 | Image with a hyperlink, where **src** is **http**.| 8415| Img | 4 | HTML::img tag. | 8416| Map | 5 | Geographical address. | 8417| Phone | 6 | Phone number. | 8418| Unknown | 7 | Unknown content. | 8419 8420 ## OverScrollMode<sup>11+</sup> 8421 8422 **System capability**: SystemCapability.Web.Webview.Core 8423 8424| Name | Value| Description | 8425| ------ | -- | ----------- | 8426| NEVER | 0 | The overscroll mode is disabled.| 8427| ALWAYS | 1 | The overscroll mode is enabled.| 8428 8429## OnContextMenuHideCallback<sup>11+</sup> 8430 8431type OnContextMenuHideCallback = () => void 8432 8433Implements the callback context menu customizes the hidden callback. 8434 8435**System capability**: SystemCapability.Web.Webview.Core 8436 8437## SslError<sup>9+</sup> 8438 8439Enumerates the error codes returned by **onSslErrorEventReceive** API. 8440 8441**System capability**: SystemCapability.Web.Webview.Core 8442 8443| Name | Value| Description | 8444| ------------ | -- | ----------- | 8445| Invalid | 0 | Minor error. | 8446| HostMismatch | 1 | The host name does not match. | 8447| DateInvalid | 2 | The certificate has an invalid date. | 8448| Untrusted | 3 | The certificate issuer is not trusted.| 8449 8450## ProtectedResourceType<sup>9+</sup> 8451 8452**System capability**: SystemCapability.Web.Webview.Core 8453 8454| Name | Value| Description | Remarks | 8455| --------------------------- | --------------- | ------------- | -------------------------- | 8456| MidiSysex | TYPE_MIDI_SYSEX | MIDI SYSEX resource.| Currently, only permission events can be reported. MIDI devices are not yet supported.| 8457| VIDEO_CAPTURE<sup>10+</sup> | TYPE_VIDEO_CAPTURE | Video capture resource, such as a camera. | | 8458| AUDIO_CAPTURE<sup>10+</sup> | TYPE_AUDIO_CAPTURE | Audio capture resource, such as a microphone.| | 8459| SENSOR<sup>12+</sup> | TYPE_SENSOR | Sensor resource, such as an acceleration sensor.| | 8460 8461## WebDarkMode<sup>9+</sup> 8462 8463**System capability**: SystemCapability.Web.Webview.Core 8464 8465| Name | Value| Description | 8466| ---- | -- | ------------ | 8467| Off | 0 | The web dark mode is disabled. | 8468| On | 1 | The web dark mode is enabled. | 8469| Auto | 2 | The web dark mode setting follows the system settings.| 8470 8471## WebCaptureMode<sup>10+</sup> 8472 8473**System capability**: SystemCapability.Web.Webview.Core 8474 8475| Name | Value| Description | 8476| ----------- | -- | ------- | 8477| HOME_SCREEN | 0 | Capture of the home screen.| 8478 8479## WebMediaOptions<sup>10+</sup> 8480 8481Describes the web-based media playback policy. 8482 8483**System capability**: SystemCapability.Web.Webview.Core 8484 8485| Name | Type | Mandatory | Description | 8486| -------------- | ------- | ---- | ---------------------------------------- | 8487| resumeInterval | number | No | Validity period for automatically resuming a paused web audio, in seconds. The maximum validity period is 60 seconds. Due to the approximate value, the validity period may have a deviation of less than 1 second.| 8488| audioExclusive | boolean | No | Whether the audio of multiple **Web** instances in an application is exclusive. | 8489 8490## ScreenCaptureConfig<sup>10+</sup> 8491 8492Provides the web screen capture configuration. 8493 8494**System capability**: SystemCapability.Web.Webview.Core 8495 8496| Name | Type | Mandatory | Description | 8497| ----------- | --------------------------------------- | ---- | ---------- | 8498| captureMode | [WebCaptureMode](#webcapturemode10) | Yes | Web screen capture mode.| 8499 8500## WebLayoutMode<sup>11+</sup> 8501 8502**System capability**: SystemCapability.Web.Webview.Core 8503 8504| Name | Value| Description | 8505| ----------- | -- | ------------------ | 8506| NONE | 0 | The web layout follows the system. | 8507| FIT_CONTENT | 1 | The web layout adapts to the page size.| 8508 8509## NestedScrollOptionsExt<sup>14+</sup> 8510 8511Implements a **NestedScrollOptionsExt** object to set up, down, left, and right nested scrolling options. 8512 8513**System capability**: SystemCapability.Web.Webview.Core 8514 8515| Name | Type | Mandatory | Description | 8516| -------------- | ---------------- | ---- | -------------------- | 8517| scrollUp | [NestedScrollMode](../apis-arkui/arkui-ts/ts-appendix-enums.md#nestedscrollmode10) | No | Nested scrolling options when the component scrolls up.| 8518| scrollDown | [NestedScrollMode](../apis-arkui/arkui-ts/ts-appendix-enums.md#nestedscrollmode10) | No | Nested scrolling options when the component scrolls down.| 8519| scrollLeft | [NestedScrollMode](../apis-arkui/arkui-ts/ts-appendix-enums.md#nestedscrollmode10) | No | Nested scrolling options when the component scrolls left.| 8520| scrollRight | [NestedScrollMode](../apis-arkui/arkui-ts/ts-appendix-enums.md#nestedscrollmode10) | No | Nested scrolling options when the component scrolls right.| 8521 8522## DataResubmissionHandler<sup>9+</sup> 8523 8524Implements the **DataResubmissionHandler** object for resubmitting or canceling the web form data. 8525 8526### constructor<sup>9+</sup> 8527 8528constructor() 8529 8530Constructs the **DataResubmissionHandler** object. 8531 8532**System capability**: SystemCapability.Web.Webview.Core 8533 8534### resend<sup>9+</sup> 8535 8536resend(): void 8537 8538Resends the web form data. 8539 8540**System capability**: SystemCapability.Web.Webview.Core 8541 8542**Example** 8543 8544 ```ts 8545 // xxx.ets 8546 import { webview } from '@kit.ArkWeb'; 8547 8548 @Entry 8549 @Component 8550 struct WebComponent { 8551 controller: webview.WebviewController = new webview.WebviewController(); 8552 8553 build() { 8554 Column() { 8555 Web({ src: 'www.example.com', controller: this.controller }) 8556 .onDataResubmitted((event) => { 8557 console.log('onDataResubmitted'); 8558 event.handler.resend(); 8559 }) 8560 } 8561 } 8562 } 8563 ``` 8564 8565### cancel<sup>9+</sup> 8566 8567cancel(): void 8568 8569Cancels the resending of web form data. 8570 8571**System capability**: SystemCapability.Web.Webview.Core 8572 8573**Example** 8574 8575 ```ts 8576 // xxx.ets 8577 import { webview } from '@kit.ArkWeb'; 8578 8579 @Entry 8580 @Component 8581 struct WebComponent { 8582 controller: webview.WebviewController = new webview.WebviewController(); 8583 8584 build() { 8585 Column() { 8586 Web({ src: 'www.example.com', controller: this.controller }) 8587 .onDataResubmitted((event) => { 8588 console.log('onDataResubmitted'); 8589 event.handler.cancel(); 8590 }) 8591 } 8592 } 8593 } 8594 ``` 8595 8596 ## WebController 8597 8598Implements a **WebController** to control the behavior of the **Web** component. A **WebController** can control only one **Web** component, and the APIs in the **WebController** can be invoked only after it has been bound to the target **Web** component. 8599 8600This API is deprecated since API version 9. You are advised to use [WebviewController<sup>9+</sup>](js-apis-webview.md#webviewcontroller) instead. 8601 8602### Creating an Object 8603 8604<!--code_no_check--> 8605```ts 8606let webController: WebController = new WebController() 8607``` 8608 8609### constructor 8610 8611constructor() 8612 8613Constructs a **WebController** object. 8614 8615> **NOTE** 8616> 8617> This API is supported since API version 8 and deprecated since API version 9. No API is provided for substitute. 8618 8619**System capability**: SystemCapability.Web.Webview.Core 8620 8621### getCookieManager<sup>(deprecated)</sup> 8622 8623getCookieManager(): WebCookie 8624 8625Obtains the cookie management object of the **Web** component. 8626 8627This API is deprecated since API version 9. You are advised to use [getCookie](js-apis-webview.md#getcookiedeprecated) instead. 8628 8629**System capability**: SystemCapability.Web.Webview.Core 8630 8631**Return value** 8632 8633| Type | Description | 8634| --------- | ---------------------------------------- | 8635| WebCookie | Cookie management object. For details, see [WebCookie](#webcookie).| 8636 8637**Example** 8638 8639 ```ts 8640 // xxx.ets 8641 @Entry 8642 @Component 8643 struct WebComponent { 8644 controller: WebController = new WebController() 8645 8646 build() { 8647 Column() { 8648 Button('getCookieManager') 8649 .onClick(() => { 8650 let cookieManager = this.controller.getCookieManager() 8651 }) 8652 Web({ src: 'www.example.com', controller: this.controller }) 8653 } 8654 } 8655 } 8656 ``` 8657 8658### requestFocus<sup>(deprecated)</sup> 8659 8660requestFocus() 8661 8662Requests focus for this web page. 8663 8664This API is deprecated since API version 9. You are advised to use [requestFocus<sup>9+</sup>](js-apis-webview.md#requestfocus) instead. 8665 8666**System capability**: SystemCapability.Web.Webview.Core 8667 8668**Example** 8669 8670 ```ts 8671 // xxx.ets 8672 @Entry 8673 @Component 8674 struct WebComponent { 8675 controller: WebController = new WebController() 8676 8677 build() { 8678 Column() { 8679 Button('requestFocus') 8680 .onClick(() => { 8681 this.controller.requestFocus() 8682 }) 8683 Web({ src: 'www.example.com', controller: this.controller }) 8684 } 8685 } 8686 } 8687 ``` 8688 8689### accessBackward<sup>(deprecated)</sup> 8690 8691accessBackward(): boolean 8692 8693Checks whether going to the previous page can be performed on the current page. 8694 8695This API is deprecated since API version 9. You are advised to use [accessBackward<sup>9+</sup>](js-apis-webview.md#accessbackward) instead. 8696 8697**System capability**: SystemCapability.Web.Webview.Core 8698 8699**Return value** 8700 8701| Type | Description | 8702| ------- | --------------------- | 8703| boolean | Returns **true** if going to the previous page can be performed on the current page; returns **false** otherwise.| 8704 8705**Example** 8706 8707 ```ts 8708 // xxx.ets 8709 @Entry 8710 @Component 8711 struct WebComponent { 8712 controller: WebController = new WebController() 8713 8714 build() { 8715 Column() { 8716 Button('accessBackward') 8717 .onClick(() => { 8718 let result = this.controller.accessBackward() 8719 console.log('result:' + result) 8720 }) 8721 Web({ src: 'www.example.com', controller: this.controller }) 8722 } 8723 } 8724 } 8725 ``` 8726 8727### accessForward<sup>(deprecated)</sup> 8728 8729accessForward(): boolean 8730 8731Checks whether going to the next page can be performed on the current page. 8732 8733This API is deprecated since API version 9. You are advised to use [accessForward<sup>9+</sup>](js-apis-webview.md#accessforward) instead. 8734 8735**System capability**: SystemCapability.Web.Webview.Core 8736 8737**Return value** 8738 8739| Type | Description | 8740| ------- | --------------------- | 8741| boolean | Returns **true** if going to the next page can be performed on the current page; returns **false** otherwise.| 8742 8743**Example** 8744 8745 ```ts 8746 // xxx.ets 8747 @Entry 8748 @Component 8749 struct WebComponent { 8750 controller: WebController = new WebController() 8751 8752 build() { 8753 Column() { 8754 Button('accessForward') 8755 .onClick(() => { 8756 let result = this.controller.accessForward() 8757 console.log('result:' + result) 8758 }) 8759 Web({ src: 'www.example.com', controller: this.controller }) 8760 } 8761 } 8762 } 8763 ``` 8764 8765### accessStep<sup>(deprecated)</sup> 8766 8767accessStep(step: number): boolean 8768 8769Performs a specific number of steps forward or backward from the current page. 8770 8771This API is deprecated since API version 9. You are advised to use [accessStep<sup>9+</sup>](js-apis-webview.md#accessstep) instead. 8772 8773**System capability**: SystemCapability.Web.Webview.Core 8774 8775**Parameters** 8776 8777| Name | Type | Mandatory | Description | 8778| ---- | ------ | ---- | --------------------- | 8779| step | number | Yes | Number of the steps to take. A positive number means to go forward, and a negative number means to go backward.| 8780 8781**Return value** 8782 8783| Type | Description | 8784| ------- | --------- | 8785| boolean | Whether going forward or backward from the current page is successful.| 8786 8787**Example** 8788 8789 ```ts 8790 // xxx.ets 8791 @Entry 8792 @Component 8793 struct WebComponent { 8794 controller: WebController = new WebController() 8795 @State steps: number = 2 8796 8797 build() { 8798 Column() { 8799 Button('accessStep') 8800 .onClick(() => { 8801 let result = this.controller.accessStep(this.steps) 8802 console.log('result:' + result) 8803 }) 8804 Web({ src: 'www.example.com', controller: this.controller }) 8805 } 8806 } 8807 } 8808 ``` 8809 8810### backward<sup>(deprecated)</sup> 8811 8812backward() 8813 8814Goes to the previous page based on the history stack. This API is generally used together with **accessBackward**. 8815 8816This API is deprecated since API version 9. You are advised to use [backward<sup>9+</sup>](js-apis-webview.md#backward) instead. 8817 8818**System capability**: SystemCapability.Web.Webview.Core 8819 8820**Example** 8821 8822 ```ts 8823 // xxx.ets 8824 @Entry 8825 @Component 8826 struct WebComponent { 8827 controller: WebController = new WebController() 8828 8829 build() { 8830 Column() { 8831 Button('backward') 8832 .onClick(() => { 8833 this.controller.backward() 8834 }) 8835 Web({ src: 'www.example.com', controller: this.controller }) 8836 } 8837 } 8838 } 8839 ``` 8840 8841### forward<sup>(deprecated)</sup> 8842 8843forward() 8844 8845Goes to the next page based on the history stack. This API is generally used together with **accessForward**. 8846 8847This API is deprecated since API version 9. You are advised to use [forward<sup>9+</sup>](js-apis-webview.md#forward) instead. 8848 8849**System capability**: SystemCapability.Web.Webview.Core 8850 8851**Example** 8852 8853 ```ts 8854 // xxx.ets 8855 @Entry 8856 @Component 8857 struct WebComponent { 8858 controller: WebController = new WebController() 8859 8860 build() { 8861 Column() { 8862 Button('forward') 8863 .onClick(() => { 8864 this.controller.forward() 8865 }) 8866 Web({ src: 'www.example.com', controller: this.controller }) 8867 } 8868 } 8869 } 8870 ``` 8871 8872### deleteJavaScriptRegister<sup>(deprecated)</sup> 8873 8874deleteJavaScriptRegister(name: string) 8875 8876Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. The deletion takes effect immediately, with no need for invoking the [refresh](#refreshdeprecated) API. 8877 8878This API is deprecated since API version 9. You are advised to use [deleteJavaScriptRegister<sup>9+</sup>](js-apis-webview.md#deletejavascriptregister) instead. 8879 8880**System capability**: SystemCapability.Web.Webview.Core 8881 8882**Parameters** 8883 8884| Name | Type | Mandatory | Description | 8885| ---- | ------ | ---- | ---------------------------------------- | 8886| name | string | Yes | Name of the registered JavaScript object, which can be used to invoke the corresponding object on the application side from the web side.| 8887 8888**Example** 8889 8890 ```ts 8891 // xxx.ets 8892 @Entry 8893 @Component 8894 struct WebComponent { 8895 controller: WebController = new WebController() 8896 @State name: string = 'Object' 8897 8898 build() { 8899 Column() { 8900 Button('deleteJavaScriptRegister') 8901 .onClick(() => { 8902 this.controller.deleteJavaScriptRegister(this.name) 8903 }) 8904 Web({ src: 'www.example.com', controller: this.controller }) 8905 } 8906 } 8907 } 8908 ``` 8909 8910### getHitTest<sup>(deprecated)</sup> 8911 8912getHitTest(): HitTestType 8913 8914Obtains the element type of the area being clicked. 8915 8916This API is deprecated since API version 9. You are advised to use [getHitTest<sup>9+</sup>](js-apis-webview.md#gethittest) instead. 8917 8918**System capability**: SystemCapability.Web.Webview.Core 8919 8920**Return value** 8921 8922| Type | Description | 8923| ------------------------------- | ----------- | 8924| [HitTestType](#hittesttype)| Element type of the area being clicked.| 8925 8926**Example** 8927 8928 ```ts 8929 // xxx.ets 8930 @Entry 8931 @Component 8932 struct WebComponent { 8933 controller: WebController = new WebController() 8934 8935 build() { 8936 Column() { 8937 Button('getHitTest') 8938 .onClick(() => { 8939 let hitType = this.controller.getHitTest() 8940 console.log("hitType: " + hitType) 8941 }) 8942 Web({ src: 'www.example.com', controller: this.controller }) 8943 } 8944 } 8945 } 8946 ``` 8947 8948### loadData<sup>(deprecated)</sup> 8949 8950loadData(options: { data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string }) 8951 8952Loads data. If **baseUrl** is empty, the specified character string will be loaded using the data protocol. 8953 8954If **baseUrl** is set to a data URL, the encoded string will be loaded by the **Web** component using the data protocol. 8955 8956If **baseUrl** is set to an HTTP or HTTPS URL, the encoded string will be processed by the **Web** component as a non-encoded string in a manner similar to **loadUrl**. 8957 8958This API is deprecated since API version 9. You are advised to use [loadData<sup>9+</sup>](js-apis-webview.md#loaddata) instead. 8959 8960**System capability**: SystemCapability.Web.Webview.Core 8961 8962**Parameters** 8963 8964| Name | Type | Mandatory | Description | 8965| ---------- | ------ | ---- | ---------------------------------------- | 8966| data | string | Yes | Character string obtained after being Base64 or URL encoded. | 8967| mimeType | string | Yes | Media type (MIME). | 8968| encoding | string | Yes | Encoding type, which can be Base64 or URL. | 8969| baseUrl | string | No | URL (HTTP/HTTPS/data compliant), which is assigned by the **Web** component to **window.origin**.| 8970| historyUrl | string | No | Historical record URL. If this parameter is not empty, it can be managed in historical records to implement page going backward and forward. This parameter is invalid when **baseUrl** is left empty.| 8971 8972**Example** 8973 8974 ```ts 8975 // xxx.ets 8976 @Entry 8977 @Component 8978 struct WebComponent { 8979 controller: WebController = new WebController() 8980 8981 build() { 8982 Column() { 8983 Button('loadData') 8984 .onClick(() => { 8985 this.controller.loadData({ 8986 data: "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>", 8987 mimeType: "text/html", 8988 encoding: "UTF-8" 8989 }) 8990 }) 8991 Web({ src: 'www.example.com', controller: this.controller }) 8992 } 8993 } 8994 } 8995 ``` 8996 8997### loadUrl<sup>(deprecated)</sup> 8998 8999loadUrl(options: { url: string | Resource, headers?: Array\<Header\> }) 9000 9001Loads a URL using the specified HTTP header. 9002 9003The object injected through **loadUrl** is valid only in the current document. It will be invalid on a new page navigated to through **loadUrl**. 9004 9005The object injected through **registerJavaScriptProxy** is still valid on a new page redirected through **loadUrl**. 9006 9007This API is deprecated since API version 9. You are advised to use [loadUrl<sup>9+</sup>](js-apis-webview.md#loadurl) instead. 9008 9009**System capability**: SystemCapability.Web.Webview.Core 9010 9011**Parameters** 9012 9013| Name | Type | Mandatory | Description | 9014| ------- | -------------------------- | ---- | -------------- | 9015| url | string \| Resource | Yes | URL to load. | 9016| headers | Array\<[Header](#header)\> | No | Additional HTTP request header of the URL. The default value is **[]**.| 9017 9018**Example** 9019 9020 ```ts 9021 // xxx.ets 9022 @Entry 9023 @Component 9024 struct WebComponent { 9025 controller: WebController = new WebController() 9026 9027 build() { 9028 Column() { 9029 Button('loadUrl') 9030 .onClick(() => { 9031 this.controller.loadUrl({ url: 'www.example.com' }) 9032 }) 9033 Web({ src: 'www.example.com', controller: this.controller }) 9034 } 9035 } 9036 } 9037 ``` 9038 9039### onActive<sup>(deprecated)</sup> 9040 9041onActive(): void 9042 9043Called when the **Web** component enters the active state. 9044 9045This API is deprecated since API version 9. You are advised to use [onActive<sup>9+</sup>](js-apis-webview.md#onactive) instead. 9046 9047**System capability**: SystemCapability.Web.Webview.Core 9048 9049**Example** 9050 9051 ```ts 9052 // xxx.ets 9053 @Entry 9054 @Component 9055 struct WebComponent { 9056 controller: WebController = new WebController() 9057 9058 build() { 9059 Column() { 9060 Button('onActive') 9061 .onClick(() => { 9062 this.controller.onActive() 9063 }) 9064 Web({ src: 'www.example.com', controller: this.controller }) 9065 } 9066 } 9067 } 9068 ``` 9069 9070### onInactive<sup>(deprecated)</sup> 9071 9072onInactive(): void 9073 9074Called when the **Web** component enters the inactive state. 9075 9076This API is deprecated since API version 9. You are advised to use [onInactive<sup>9+</sup>](js-apis-webview.md#oninactive) instead. 9077 9078**System capability**: SystemCapability.Web.Webview.Core 9079 9080**Example** 9081 9082 ```ts 9083 // xxx.ets 9084 @Entry 9085 @Component 9086 struct WebComponent { 9087 controller: WebController = new WebController() 9088 9089 build() { 9090 Column() { 9091 Button('onInactive') 9092 .onClick(() => { 9093 this.controller.onInactive() 9094 }) 9095 Web({ src: 'www.example.com', controller: this.controller }) 9096 } 9097 } 9098 } 9099 ``` 9100 9101### zoom<sup>(deprecated)</sup> 9102 9103zoom(factor: number): void 9104 9105Sets a zoom factor for the current web page. 9106 9107This API is deprecated since API version 9. You are advised to use [zoom<sup>9+</sup>](js-apis-webview.md#zoom) instead. 9108 9109**System capability**: SystemCapability.Web.Webview.Core 9110 9111**Parameters** 9112 9113| Name | Type | Mandatory | Description | 9114| ------ | ------ | ---- | ------------------------------ | 9115| factor | number | Yes | Zoom factor to set. A positive value indicates zoom-in, and a negative value indicates zoom-out.| 9116 9117**Example** 9118 9119 ```ts 9120 // xxx.ets 9121 @Entry 9122 @Component 9123 struct WebComponent { 9124 controller: WebController = new WebController() 9125 @State factor: number = 1 9126 9127 build() { 9128 Column() { 9129 Button('zoom') 9130 .onClick(() => { 9131 this.controller.zoom(this.factor) 9132 }) 9133 Web({ src: 'www.example.com', controller: this.controller }) 9134 } 9135 } 9136 } 9137 ``` 9138 9139### refresh<sup>(deprecated)</sup> 9140 9141refresh() 9142 9143Called when the **Web** component refreshes the web page. 9144 9145This API is deprecated since API version 9. You are advised to use [refresh<sup>9+</sup>](js-apis-webview.md#refresh) instead. 9146 9147**System capability**: SystemCapability.Web.Webview.Core 9148 9149**Example** 9150 9151 ```ts 9152 // xxx.ets 9153 @Entry 9154 @Component 9155 struct WebComponent { 9156 controller: WebController = new WebController() 9157 9158 build() { 9159 Column() { 9160 Button('refresh') 9161 .onClick(() => { 9162 this.controller.refresh() 9163 }) 9164 Web({ src: 'www.example.com', controller: this.controller }) 9165 } 9166 } 9167 } 9168 ``` 9169 9170### registerJavaScriptProxy<sup>(deprecated)</sup> 9171 9172registerJavaScriptProxy(options: { object: object, name: string, methodList: Array\<string\> }) 9173 9174Registers a JavaScript object with the window. APIs of this object can then be invoked in the window. You must invoke the [refresh](#refreshdeprecated) API for the registration to take effect. 9175 9176This API is deprecated since API version 9. You are advised to use [registerJavaScriptProxy<sup>9+</sup>](js-apis-webview.md#registerjavascriptproxy) instead. 9177 9178**System capability**: SystemCapability.Web.Webview.Core 9179 9180**Parameters** 9181 9182| Name | Type | Mandatory | Description | 9183| ---------- | --------------- | ---- | ---------------------------------------- | 9184| object | object | Yes | Application-side JavaScript object to be registered. Methods and attributes can be declared, but cannot be directly called on HTML5. The parameters and return value can only be of the string, number, or Boolean type.| 9185| name | string | Yes | Name of the object to be registered, which is the same as that invoked in the window. After registration, the window can use this name to access the JavaScript object at the application side.| 9186| methodList | Array\<string\> | Yes | Methods of the JavaScript object to be registered at the application side. | 9187 9188**Example** 9189 9190 ```ts 9191 // xxx.ets 9192 class TestObj { 9193 constructor() { 9194 } 9195 9196 test(): string { 9197 return "ArkUI Web Component" 9198 } 9199 9200 toString(): void { 9201 console.log('Web Component toString') 9202 } 9203 } 9204 9205 @Entry 9206 @Component 9207 struct Index { 9208 controller: WebController = new WebController() 9209 testObj = new TestObj(); 9210 build() { 9211 Column() { 9212 Row() { 9213 Button('Register JavaScript To Window').onClick(() => { 9214 this.controller.registerJavaScriptProxy({ 9215 object: this.testObj, 9216 name: "objName", 9217 methodList: ["test", "toString"], 9218 }) 9219 }) 9220 } 9221 Web({ src: $rawfile('index.html'), controller: this.controller }) 9222 .javaScriptAccess(true) 9223 } 9224 } 9225 } 9226 ``` 9227 9228 HTML file to be loaded: 9229 ```html 9230 <!-- index.html --> 9231 <!DOCTYPE html> 9232 <html> 9233 <meta charset="utf-8"> 9234 <body> 9235 Hello world! 9236 </body> 9237 <script type="text/javascript"> 9238 function htmlTest() { 9239 str = objName.test("test function") 9240 console.log('objName.test result:'+ str) 9241 } 9242 </script> 9243 </html> 9244 9245 ``` 9246 9247### runJavaScript<sup>(deprecated)</sup> 9248 9249runJavaScript(options: { script: string, callback?: (result: string) => void }) 9250 9251Executes a JavaScript script. This API uses an asynchronous callback to return the script execution result. **runJavaScript** can be invoked only after **loadUrl** is executed. For example, it can be invoked in **onPageEnd**. 9252 9253This API is deprecated since API version 9. You are advised to use [runJavaScript<sup>9+</sup>](js-apis-webview.md#runjavascript) instead. 9254 9255**System capability**: SystemCapability.Web.Webview.Core 9256 9257**Parameters** 9258 9259| Name | Type | Mandatory| Description | 9260| -------- | ------------------------ | ---- | ---------------------------------------- | 9261| script | string | Yes | JavaScript script. | 9262| callback | (result: string) => void | No | Callback used to return the result. Returns **null** if the JavaScript script fails to be executed or no value is returned.| 9263 9264**Example** 9265 9266 ```ts 9267 // xxx.ets 9268 @Entry 9269 @Component 9270 struct WebComponent { 9271 controller: WebController = new WebController() 9272 @State webResult: string = '' 9273 build() { 9274 Column() { 9275 Text(this.webResult).fontSize(20) 9276 Web({ src: $rawfile('index.html'), controller: this.controller }) 9277 .javaScriptAccess(true) 9278 .onPageEnd((event) => { 9279 this.controller.runJavaScript({ 9280 script: 'test()', 9281 callback: (result: string)=> { 9282 this.webResult = result 9283 console.info(`The test() return value is: ${result}`) 9284 }}) 9285 if (event) { 9286 console.info('url: ', event.url) 9287 } 9288 }) 9289 } 9290 } 9291 } 9292 ``` 9293 HTML file to be loaded: 9294 ```html 9295 <!-- index.html --> 9296 <!DOCTYPE html> 9297 <html> 9298 <meta charset="utf-8"> 9299 <body> 9300 Hello world! 9301 </body> 9302 <script type="text/javascript"> 9303 function test() { 9304 console.log('Ark WebComponent') 9305 return "This value is from index.html" 9306 } 9307 </script> 9308 </html> 9309 ``` 9310 9311### stop<sup>(deprecated)</sup> 9312 9313stop() 9314 9315Stops page loading. 9316 9317This API is deprecated since API version 9. You are advised to use [stop<sup>9+</sup>](js-apis-webview.md#stop) instead. 9318 9319**System capability**: SystemCapability.Web.Webview.Core 9320 9321**Example** 9322 9323 ```ts 9324 // xxx.ets 9325 @Entry 9326 @Component 9327 struct WebComponent { 9328 controller: WebController = new WebController() 9329 9330 build() { 9331 Column() { 9332 Button('stop') 9333 .onClick(() => { 9334 this.controller.stop() 9335 }) 9336 Web({ src: 'www.example.com', controller: this.controller }) 9337 } 9338 } 9339 } 9340 ``` 9341 9342### clearHistory<sup>(deprecated)</sup> 9343 9344clearHistory(): void 9345 9346Clears the browsing history. 9347 9348This API is deprecated since API version 9. You are advised to use [clearHistory<sup>9+</sup>](js-apis-webview.md#clearhistory) instead. 9349 9350**System capability**: SystemCapability.Web.Webview.Core 9351 9352**Example** 9353 9354 ```ts 9355 // xxx.ets 9356 @Entry 9357 @Component 9358 struct WebComponent { 9359 controller: WebController = new WebController() 9360 9361 build() { 9362 Column() { 9363 Button('clearHistory') 9364 .onClick(() => { 9365 this.controller.clearHistory() 9366 }) 9367 Web({ src: 'www.example.com', controller: this.controller }) 9368 } 9369 } 9370 } 9371 ``` 9372 9373## WebCookie 9374 9375Manages behavior of cookies in **Web** components. All **Web** components in an application share a **WebCookie**. You can use the **getCookieManager** API in **controller** to obtain the **WebCookie** for subsequent cookie management. 9376 9377### constructor 9378 9379constructor() 9380 9381Constructs the **WebCookie** object. 9382 9383**System capability**: SystemCapability.Web.Webview.Core 9384 9385### setCookie<sup>(deprecated)</sup> 9386 9387setCookie() 9388 9389Sets the cookie. This API returns the result synchronously. Returns **true** if the operation is successful; returns **false** otherwise. 9390 9391This API is deprecated since API version 9. You are advised to use [setCookie<sup>9+</sup>](js-apis-webview.md#setcookie) instead. 9392 9393**System capability**: SystemCapability.Web.Webview.Core 9394 9395### saveCookie<sup>(deprecated)</sup> 9396 9397saveCookie() 9398 9399Saves the cookies in the memory to the drive. This API returns the result synchronously. 9400 9401This API is deprecated since API version 9. You are advised to use [saveCookieAsync<sup>9+</sup>](js-apis-webview.md#savecookieasync) instead. 9402 9403**System capability**: SystemCapability.Web.Webview.Core 9404 9405## ScriptItem<sup>11+</sup> 9406 9407Describes the **ScriptItem** object injected to the **Web** component through the [javaScriptOnDocumentStart](#javascriptondocumentstart11) attribute. 9408 9409**System capability**: SystemCapability.Web.Webview.Core 9410 9411| Name | Type | Mandatory | Description | 9412| ----------- | -------------- | ---- | --------------------- | 9413| script | string | Yes | JavaScript script to be injected and executed.| 9414| scriptRules | Array\<string> | Yes | Matching rules for allowed sources.<br>1. To allow URLs from all sources, use the wildcard (\*).<br>2. If exact match is required, specify the exact URL, for example, **https:\//www\\.example.com**.<br>3. For fuzzy match, you can use a wildcard (\*) in the website URL, for example, **https://\*.example.com**. Websites such as "x,*.y.com" and "* foobar.com" are not allowed. <br>4. If the source is an IP address, follow rule 2.<br>5. For protocols other than HTTP/HTTPS (user-defined protocols), exact match and fuzzy match are not supported, and the protocol must end with a slash (/), for example, **resource://**.<br>6. If one of the preceding rules is not met in the **scriptRules**, the **scriptRules** does not take effect.| 9415 9416## WebNavigationType<sup>11+</sup> 9417 9418Defines the navigation type. 9419 9420**System capability**: SystemCapability.Web.Webview.Core 9421 9422| Name | Value| Description | 9423| ----------------------------- | -- | ------------ | 9424| UNKNOWN | 0 | Unknown type. | 9425| MAIN_FRAME_NEW_ENTRY | 1 | Navigation to a new history entry from the main document. | 9426| MAIN_FRAME_EXISTING_ENTRY | 2 | Navigation to an existing history entry from the main document.| 9427| NAVIGATION_TYPE_NEW_SUBFRAME | 4 | User-triggered navigation from a subdocument.| 9428| NAVIGATION_TYPE_AUTO_SUBFRAME | 5 | Non-user-triggered navigation from a subdocument.| 9429 9430## LoadCommittedDetails<sup>11+</sup> 9431 9432Provides detailed information about the web page that has been submitted for redirection. 9433 9434**System capability**: SystemCapability.Web.Webview.Core 9435 9436| Name | Type | Mandatory | Description | 9437| ----------- | ------------------------------------ | ---- | --------------------- | 9438| isMainFrame | boolean | Yes | Whether the document is the main document.| 9439| isSameDocument | boolean | Yes | Whether to navigate without changing the document. Example of navigation in the same document: 1. navigation shown in the example; 2. navigation triggered by **pushState** or **replaceState**; 3. navigation to a history entry on the same page. | 9440| didReplaceEntry | boolean | Yes | Whether the submitted new entry replaces the existing entry. In certain scenarios for navigation to a subdocument, although the existing entry is not replaced, some attributes are changed. | 9441| navigationType | [WebNavigationType](#webnavigationtype11) | Yes | Navigation type. | 9442| url | string | Yes | URL of the current navigated-to web page. | 9443 9444## ThreatType<sup>11+</sup> 9445 9446Enumerates the website threat types. 9447 9448**System capability**: SystemCapability.Web.Webview.Core 9449 9450| Name | Value| Description | 9451| ---------------- | -- | ----------------------| 9452| THREAT_ILLEGAL | 0 | Illegal website. | 9453| THREAT_FRAUD | 1 | Fraudulent website. | 9454| THREAT_RISK | 2 | Website that poses security risks. | 9455| THREAT_WARNING | 3 | Website suspected to contain unsafe content.| 9456 9457## OnNavigationEntryCommittedCallback<sup>11+</sup> 9458 9459type OnNavigationEntryCommittedCallback = (loadCommittedDetails: [LoadCommittedDetails](#loadcommitteddetails11)) => void 9460 9461Called when a navigation item is submitted. 9462 9463**System capability**: SystemCapability.Web.Webview.Core 9464 9465**Parameters** 9466 9467| Name | Type | Mandatory | Description | 9468| ------ | ------ | ---- | --------------------- | 9469| loadCommittedDetails | [LoadCommittedDetails](#loadcommitteddetails11) | Yes| Detailed information about the web page that has been submitted for redirection.| 9470 9471## OnSafeBrowsingCheckResultCallback<sup>11+</sup> 9472 9473type OnSafeBrowsingCheckResultCallback = (threatType: ThreatType) => void 9474 9475Called by a website safe browsing check. 9476 9477**System capability**: SystemCapability.Web.Webview.Core 9478 9479**Parameters** 9480 9481| Name | Type | Mandatory | Description | 9482| ------ | ------ | ---- | --------------------- | 9483| threatType | [ThreatType](#threattype11) | Yes| Website threat type. | 9484 9485## FullScreenEnterEvent<sup>12+</sup> 9486 9487Provides details about the callback event for the **Web** component to enter the full-screen mode. 9488 9489**System capability**: SystemCapability.Web.Webview.Core 9490 9491| Name | Type | Mandatory | Description | 9492| ----------- | ------------------------------------ | ---- | --------------------- | 9493| handler | [FullScreenExitHandler](#fullscreenexithandler9) | Yes | Function handle for exiting full screen mode.| 9494| videoWidth | number | No | Video width, in px. If the element that enters fulls screen mode is a **\<video>** element, the value represents its width; if the element that enters fulls screen mode contains a **\<video>** element, the value represents the width of the first sub-video element; in other cases, the value is **0**.| 9495| videoHeight | number | No | Video height, in px. If the element that enters fulls screen mode is a **\<video>** element, the value represents its height; if the element that enters fulls screen mode contains a **\<video>** element, the value represents the height of the first sub-video element; in other cases, the value is **0**.| 9496 9497## OnFullScreenEnterCallback<sup>12+</sup> 9498 9499type OnFullScreenEnterCallback = (event: FullScreenEnterEvent) => void 9500 9501Called when the **Web** component enters full screen mode. 9502 9503**System capability**: SystemCapability.Web.Webview.Core 9504 9505**Parameters** 9506 9507| Name | Type | Mandatory | Description | 9508| ------ | ------ | ---- | --------------------- | 9509| event | [FullScreenEnterEvent](#fullscreenenterevent12) | Yes| Callback event for the **Web** component to enter full screen mode.| 9510 9511## SslErrorEvent<sup>12+</sup> 9512 9513Provides details about the callback invoked when an SSL error occurs during resource loading. 9514 9515**System capability**: SystemCapability.Web.Webview.Core 9516 9517| Name | Type | Mandatory | Description | 9518| ------- | ------------------------------------ | ---- | -------------- | 9519| handler | [SslErrorHandler](#sslerrorhandler9) | Yes | User operation.| 9520| error | [SslError](#sslerror9) | Yes | Error code. | 9521| url | string | Yes | URL. | 9522| originalUrl | string | Yes | Original URL of the request. | 9523| referrer | string | Yes | Referrer URL. | 9524| isFatalError | boolean | Yes | Whether the error is a fatal error. | 9525| isMainFrame | boolean | Yes | Whether the request is made for the main frame. | 9526 9527 9528## OnSslErrorEventCallback<sup>12+</sup> 9529 9530type OnSslErrorEventCallback = (sslErrorEvent: SslErrorEvent) => void 9531 9532Provides details about the callback invoked when an SSL error occurs during resource loading. 9533 9534**System capability**: SystemCapability.Web.Webview.Core 9535 9536**Parameters** 9537 9538| Name | Type | Mandatory | Description | 9539| ------ | ------ | ---- | --------------------- | 9540| sslErrorEvent | [SslErrorEvent](#sslerrorevent12) | Yes| Details about the callback invoked when an SSL error occurs during resource loading.| 9541 9542## NativeEmbedStatus<sup>11+</sup> 9543 9544Defines the lifecycle of the same-layer tag. When the same-layer tag exists on the loaded page, **CREATE** is triggered. When the same-layer tag is moved or is enlarged, **UPDATE **is triggered. When the page exits, **DESTROY** is triggered. 9545 9546**System capability**: SystemCapability.Web.Webview.Core 9547 9548| Name | Value| Description | 9549| ----------------------------- | -- | ------------ | 9550| CREATE | 0 | The same-layer tag is created. | 9551| UPDATE | 1 | The same-layer tag is updated. | 9552| DESTROY | 2 | The same-layer tag is destroyed.| 9553| ENTER_BFCACHE<sup>12+</sup> | 3 | The same-layer tag enters the BFCache. | 9554| LEAVE_BFCACHE<sup>12+</sup> | 4 | The same-layer tag leaves the BFCache.| 9555 9556## NativeEmbedInfo<sup>11+</sup> 9557 9558Provides detailed information about the same-layer tag. 9559 9560**System capability**: SystemCapability.Web.Webview.Core 9561 9562| Name | Type | Mandatory | Description | 9563|-------------------| ------------------------------------ | ---- |---------------------------| 9564| id | string | No | ID of the same-layer tag. | 9565| type | string | No | Type of the same-layer tag. The value is in lowercase. | 9566| src | string | No | **src** information of the same-layer tag. | 9567| width | number | No | Width of the same-layer tag, in px. | 9568| height | number | No | Height of the same-layer tag, in px. | 9569| url | string | No | URL of the same-layer tag. | 9570| tag<sup>12+</sup> | string | No | Name of the tag, which consists of uppercase letters. | 9571| params<sup>12+</sup> | Map<string, string> | No | List of key-value pairs contained in the **object** tag that form a map of the Object type. Use the methods provided by the Object type to operate the map object. | 9572| position<sup>12+</sup> | Position | No | Position of the same-layer tag relative to the **Web** component in the screen coordinate system, which is different from the standard **Position**. The unit is px.| 9573 9574## NativeEmbedDataInfo<sup>11+</sup> 9575 9576Provides detailed information about the lifecycle changes of the same-layer tag. 9577 9578**System capability**: SystemCapability.Web.Webview.Core 9579 9580| Name | Type | Mandatory | Description | 9581| ----------- | ------------------------------------ | ---- | --------------------- | 9582| status | [NativeEmbedStatus](#nativeembedstatus11) | No | Lifecycle status of the same-layer tag.| 9583| surfaceId | string | No | Surface ID of the native image. | 9584| embedId | string | No | Unique ID of the same-layer tag. | 9585| info | [NativeEmbedInfo](#nativeembedinfo11) | No | Detailed information about the same-layer tag. | 9586 9587## NativeEmbedTouchInfo<sup>11+</sup> 9588 9589Provides touch information of the same-layer tag. 9590 9591**System capability**: SystemCapability.Web.Webview.Core 9592 9593| Name | Type | Mandatory | Description | 9594| ----------- | ------------------------------------ | ---- | --------------------- | 9595| embedId | string | No | Unique ID of the same-layer tag.| 9596| touchEvent | [TouchEvent](../apis-arkui/arkui-ts/ts-universal-events-touch.md#touchevent) | No | Touch action information.| 9597| result<sup>12+</sup> | [EventResult](#eventresult12) | No | Gesture event consumption result.| 9598 9599## FirstMeaningfulPaint<sup>12+</sup> 9600 9601Provides detailed information about the first meaningful paint. 9602 9603**System capability**: SystemCapability.Web.Webview.Core 9604 9605| Name | Type | Mandatory| Description | 9606| ------------------------ | ------ | ---- | -------------------------------------- | 9607| navigationStartTime | number | No | Navigation bar loading time, in microseconds. | 9608| firstMeaningfulPaintTime | number | No | Time taken for the first meaningful paint of the page, in milliseconds.| 9609 9610## OnFirstMeaningfulPaintCallback<sup>12+</sup> 9611 9612type OnFirstMeaningfulPaintCallback = (firstMeaningfulPaint: [FirstMeaningfulPaint](#firstmeaningfulpaint12)) => void 9613 9614Represents the callback invoked when the first meaningful paint occurs on the page. 9615 9616**System capability**: SystemCapability.Web.Webview.Core 9617 9618**Parameters** 9619 9620| Name | Type | Mandatory | Description | 9621| ------ | ------ | ---- | --------------------- | 9622| firstMeaningfulPaint | [FirstMeaningfulPaint](#firstmeaningfulpaint12) | Yes| Information about the first meaningful paint.| 9623 9624## LargestContentfulPaint<sup>12+</sup> 9625 9626Provides detailed information about the largest content paint. 9627 9628**System capability**: SystemCapability.Web.Webview.Core 9629 9630| Name | Type | Mandatory| Description | 9631| ------------------------- | ------ | ---- | ---------------------------------------- | 9632| navigationStartTime | number | No | Navigation bar loading time, in microseconds. | 9633| largestImagePaintTime | number | No | Maximum image loading time, in milliseconds. | 9634| largestTextPaintTime | number | No | Maximum text loading time, in milliseconds. | 9635| largestImageLoadStartTime | number | No | Maximum time for an image to start loading, in milliseconds.| 9636| largestImageLoadEndTime | number | No | Maximum time for an image to finish loading, in milliseconds.| 9637| imageBPP | number | No | Maximum number of image pixels. | 9638 9639## OnLargestContentfulPaintCallback<sup>12+</sup> 9640 9641type OnLargestContentfulPaintCallback = (largestContentfulPaint: [LargestContentfulPaint](#largestcontentfulpaint12 9642)) => void 9643 9644Called when the largest content paint occurs on the web page. 9645 9646**System capability**: SystemCapability.Web.Webview.Core 9647 9648**Parameters** 9649 9650| Name | Type | Mandatory | Description | 9651| ------ | ------ | ---- | --------------------- | 9652| largestContentfulPaint | [LargestContentfulPaint](#largestcontentfulpaint12) | Yes| Information about the largest content paint.| 9653 9654## IntelligentTrackingPreventionDetails<sup>12+</sup> 9655 9656Provides detailed information about intelligent tracking prevention. 9657 9658**System capability**: SystemCapability.Web.Webview.Core 9659 9660| Name | Type | Mandatory | Description | 9661| ------------- | ------------------------------------| ----- | ------------ | 9662| host | string | Yes | Domain name. | 9663| trackerHost | string | Yes | Domain name of the tracker. | 9664 9665## OnIntelligentTrackingPreventionCallback<sup>12+</sup> 9666 9667type OnIntelligentTrackingPreventionCallback = (details: IntelligentTrackingPreventionDetails) => void 9668 9669Represents the callback invoked when the tracker cookie is intercepted. 9670 9671**System capability**: SystemCapability.Web.Webview.Core 9672 9673**Parameters** 9674 9675| Name | Type | Mandatory | Description | 9676| ------ | ------ | ---- | --------------------- | 9677| details | [IntelligentTrackingPreventionDetails](#intelligenttrackingpreventiondetails12) | Yes| Detailed information about intelligent tracking prevention.| 9678 9679## OnOverrideUrlLoadingCallback<sup>12+</sup> 9680 9681type OnOverrideUrlLoadingCallback = (webResourceRequest: WebResourceRequest) => boolean 9682 9683Represents a callback for **onOverrideUrlLoading**. 9684 9685**System capability**: SystemCapability.Web.Webview.Core 9686 9687**Parameters** 9688 9689| Name | Type | Mandatory | Description| 9690| ------------------ | ------- | ---- | ------------- | 9691| webResourceRequest | [WebResourceRequest](#webresourcerequest) | Yes | Information about the URL request.| 9692 9693**Return value** 9694 9695| Type | Description | 9696| ------- | ------------------------ | 9697| boolean | Returns **true** if the access is blocked; returns **false** otherwise.| 9698 9699## RenderMode<sup>12+</sup> 9700 9701Enumerates the rendering mode of **Web** components. By default, the asynchronous rendering mode is used. 9702 9703The asynchronous rendering mode is recommended because it has better performance and lower power consumption. 9704 9705**System capability**: SystemCapability.Web.Webview.Core 9706 9707| Name | Value| Description | 9708| ----------------------------- | -- | ------------ | 9709| ASYNC_RENDER | 0 | The **Web** component is rendered asynchronously. The ArkWeb component as a graphic surface node is displayed independently. The maximum width of the **Web** component is 7,680 px (physical pixel). | 9710| SYNC_RENDER | 1 | The **Web** component is rendered synchronously. The ArkWeb component as a graphic canvas node is displayed together with the system component. The maximum width of the **Web** component is 500,000 px (physical pixel). | 9711 9712## NativeMediaPlayerConfig<sup>12+</sup> 9713 9714Represents the configuration for [enabling the application to take over web page media playback](#enablenativemediaplayer12). 9715 9716**System capability**: SystemCapability.Web.Webview.Core 9717 9718| Name| Type| Mandatory| Description| 9719|------|------|------|------| 9720| enable | boolean | Yes| Whether to enable the feature.<br> **true**: enabled<br> **false** (default): disabled| 9721| shouldOverlay | boolean | Yes| Whether the video player's display overlays the web page content when the application takes over the web page's video player.<br> **true**: The video player's display overlays the web page content. This means that the height of the video layer is adjusted to cover the web page content.<br> **false** (default): The video player's display does not overlay the web page content. This means that the video player maintains its original height and is embedded within the web page.| 9722 9723## RenderProcessNotRespondingReason<sup>12+</sup> 9724 9725Provides the reason why the rendering process does not respond. 9726 9727**System capability**: SystemCapability.Web.Webview.Core 9728 9729| Name | Value| Description | 9730| ----------------------------- | -- | ------------ | 9731| INPUT_TIMEOUT | 0 | The response to the input event sent to the rendering process times out. | 9732| NAVIGATION_COMMIT_TIMEOUT | 1 | The navigation for loading a new web page times out. | 9733 9734## RenderProcessNotRespondingData<sup>12+</sup> 9735 9736Provides detailed information about the unresponsive rendering process. 9737 9738**System capability**: SystemCapability.Web.Webview.Core 9739 9740| Name | Type | Mandatory| Description | 9741| ------------------------ | ------ | ---- | -------------------------------------- | 9742| jsStack | string | Yes | JavaScript call stack information of the web page. | 9743| pid | number | Yes | Process ID of the web page.| 9744| reason | [RenderProcessNotRespondingReason](#renderprocessnotrespondingreason12) | Yes | The reason why the rendering process does not respond.| 9745 9746## OnRenderProcessNotRespondingCallback<sup>12+</sup> 9747 9748type OnRenderProcessNotRespondingCallback = (data : RenderProcessNotRespondingData) => void 9749 9750Represents a callback invoked when the rendering process does not respond. 9751 9752**System capability**: SystemCapability.Web.Webview.Core 9753 9754**Parameters** 9755 9756| Name | Type | Mandatory | Description | 9757| ------ | ------ | ---- | --------------------- | 9758| data | [RenderProcessNotRespondingData](#renderprocessnotrespondingdata12) | Yes| The detailed information about the unresponsive rendering process.| 9759 9760## OnRenderProcessRespondingCallback<sup>12+</sup> 9761 9762type OnRenderProcessRespondingCallback = () => void 9763 9764Represents a callback invoked when the rendering process transitions back to a normal operating state from an unresponsive state. 9765 9766**System capability**: SystemCapability.Web.Webview.Core 9767 9768## ViewportFit<sup>12+</sup> 9769 9770Enumerates the viewport types available for **viewport-fit** in the web page **\<meta>** tag. 9771 9772**System capability**: SystemCapability.Web.Webview.Core 9773 9774| Name | Value| Description | 9775| ----------------------------- | -- | ------------ | 9776| AUTO | 0 | The entire web page is visible. Default value. | 9777| CONTAINS | 1 | The initial layout viewport and the visual viewport fit within the largest rectangle that adapts to the device's display screen. | 9778| COVER | 2| The initial layout viewport and the visual viewport are confined within the bounding rectangle of the device's physical screen. | 9779 9780## OnViewportFitChangedCallback<sup>12+</sup> 9781 9782type OnViewportFitChangedCallback = (viewportFit: ViewportFit) => void 9783 9784Represents the callback invoked when the **viewport-fit** configuration in the web page's **\<meta>** tag changes. 9785 9786**System capability**: SystemCapability.Web.Webview.Core 9787 9788**Parameters** 9789 9790| Name | Type | Mandatory | Description | 9791| ------ | ------ | ---- | --------------------- | 9792| viewportFit | [ViewportFit](#viewportfit12) | Yes| Viewport type for **viewport-fit** in the web page **\<meta>** tag.| 9793 9794## ExpandedMenuItemOptions<sup>12+</sup> 9795 9796Defines the custom expanded menu options. 9797 9798**System capability**: SystemCapability.Web.Webview.Core 9799 9800| Name | Type | Mandatory | Description | 9801| ---------- | -----------------------------------------------------| ------ | ---------------- | 9802| content | [ResourceStr](../apis-arkui/arkui-ts/ts-types.md#resourcestr) | Yes | Content to display. | 9803| startIcon | [ResourceStr](../apis-arkui/arkui-ts/ts-types.md#resourcestr) | No | Icon to display. | 9804| action | (selectedText: {plainText: string}) => void | Yes | Selected text.| 9805 9806## WebKeyboardAvoidMode<sup>12+</sup> 9807 9808Enumerates the soft keyboard avoidance modes. 9809 9810**System capability**: SystemCapability.Web.Webview.Core 9811 9812| Name | Value| Description | 9813| ------------------ | -- | ------------ | 9814| RESIZE_VISUAL | 0 | For soft keyboard avoidance, the visual viewport is resized, but not the layout viewport. | 9815| RESIZE_CONTENT | 1 | For soft keyboard avoidance, both the visual viewport and layout viewport are resized. Default value.| 9816| OVERLAYS_CONTENT | 2 | No viewport is resized, and soft keyboard avoidance is not triggered. | 9817 9818## OnPageEndEvent<sup>12+</sup> 9819 9820Represents the callback invoked when the web page loading ends. 9821 9822**System capability**: SystemCapability.Web.Webview.Core 9823 9824| Name | Type | Mandatory | Description | 9825| -------------- | ---- | ---- | ---------------------------------------- | 9826| url | string | Yes| URL of the page. | 9827 9828## OnPageBeginEvent<sup>12+</sup> 9829 9830Represents the callback invoked when the web page loading begins. 9831 9832**System capability**: SystemCapability.Web.Webview.Core 9833 9834| Name | Type | Mandatory | Description | 9835| -------------- | ---- | ---- | ---------------------------------------- | 9836| url | string | Yes| URL of the page. | 9837 9838## OnProgressChangeEvent<sup>12+</sup> 9839 9840Represents the callback invoked when the web page loading progress changes. 9841 9842**System capability**: SystemCapability.Web.Webview.Core 9843 9844| Name | Type | Mandatory | Description | 9845| -------------- | ---- | ---- | ---------------------------------------- | 9846| newProgress | number | Yes| New loading progress. The value is an integer ranging from 0 to 100. | 9847 9848## OnTitleReceiveEvent<sup>12+</sup> 9849 9850Represents the callback invoked when the document title of the web page is changed. 9851 9852**System capability**: SystemCapability.Web.Webview.Core 9853 9854| Name | Type | Mandatory | Description | 9855| -------------- | ---- | ---- | ---------------------------------------- | 9856| title | string | Yes| Document title. | 9857 9858## OnGeolocationShowEvent<sup>12+</sup> 9859 9860Represents the callback invoked when a request to obtain the geolocation information is received. 9861 9862**System capability**: SystemCapability.Web.Webview.Core 9863 9864| Name | Type | Mandatory | Description | 9865| -------------- | ---- | ---- | ---------------------------------------- | 9866| origin | string | Yes| Index of the origin. | 9867| geolocation | [JsGeolocation](#jsgeolocation) | Yes| User operation. | 9868 9869## OnAlertEvent<sup>12+</sup> 9870 9871Represents the callback invoked when **alert()** is invoked to display an alert dialog box on the web page. 9872 9873**System capability**: SystemCapability.Web.Webview.Core 9874 9875| Name | Type | Mandatory | Description | 9876| -------------- | ---- | ---- | ---------------------------------------- | 9877| url | string | Yes| URL of the web page where the dialog box is displayed. | 9878| message | string | Yes| Message displayed in the dialog box. | 9879| result | [JsResult](#jsresult) | Yes| User operation. | 9880 9881## OnBeforeUnloadEvent<sup>12+</sup> 9882 9883Represents the callback invoked when this page is about to exit after the user refreshes or closes the page. 9884 9885**System capability**: SystemCapability.Web.Webview.Core 9886 9887| Name | Type | Mandatory | Description | 9888| -------------- | ---- | ---- | ---------------------------------------- | 9889| url | string | Yes| URL of the web page where the dialog box is displayed. | 9890| message | string | Yes| Message displayed in the dialog box. | 9891| result | [JsResult](#jsresult) | Yes| User operation. | 9892 9893## OnConfirmEvent<sup>12+</sup> 9894 9895Represents the callback invoked when **confirm()** is invoked by the web page. 9896 9897**System capability**: SystemCapability.Web.Webview.Core 9898 9899| Name | Type | Mandatory | Description | 9900| -------------- | ---- | ---- | ---------------------------------------- | 9901| url | string | Yes| URL of the web page where the dialog box is displayed. | 9902| message | string | Yes| Message displayed in the dialog box. | 9903| result | [JsResult](#jsresult) | Yes| User operation. | 9904 9905## OnPromptEvent<sup>12+</sup> 9906 9907Represents the callback invoked when **prompt()** is invoked by the web page. 9908 9909**System capability**: SystemCapability.Web.Webview.Core 9910 9911| Name | Type | Mandatory | Description | 9912| -------------- | ---- | ---- | ---------------------------------------- | 9913| url | string | Yes| URL of the web page where the dialog box is displayed. | 9914| message | string | Yes| Message displayed in the dialog box. | 9915| value | string | Yes| Information in the dialog box. | 9916| result | [JsResult](#jsresult) | Yes| User operation. | 9917 9918## OnConsoleEvent<sup>12+</sup> 9919 9920Represents the callback invoked to notify the host application of a JavaScript console message. 9921 9922**System capability**: SystemCapability.Web.Webview.Core 9923 9924| Name | Type | Mandatory | Description | 9925| -------------- | ---- | ---- | ---------------------------------------- | 9926| message | [ConsoleMessage](#consolemessage) | Yes| Console message. | 9927 9928## OnErrorReceiveEvent<sup>12+</sup> 9929 9930Represents the callback invoked when an error occurs during web page loading. 9931 9932**System capability**: SystemCapability.Web.Webview.Core 9933 9934| Name | Type | Mandatory | Description | 9935| -------------- | ---- | ---- | ---------------------------------------- | 9936| request | [WebResourceRequest](#webresourcerequest) | Yes| Encapsulation of a web page request. | 9937| error | [WebResourceError](#webresourceerror) | Yes| Encapsulation of a web page resource loading error.| 9938 9939## OnHttpErrorReceiveEvent<sup>12+</sup> 9940 9941Represents the callback invoked when an HTTP error occurs during web page resource loading. 9942 9943**System capability**: SystemCapability.Web.Webview.Core 9944 9945| Name | Type | Mandatory | Description | 9946| -------------- | ---- | ---- | ---------------------------------------- | 9947| request | [WebResourceRequest](#webresourcerequest) | Yes| Encapsulation of a web page request. | 9948| response | [WebResourceResponse](#webresourceresponse) | Yes| Encapsulation of a resource response.| 9949 9950## OnDownloadStartEvent<sup>12+</sup> 9951 9952Represents the callback invoked when the main application starts downloading a file. 9953 9954**System capability**: SystemCapability.Web.Webview.Core 9955 9956| Name | Type | Mandatory | Description | 9957| -------------- | ---- | ---- | ---------------------------------------- | 9958| url | string | Yes| URL for the download task. | 9959| userAgent | string | Yes| User agent used for download. | 9960| contentDisposition | string | Yes| Content-Disposition response header returned by the server, which may be empty.| 9961| mimetype | string | Yes| MIME type of the content returned by the server. | 9962| contentLength | number | Yes| Length of the content returned by the server. | 9963 9964## OnRefreshAccessedHistoryEvent<sup>12+</sup> 9965 9966Represents the callback invoked when the access history of the web page is refreshed. 9967 9968**System capability**: SystemCapability.Web.Webview.Core 9969 9970| Name | Type | Mandatory | Description | 9971| -------------- | ---- | ---- | ---------------------------------------- | 9972| url | string | Yes| URL to be accessed. | 9973| isRefreshed | boolean | Yes| Whether the page is reloaded. The value **true** means that the page is reloaded by invoking the [refresh<sup>9+</sup>](js-apis-webview.md#refresh) API, and **false** means the opposite.| 9974 9975## OnRenderExitedEvent<sup>12+</sup> 9976 9977Represents the callback invoked when the rendering process exits. 9978 9979**System capability**: SystemCapability.Web.Webview.Core 9980 9981| Name | Type | Mandatory | Description | 9982| -------------- | ---- | ---- | ---------------------------------------- | 9983| renderExitReason | [RenderExitReason](#renderexitreason9) | Yes| Cause for the abnormal exit of the rendering process.| 9984 9985## OnShowFileSelectorEvent<sup>12+</sup> 9986 9987Represents the callback invoked to notify the file selector result. 9988 9989**System capability**: SystemCapability.Web.Webview.Core 9990 9991| Name | Type | Mandatory | Description | 9992| -------------- | ---- | ---- | ---------------------------------------- | 9993| result | [FileSelectorResult](#fileselectorresult9) | Yes| File selection result to be sent to the **Web** component.| 9994| fileSelector | [FileSelectorParam](#fileselectorparam9) | Yes| Information about the file selector. | 9995 9996## OnResourceLoadEvent<sup>12+</sup> 9997 9998Represents the callback invoked when the URL is loaded. 9999 10000**System capability**: SystemCapability.Web.Webview.Core 10001 10002| Name | Type | Mandatory | Description | 10003| -------------- | ---- | ---- | ---------------------------------------- | 10004| url | string | Yes| URL of the loaded resource file.| 10005 10006## OnScaleChangeEvent<sup>12+</sup> 10007 10008Represents the callback invoked when the display scale of this page changes. 10009 10010**System capability**: SystemCapability.Web.Webview.Core 10011 10012| Name | Type | Mandatory | Description | 10013| -------------- | ---- | ---- | ---------------------------------------- | 10014| oldScale | number | Yes| Display ratio of the page before the change.| 10015| newScale | number | Yes| Display ratio of the page after the change.| 10016 10017## OnHttpAuthRequestEvent<sup>12+</sup> 10018 10019Represents the callback invoked when an HTTP authentication request is received. 10020 10021**System capability**: SystemCapability.Web.Webview.Core 10022 10023| Name | Type | Mandatory | Description | 10024| -------------- | ---- | ---- | ---------------------------------------- | 10025| handler | [HttpAuthHandler](#httpauthhandler9) | Yes| User operation. | 10026| host | string | Yes| Host to which HTTP authentication credentials apply.| 10027| realm | string | Yes| Realm to which HTTP authentication credentials apply. | 10028 10029## OnInterceptRequestEvent<sup>12+</sup> 10030 10031Represents the callback invoked when the **Web** component is about to load a URL. 10032 10033**System capability**: SystemCapability.Web.Webview.Core 10034 10035| Name | Type | Mandatory | Description | 10036| -------------- | ---- | ---- | ---------------------------------------- | 10037| request | [WebResourceRequest](#webresourcerequest) | Yes| Information about the URL request.| 10038 10039## OnPermissionRequestEvent<sup>12+</sup> 10040 10041Represents the callback invoked when a permission request is received. 10042 10043**System capability**: SystemCapability.Web.Webview.Core 10044 10045| Name | Type | Mandatory | Description | 10046| -------------- | ---- | ---- | ---------------------------------------- | 10047| request | [PermissionRequest](#permissionrequest9) | Yes| User operation.| 10048 10049## OnScreenCaptureRequestEvent<sup>12+</sup> 10050 10051Represents the callback invoked when a screen capture request is received. 10052 10053**System capability**: SystemCapability.Web.Webview.Core 10054 10055| Name | Type | Mandatory | Description | 10056| -------------- | ---- | ---- | ---------------------------------------- | 10057| handler | [ScreenCaptureHandler](#screencapturehandler10) | Yes| User operation.| 10058 10059## OnContextMenuShowEvent<sup>12+</sup> 10060 10061Represents the callback invoked during a call to allow for the display of a custom context menu. 10062 10063**System capability**: SystemCapability.Web.Webview.Core 10064 10065| Name | Type | Mandatory | Description | 10066| -------------- | ---- | ---- | ---------------------------------------- | 10067| param | [WebContextMenuParam](#webcontextmenuparam9) | Yes| Parameters related to the context menu. | 10068| result | [WebContextMenuResult](#webcontextmenuresult9) | Yes| Result of the context menu.| 10069 10070## OnSearchResultReceiveEvent<sup>12+</sup> 10071 10072Represents the callback invoked to notify the caller of the search result on the web page. 10073 10074**System capability**: SystemCapability.Web.Webview.Core 10075 10076| Name | Type | Mandatory | Description | 10077| -------------- | ---- | ---- | ---------------------------------------- | 10078| activeMatchOrdinal | number | Yes| Sequence number of the current match, which starts from 0. | 10079| numberOfMatches | number | Yes| Total number of matches. | 10080| isDoneCounting | boolean | Yes| Whether the search operation on the current page is complete. This API may be called multiple times until **isDoneCounting** is **true**.| 10081 10082## OnScrollEvent<sup>12+</sup> 10083 10084Represents the callback invoked when the scrollbar scrolls to a specified position. 10085 10086**System capability**: SystemCapability.Web.Webview.Core 10087 10088| Name | Type | Mandatory | Description | 10089| -------------- | ---- | ---- | ---------------------------------------- | 10090| xOffset | number | Yes| Position of the scrollbar on the x-axis relative to the leftmost of the web page.| 10091| yOffset | number | Yes| Position of the scrollbar on the y-axis relative to the top of the web page.| 10092 10093## OnSslErrorEventReceiveEvent<sup>12+</sup> 10094 10095Represents the callback invoked when the web page receives an SSL error. 10096 10097**System capability**: SystemCapability.Web.Webview.Core 10098 10099| Name | Type | Mandatory | Description | 10100| -------------- | ---- | ---- | ---------------------------------------- | 10101| handler | [SslErrorHandler](#sslerrorhandler9) | Yes| User operation.| 10102| error | [SslError](#sslerror9) | Yes| Error code. | 10103| certChainData<sup>14+</sup> | Array<Uint8Array\> | No| Certificate chain data. | 10104 10105## OnClientAuthenticationEvent<sup>12+</sup> 10106 10107Represents the callback invoked when an SSL client certificate is required from the user. 10108 10109**System capability**: SystemCapability.Web.Webview.Core 10110 10111| Name | Type | Mandatory | Description | 10112| -------------- | ---- | ---- | ---------------------------------------- | 10113| handler | [ClientAuthenticationHandler](#clientauthenticationhandler9) | Yes| User operation. | 10114| host | string | Yes| Host name of the server that requests a certificate. | 10115| port | number | Yes| Port number of the server that requests a certificate. | 10116| keyTypes | Array<string\> | Yes| Acceptable asymmetric private key types. | 10117| issuers | Array<string\> | Yes| Issuer of the certificate that matches the private key.| 10118 10119## OnWindowNewEvent<sup>12+</sup> 10120 10121Represents the callback invoked when the web page requests the user to create a window. 10122 10123**System capability**: SystemCapability.Web.Webview.Core 10124 10125| Name | Type | Mandatory | Description | 10126| -------------- | ---- | ---- | ---------------------------------------- | 10127| isAlert | boolean | Yes| Whether to open the target URL in a new window. The value **true** means to open the target URL in a new window, and **false** means to open the target URL in a new tab. | 10128| isUserTrigger | boolean | Yes| Whether the creation is triggered by the user. The value **true** means that the creation is triggered by the user, and **false** means the opposite. | 10129| targetUrl | string | Yes| Target URL. | 10130| handler | [ControllerHandler](#controllerhandler9) | Yes| **WebviewController** instance for setting the new window.| 10131 10132## OnTouchIconUrlReceivedEvent<sup>12+</sup> 10133 10134Represents the callback invoked when an apple-touch-icon URL is received. 10135 10136**System capability**: SystemCapability.Web.Webview.Core 10137 10138| Name | Type | Mandatory | Description | 10139| -------------- | ---- | ---- | ---------------------------------------- | 10140| url | string | Yes| Received apple-touch-icon URL.| 10141| precomposed | boolean | Yes| Whether the apple-touch-icon is precomposed. | 10142 10143## OnFaviconReceivedEvent<sup>12+</sup> 10144 10145Represents the callback invoked when this web page receives a new favicon. 10146 10147**System capability**: SystemCapability.Web.Webview.Core 10148 10149| Name | Type | Mandatory | Description | 10150| -------------- | ---- | ---- | ---------------------------------------- | 10151| favicon | [PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Yes| **PixelMap** object of the received favicon.| 10152 10153## OnPageVisibleEvent<sup>12+</sup> 10154 10155Represents the callback invoked when the old page is not displayed and the new page is about to be visible. 10156 10157**System capability**: SystemCapability.Web.Webview.Core 10158 10159| Name | Type | Mandatory | Description | 10160| -------------- | ---- | ---- | ---------------------------------------- | 10161| url | string | Yes| URL of the new page that is able to be visible when the old page is not displayed.| 10162 10163## OnDataResubmittedEvent<sup>12+</sup> 10164 10165Represents the callback invoked when the web form data can be resubmitted. 10166 10167**System capability**: SystemCapability.Web.Webview.Core 10168 10169| Name | Type | Mandatory | Description | 10170| -------------- | ---- | ---- | ---------------------------------------- | 10171| handler | [DataResubmissionHandler](#dataresubmissionhandler9) | Yes| Handler for resubmitting web form data.| 10172 10173## OnAudioStateChangedEvent<sup>12+</sup> 10174 10175Represents the callback invoked when the audio playback status on the web page changes. 10176 10177**System capability**: SystemCapability.Web.Webview.Core 10178 10179| Name | Type | Mandatory | Description | 10180| -------------- | ---- | ---- | ---------------------------------------- | 10181| playing | boolean | Yes| Audio playback status on the current page. The value **true** means that audio is being played, and **false** means the opposite.| 10182 10183## OnFirstContentfulPaintEvent<sup>12+</sup> 10184 10185Represents the callback invoked when the first content paint occurs on the web page. 10186 10187**System capability**: SystemCapability.Web.Webview.Core 10188 10189| Name | Type | Mandatory | Description | 10190| -------------- | ---- | ---- | ---------------------------------------- | 10191| navigationStartTick | number | Yes| Navigation start time, in microseconds. | 10192| firstContentfulPaintMs | number | Yes| Time between navigation and when the content is first rendered, in milliseconds.| 10193 10194## OnLoadInterceptEvent<sup>12+</sup> 10195 10196Represents the callback invoked when the **Web** component is about to access a URL. 10197 10198**System capability**: SystemCapability.Web.Webview.Core 10199 10200| Name | Type | Mandatory | Description | 10201| -------------- | ---- | ---- | ---------------------------------------- | 10202| data | [WebResourceRequest](#webresourcerequest) | Yes| Information about the URL request.| 10203 10204## OnOverScrollEvent<sup>12+</sup> 10205 10206Represents the callback invoked when the web page is overscrolled. 10207 10208**System capability**: SystemCapability.Web.Webview.Core 10209 10210| Name | Type | Mandatory | Description | 10211| -------------- | ---- | ---- | ---------------------------------------- | 10212| xOffset | number | Yes| Horizontal overscroll offset based on the leftmost edge of the web page.| 10213| yOffset | number | Yes| Vertical overscroll offset based on the top edge of the web page.| 10214 10215## JavaScriptProxy<sup>12+</sup> 10216 10217Defines the JavaScript object to be injected. 10218 10219**System capability**: SystemCapability.Web.Webview.Core 10220 10221| Name | Type | Mandatory | Description | 10222| -------------- | ---- | ---- | ---------------------------------------- | 10223| object | object | Yes | Object to be registered. Methods can be declared, but attributes cannot. | 10224| name | string | Yes | Name of the object to be registered, which is the same as that invoked in the window. | 10225| methodList | Array\<string\> | Yes | Synchronous methods of the JavaScript object to be registered at the application side. | 10226| controller | [WebController](#webcontroller) \| [WebviewController<sup>9+</sup>](#webviewcontroller9) | Yes | - | Controller. This API is deprecated since API version 9. You are advised to use **WebviewController** instead.| 10227| asyncMethodList<sup>12+</sup> | Array\<string\> | No | Asynchronous methods of the JavaScript object to be registered at the application side. Asynchronous methods do not provide return values. | 10228| permission<sup>12+</sup> | string | No | JSON string, which is empty by default. This string is used to configure JSBridge permission control and define the URL whitelist at the object and method levels.<br>For the example, see [Invoking Application Functions on the Frontend Page](../../web/web-in-page-app-function-invoking.md).| 10229 10230## AdsBlockedDetails<sup>12+</sup> 10231 10232Provides detailed information about the blocked ads when ads are blocked. 10233 10234**System capability**: SystemCapability.Web.Webview.Core 10235 10236| Name| Type | Mandatory | Description | 10237| ------- | -------------------------------------------------------------------------------- | ---- | ------------------------- | 10238| url | string | Yes | URL of the page where ads are blocked.| 10239| adsBlocked | Array\<string\> | Yes | URLs or DOMPath of the blocked ads. If ads have the same URLs, duplicate elements may exist.| 10240 10241## OnAdsBlockedCallback<sup>12+</sup> 10242 10243type OnAdsBlockedCallback = (details: AdsBlockedDetails) => void 10244 10245Represents the callback invoked when ads are blocked on the web page. 10246 10247**System capability**: SystemCapability.Web.Webview.Core 10248 10249**Parameters** 10250 10251| Name | Type | Mandatory | Description | 10252| -------------------- | ----------------------------------------------- | ---- | -------------------------------- | 10253| details | [AdsBlockedDetails](#adsblockeddetails12) | Yes | Detailed information about the blocked ads when ads are blocked.| 10254 10255## NativeEmbedVisibilityInfo<sup>12+</sup> 10256 10257Provides visibility information about the same-layer tag. 10258 10259**System capability**: SystemCapability.Web.Webview.Core 10260 10261| Name | Type | Mandatory | Description | 10262| ------------- | ------------------------------------| ----- | ------------------ | 10263| visibility | boolean | Yes | Whether the **embed** tag is visible. | 10264| embedId | string | Yes | ID of the same-layer rendering tag. | 10265 10266## OnNativeEmbedVisibilityChangeCallback<sup>12+</sup> 10267 10268type OnNativeEmbedVisibilityChangeCallback = (nativeEmbedVisibilityInfo: NativeEmbedVisibilityInfo) => void 10269 10270Called when the visibility of a same-layer tag changes. 10271 10272**System capability**: SystemCapability.Web.Webview.Core 10273 10274**Parameters** 10275 10276| Name | Type | Mandatory | Description | 10277| ------ | ------ | ---- | --------------------- | 10278| nativeEmbedVisibilityInfo | [NativeEmbedVisibilityInfo](#nativeembedvisibilityinfo12) | Yes| Visibility information about the same-layer tag.| 10279 10280## WebElementType<sup>13+</sup> 10281 10282Enumerates the web element type. 10283 10284**System capability**: SystemCapability.Web.Webview.Core 10285 10286**Parameters** 10287 10288| Name | Value| Description | 10289| --------- | -- | ----------------- | 10290| IMAGE | 1 | Image type.| 10291 10292## WebResponseType<sup>13+</sup> 10293 10294Enumerates the response type of the menu. 10295 10296**System capability**: SystemCapability.Web.Webview.Core 10297 10298**Parameters** 10299 10300| Name | Value| Description | 10301| -------------- | -- | ------------------ | 10302| LONG_PRESS | 1 | The menu is displayed when the component is long-pressed.| 10303 10304## SelectionMenuOptionsExt<sup>13+</sup> 10305 10306Defines the custom expanded menu options. 10307 10308**System capability**: SystemCapability.Web.Webview.Core 10309 10310| Name | Type | Mandatory | Description | 10311| ---------- | -----------------------------------------------------| ------ | ---------------- | 10312| onAppear | Callback\<void\> | No | Callback invoked when the custom selection menu is displayed. | 10313| onDisappear | Callback\<void\> | No | Callback invoked when the custom selection menu is closed. | 10314| preview | [CustomBuilder](../apis-arkui/arkui-ts/ts-types.md#custombuilder8) | No | Preview content style of the custom selection menu. If this parameter is not set, there is no preview content.| 10315| menuType | [MenuType](../apis-arkui/arkui-ts/ts-text-common.md#menutype13) | No | Type of the custom menu.<br>Default value: **MenuType.SELECTION_MENU** | 10316 10317## BlurOnKeyboardHideMode<sup>14+</sup> 10318 10319Enumerates whether the **Web** component loses focus when the soft keyboard is manually collapsed. 10320 10321**System capability**: SystemCapability.Web.Webview.Core 10322 10323**Parameters** 10324 10325| Name | Value| Description | 10326| ------ | -- | ----------- | 10327| SILENT | 0 | The **Web** component does not lose focus when the soft keyboard is manually collapsed.| 10328| BLUR | 1 | The **Web** component loses focus when the soft keyboard is manually collapsed.| 10329