1# Web 2 3The **<Web\>** component can be used to display web pages. It can be used with the [@ohos.web.webview](../apis/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 the DevEco Studio Previewer. 9 10## Required Permissions 11To 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-guidelines.md). 12 13## Child Components 14 15Not supported 16 17## APIs 18 19Web(options: { src: ResourceStr, controller: WebviewController | WebController}) 20 21> **NOTE** 22> 23> Transition animation is not supported. 24> 25> **\<Web>** components on a page must be bound to different **WebviewController**s. 26 27**Parameters** 28 29| Name | Type | Mandatory | Description | 30| ---------- | ---------------------------------------- | ---- | ------- | 31| src | [ResourceStr](ts-types.md) | 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 the sandbox outside of the application package, use **file://** to specify the path of the sandbox.| 32| controller | [WebviewController<sup>9+</sup>](../apis/js-apis-webview.md#webviewcontroller) \| [WebController](#webcontroller) | Yes | Controller. This API is deprecated since API version 9. You are advised to use **WebviewController** instead.| 33 34**Example** 35 36 Example of loading online web pages: 37 ```ts 38 // xxx.ets 39 import web_webview from '@ohos.web.webview' 40 41 @Entry 42 @Component 43 struct WebComponent { 44 controller: web_webview.WebviewController = new web_webview.WebviewController() 45 build() { 46 Column() { 47 Web({ src: 'www.example.com', controller: this.controller }) 48 } 49 } 50 } 51 ``` 52 53 Example of loading local web pages: 54 ```ts 55 // xxx.ets 56 import web_webview from '@ohos.web.webview' 57 58 @Entry 59 @Component 60 struct WebComponent { 61 controller: web_webview.WebviewController = new web_webview.WebviewController() 62 build() { 63 Column() { 64 // Load a local resource file through $rawfile. 65 Web({ src: $rawfile("index.html"), controller: this.controller }) 66 } 67 } 68 } 69 ``` 70 71 ```ts 72 // xxx.ets 73 import web_webview from '@ohos.web.webview' 74 75 @Entry 76 @Component 77 struct WebComponent { 78 controller: web_webview.WebviewController = new web_webview.WebviewController() 79 build() { 80 Column() { 81 // Load a local resource file through the resource protocol. 82 Web({ src: "resource://rawfile/index.html", controller: this.controller }) 83 } 84 } 85 } 86 ``` 87 88 Example of loading local resource files in the sandbox: 89 901. Obtain the sandbox path through the constructed singleton object **GlobalContext**. 91 92 ```ts 93 // GlobalContext.ts 94 export class GlobalContext { 95 private constructor() {} 96 private static instance: GlobalContext; 97 private _objects = new Map<string, Object>(); 98 99 public static getContext(): GlobalContext { 100 if (!GlobalContext.instance) { 101 GlobalContext.instance = new GlobalContext(); 102 } 103 return GlobalContext.instance; 104 } 105 106 getObject(value: string): Object | undefined { 107 return this._objects.get(value); 108 } 109 110 setObject(key: string, objectClass: Object): void { 111 this._objects.set(key, objectClass); 112 } 113 } 114 ``` 115 116 ```ts 117 // xxx.ets 118 import web_webview from '@ohos.web.webview' 119 import { GlobalContext } from '../GlobalContext.ts' 120 121 let url = 'file://' + GlobalContext.getContext().getObject("filesDir") + '/index.html' 122 123 @Entry 124 @Component 125 struct WebComponent { 126 controller: web_webview.WebviewController = new web_webview.WebviewController() 127 build() { 128 Column() { 129 // Load the files in the sandbox. 130 Web({ src: url, controller: this.controller }) 131 } 132 } 133 } 134 ``` 135 1362. Modify the **EntryAbility.ets** file. 137 138 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). 139 140 ```ts 141 // xxx.ts 142 import UIAbility from '@ohos.app.ability.UIAbility'; 143 import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 144 import Want from '@ohos.app.ability.Want'; 145 import web_webview from '@ohos.web.webview'; 146 import { GlobalContext } from '../GlobalContext' 147 148 export default class EntryAbility extends UIAbility { 149 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 150 // Data synchronization between the UIAbility component and UI can be implemented by binding filesDir to the GlobalContext object. 151 GlobalContext.getContext().setObject("filesDir", this.context.filesDir); 152 console.log("Sandbox path is " + GlobalContext.getContext().getObject("filesDir")) 153 } 154 } 155 ``` 156 157 HTML file to be loaded: 158 159 ```html 160 <!-- index.html --> 161 <!DOCTYPE html> 162 <html> 163 <body> 164 <p>Hello World</p> 165 </body> 166 </html> 167 ``` 168 169## Attributes 170 171The following universal attributes are supported: [aspectRatio](ts-universal-attributes-layout-constraints.md#attributes), [backdropBlur](ts-universal-attributes-image-effect.md#attributes), [bindContentCover](ts-universal-attributes-modal-transition.md#attributes), [bindContextMenu](ts-universal-attributes-menu.md#attributes), [bindMenu](ts-universal-attributes-menu.md#attributes), [bindSheet](ts-universal-attributes-sheet-transition.md#attributes), [borderColor](ts-universal-attributes-border.md#attributes), [borderRadius](ts-universal-attributes-border.md#attributes), [borderStyle](ts-universal-attributes-border.md#attributes), [borderWidth](ts-universal-attributes-border.md#attributes), [clip](ts-universal-attributes-sharp-clipping.md#attributes), [constraintSize](ts-universal-attributes-size.md#attributes), [defaultFocus](ts-universal-attributes-focus.md#attributes), [focusable](ts-universal-attributes-focus.md#attributes), [tabIndex](ts-universal-attributes-focus.md#attributes), [groupDefaultFocus](ts-universal-attributes-focus.md#attributes), [focusOnTouch](ts-universal-attributes-focus.md#attributes), [displayPriority](ts-universal-attributes-layout-constraints.md#attributes), [enabled](ts-universal-attributes-enable.md#attributes), [flexBasis](ts-universal-attributes-flex-layout.md#attributes), [flexGrow](ts-universal-attributes-flex-layout.md#attributes), [flexShrink](ts-universal-attributes-flex-layout.md#attributes), [layoutWeight](ts-universal-attributes-flex-layout.md#attributes), [id](ts-universal-attributes-component-id.md#attributes), [gridOffset](ts-universal-attributes-grid.md#attributes), [gridSpan](ts-universal-attributes-grid.md#attributes), [useSizeType](ts-universal-attributes-grid.md#attributes), [height](ts-universal-attributes-size.md#attributes), [touchable](ts-universal-attributes-click.md#attributes), [margin](ts-universal-attributes-size.md#attributes), [markAnchor](ts-universal-attributes-location.md#attributes), [offset](ts-universal-attributes-location.md#attributes), [width](ts-universal-attributes-size.md#attributes), [zIndex](ts-universal-attributes-z-order.md#attributes), [visibility](ts-universal-attributes-visibility.md#attributes), [rotate](ts-universal-attributes-transformation.md#attributes), [transform](ts-universal-attributes-transformation.md#attributes), [responseRegion](ts-universal-attributes-touch-target.md#attributes), [size](ts-universal-attributes-size.md#attributes), [stateStyles](ts-universal-attributes-polymorphic-style.md#attributes), [opacity](ts-universal-attributes-opacity.md#attributes), [shadow](ts-universal-attributes-image-effect.md#attributes), [sharedTransition](ts-transition-animation-shared-elements.md#attributes), and [transition](ts-transition-animation-component.md#attributes). 172 173### domStorageAccess 174 175domStorageAccess(domStorageAccess: boolean) 176 177Sets whether to enable the DOM Storage API. By default, this feature is disabled. 178 179**System capability**: SystemCapability.Web.Webview.Core 180 181**Parameters** 182 183| Name | Type | Mandatory | Default Value | Description | 184| ---------------- | ------- | ---- | ----- | ------------------------------------ | 185| domStorageAccess | boolean | Yes | false | Whether to enable the DOM Storage API.| 186 187**Example** 188 189 ```ts 190 // xxx.ets 191 import web_webview from '@ohos.web.webview' 192 193 @Entry 194 @Component 195 struct WebComponent { 196 controller: web_webview.WebviewController = new web_webview.WebviewController() 197 build() { 198 Column() { 199 Web({ src: 'www.example.com', controller: this.controller }) 200 .domStorageAccess(true) 201 } 202 } 203 } 204 ``` 205 206### fileAccess 207 208fileAccess(fileAccess: boolean) 209 210Sets 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). 211 212**Parameters** 213 214| Name | Type | Mandatory | Default Value | Description | 215| ---------- | ------- | ---- | ---- | ---------------------- | 216| fileAccess | boolean | Yes | true | Whether to enable access to the file system in the application. By default, this feature is enabled.| 217 218**Example** 219 220 ```ts 221 // xxx.ets 222 import web_webview from '@ohos.web.webview' 223 224 @Entry 225 @Component 226 struct WebComponent { 227 controller: web_webview.WebviewController = new web_webview.WebviewController() 228 build() { 229 Column() { 230 Web({ src: 'www.example.com', controller: this.controller }) 231 .fileAccess(true) 232 } 233 } 234 } 235 ``` 236 237### imageAccess 238 239imageAccess(imageAccess: boolean) 240 241Sets whether to enable automatic image loading. By default, this feature is enabled. 242 243**Parameters** 244 245| Name | Type | Mandatory | Default Value | Description | 246| ----------- | ------- | ---- | ---- | --------------- | 247| imageAccess | boolean | Yes | true | Whether to enable automatic image loading.| 248 249**Example** 250 ```ts 251 // xxx.ets 252 import web_webview from '@ohos.web.webview' 253 254 @Entry 255 @Component 256 struct WebComponent { 257 controller: web_webview.WebviewController = new web_webview.WebviewController() 258 build() { 259 Column() { 260 Web({ src: 'www.example.com', controller: this.controller }) 261 .imageAccess(true) 262 } 263 } 264 } 265 ``` 266 267### javaScriptProxy 268 269javaScriptProxy(javaScriptProxy: { object: object, name: string, methodList: Array\<string\>, 270 controller: WebviewController | WebController}) 271 272Registers a JavaScript object with the window. APIs of this object can then be invoked in the window. The parameters cannot be updated. Only one object can be registered through this API. To register multiple objects, use [registerJavaScriptProxy<sup>9+</sup>](../apis/js-apis-webview.md#registerjavascriptproxy). 273 274**Parameters** 275 276| Name | Type | Mandatory | Default Value | Description | 277| ---------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- | 278| object | object | Yes | - | Object to be registered. Methods can be declared, but attributes cannot. | 279| name | string | Yes | - | Name of the object to be registered, which is the same as that invoked in the window. | 280| methodList | Array\<string\> | Yes | - | Methods of the JavaScript object to be registered at the application side. | 281| controller | [WebviewController<sup>9+</sup>](../apis/js-apis-webview.md#webviewcontroller) \| [WebController](#webcontroller) | Yes | - | Controller. This API is deprecated since API version 9. You are advised to use **WebviewController** instead.| 282 283**Example** 284 285 ```ts 286 // xxx.ets 287 import web_webview from '@ohos.web.webview' 288 289 class TestObj { 290 constructor() { 291 } 292 293 test(data1: string, data2: string, data3: string): string { 294 console.log("data1:" + data1) 295 console.log("data2:" + data2) 296 console.log("data3:" + data3) 297 return "AceString" 298 } 299 300 toString(): void { 301 console.log('toString' + "interface instead.") 302 } 303 } 304 305 @Entry 306 @Component 307 struct WebComponent { 308 controller: web_webview.WebviewController = new web_webview.WebviewController() 309 testObj = new TestObj(); 310 build() { 311 Column() { 312 Web({ src: 'www.example.com', controller: this.controller }) 313 .javaScriptAccess(true) 314 .javaScriptProxy({ 315 object: this.testObj, 316 name: "objName", 317 methodList: ["test", "toString"], 318 controller: this.controller, 319 }) 320 } 321 } 322 } 323 ``` 324 325### javaScriptAccess 326 327javaScriptAccess(javaScriptAccess: boolean) 328 329Sets whether JavaScript scripts can be executed. By default, JavaScript scripts can be executed. 330 331**Parameters** 332 333| Name | Type | Mandatory | Default Value | Description | 334| ---------------- | ------- | ---- | ---- | ------------------- | 335| javaScriptAccess | boolean | Yes | true | Whether JavaScript scripts can be executed.| 336 337**Example** 338 339 ```ts 340 // xxx.ets 341 import web_webview from '@ohos.web.webview' 342 343 @Entry 344 @Component 345 struct WebComponent { 346 controller: web_webview.WebviewController = new web_webview.WebviewController() 347 build() { 348 Column() { 349 Web({ src: 'www.example.com', controller: this.controller }) 350 .javaScriptAccess(true) 351 } 352 } 353 } 354 ``` 355 356### mixedMode 357 358mixedMode(mixedMode: MixedMode) 359 360Sets whether to enable loading of HTTP and HTTPS hybrid content can be loaded. By default, this feature is disabled. 361 362**Parameters** 363 364| Name | Type | Mandatory | Default Value | Description | 365| --------- | --------------------------- | ---- | -------------- | --------- | 366| mixedMode | [MixedMode](#mixedmode)| Yes | MixedMode.None | Mixed content to load.| 367 368**Example** 369 370 ```ts 371 // xxx.ets 372 import web_webview from '@ohos.web.webview' 373 374 @Entry 375 @Component 376 struct WebComponent { 377 controller: web_webview.WebviewController = new web_webview.WebviewController() 378 @State mode: MixedMode = MixedMode.All 379 build() { 380 Column() { 381 Web({ src: 'www.example.com', controller: this.controller }) 382 .mixedMode(this.mode) 383 } 384 } 385 } 386 ``` 387 388### onlineImageAccess 389 390onlineImageAccess(onlineImageAccess: boolean) 391 392Sets whether to enable access to online images through HTTP and HTTPS. By default, this feature is enabled. 393 394**Parameters** 395 396| Name | Type | Mandatory | Default Value | Description | 397| ----------------- | ------- | ---- | ---- | ---------------- | 398| onlineImageAccess | boolean | Yes | true | Whether to enable access to online images through HTTP and HTTPS.| 399 400**Example** 401 402 ```ts 403 // xxx.ets 404 import web_webview from '@ohos.web.webview' 405 406 @Entry 407 @Component 408 struct WebComponent { 409 controller: web_webview.WebviewController = new web_webview.WebviewController() 410 build() { 411 Column() { 412 Web({ src: 'www.example.com', controller: this.controller }) 413 .onlineImageAccess(true) 414 } 415 } 416 } 417 ``` 418 419### zoomAccess 420 421zoomAccess(zoomAccess: boolean) 422 423Sets whether to enable zoom gestures. By default, this feature is enabled. 424 425**Parameters** 426 427| Name | Type | Mandatory | Default Value | Description | 428| ---------- | ------- | ---- | ---- | ------------- | 429| zoomAccess | boolean | Yes | true | Whether to enable zoom gestures.| 430 431**Example** 432 433 ```ts 434 // xxx.ets 435 import web_webview from '@ohos.web.webview' 436 437 @Entry 438 @Component 439 struct WebComponent { 440 controller: web_webview.WebviewController = new web_webview.WebviewController() 441 build() { 442 Column() { 443 Web({ src: 'www.example.com', controller: this.controller }) 444 .zoomAccess(true) 445 } 446 } 447 } 448 ``` 449 450### overviewModeAccess 451 452overviewModeAccess(overviewModeAccess: boolean) 453 454Sets whether to load web pages by using the overview mode. By default, this feature is enabled. Currently, only mobile devices are supported. 455 456**Parameters** 457 458| Name | Type | Mandatory | Default Value | Description | 459| ------------------ | ------- | ---- | ---- | --------------- | 460| overviewModeAccess | boolean | Yes | true | Whether to load web pages by using the overview mode.| 461 462**Example** 463 464 ```ts 465 // xxx.ets 466 import web_webview from '@ohos.web.webview' 467 468 @Entry 469 @Component 470 struct WebComponent { 471 controller: web_webview.WebviewController = new web_webview.WebviewController() 472 build() { 473 Column() { 474 Web({ src: 'www.example.com', controller: this.controller }) 475 .overviewModeAccess(true) 476 } 477 } 478 } 479 ``` 480 481### databaseAccess 482 483databaseAccess(databaseAccess: boolean) 484 485Sets whether to enable database access. By default, this feature is disabled. 486 487**Parameters** 488 489| Name | Type | Mandatory | Default Value | Description | 490| -------------- | ------- | ---- | ----- | ----------------- | 491| databaseAccess | boolean | Yes | false | Whether to enable database access.| 492 493**Example** 494 495 ```ts 496 // xxx.ets 497 import web_webview from '@ohos.web.webview' 498 499 @Entry 500 @Component 501 struct WebComponent { 502 controller: web_webview.WebviewController = new web_webview.WebviewController() 503 build() { 504 Column() { 505 Web({ src: 'www.example.com', controller: this.controller }) 506 .databaseAccess(true) 507 } 508 } 509 } 510 ``` 511 512### geolocationAccess 513 514geolocationAccess(geolocationAccess: boolean) 515 516Sets whether to enable geolocation access. By default, this feature is enabled. 517 518**Parameters** 519 520| Name | Type | Mandatory | Default Value | Description | 521| ----------------- | ------- | ---- | ---- | --------------- | 522| geolocationAccess | boolean | Yes | true | Whether to enable geolocation access.| 523 524**Example** 525 526 ```ts 527 // xxx.ets 528 import web_webview from '@ohos.web.webview' 529 530 @Entry 531 @Component 532 struct WebComponent { 533 controller: web_webview.WebviewController = new web_webview.WebviewController() 534 build() { 535 Column() { 536 Web({ src: 'www.example.com', controller: this.controller }) 537 .geolocationAccess(true) 538 } 539 } 540 } 541 ``` 542 543### mediaPlayGestureAccess 544 545mediaPlayGestureAccess(access: boolean) 546 547Sets 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. 548 549**Parameters** 550 551| Name | Type | Mandatory | Default Value | Description | 552| ------ | ------- | ---- | ---- | ----------------- | 553| access | boolean | Yes | true | Whether video playback must be started by user gestures.| 554 555**Example** 556 557 ```ts 558 // xxx.ets 559 import web_webview from '@ohos.web.webview' 560 561 @Entry 562 @Component 563 struct WebComponent { 564 controller: web_webview.WebviewController = new web_webview.WebviewController() 565 @State access: boolean = true 566 build() { 567 Column() { 568 Web({ src: 'www.example.com', controller: this.controller }) 569 .mediaPlayGestureAccess(this.access) 570 } 571 } 572 } 573 ``` 574 575### multiWindowAccess<sup>9+</sup> 576 577multiWindowAccess(multiWindow: boolean) 578 579Sets whether to enable the multi-window permission. By default, this feature is disabled. 580Enabling the multi-window permission requires implementation of the **onWindowNew** event. For the sample code, see [onWindowNew](#onwindownew9). 581 582**Parameters** 583 584| Name | Type | Mandatory | Default Value | Description | 585| ----------- | ------- | ---- | ----- | ------------ | 586| multiWindow | boolean | Yes | false | Whether to enable the multi-window permission.| 587 588**Example** 589 590 ```ts 591 // xxx.ets 592 import web_webview from '@ohos.web.webview' 593 594 @Entry 595 @Component 596 struct WebComponent { 597 controller: web_webview.WebviewController = new web_webview.WebviewController() 598 build() { 599 Column() { 600 Web({ src: 'www.example.com', controller: this.controller }) 601 .multiWindowAccess(false) 602 } 603 } 604 } 605 ``` 606 607### horizontalScrollBarAccess<sup>9+</sup> 608 609horizontalScrollBarAccess(horizontalScrollBar: boolean) 610 611Sets whether to display the horizontal scrollbar, including the default system scrollbar and custom scrollbar. By default, the horizontal scrollbar is displayed. 612 613**Parameters** 614 615| Name | Type | Mandatory | Default Value | Description | 616| ----------- | ------- | ---- | ----- | ------------ | 617| horizontalScrollBar | boolean | Yes | true | Whether to display the horizontal scrollbar.| 618 619**Example** 620 621 ```ts 622 // xxx.ets 623 import web_webview from '@ohos.web.webview' 624 625 @Entry 626 @Component 627 struct WebComponent { 628 controller: web_webview.WebviewController = new web_webview.WebviewController() 629 build() { 630 Column() { 631 Web({ src: $rawfile('index.html'), controller: this.controller }) 632 .horizontalScrollBarAccess(true) 633 } 634 } 635 } 636 ``` 637 638 HTML file to be loaded: 639 ```html 640 <!--index.html--> 641 <!DOCTYPE html> 642 <html> 643 <head> 644 <title>Demo</title> 645 <style> 646 body { 647 width:3000px; 648 height:3000px; 649 padding-right:170px; 650 padding-left:170px; 651 border:5px solid blueviolet 652 } 653 </style> 654 </head> 655 <body> 656 Scroll Test 657 </body> 658 </html> 659 ``` 660 661### verticalScrollBarAccess<sup>9+</sup> 662 663verticalScrollBarAccess(verticalScrollBar: boolean) 664 665Sets whether to display the vertical scrollbar, including the default system scrollbar and custom scrollbar. By default, the vertical scrollbar is displayed. 666 667**Parameters** 668 669| Name | Type | Mandatory | Default Value | Description | 670| ----------- | ------- | ---- | ----- | ------------ | 671| verticalScrollBarAccess | boolean | Yes | true | Whether to display the vertical scrollbar.| 672 673**Example** 674 675 ```ts 676 // xxx.ets 677 import web_webview from '@ohos.web.webview' 678 679 @Entry 680 @Component 681 struct WebComponent { 682 controller: web_webview.WebviewController = new web_webview.WebviewController() 683 build() { 684 Column() { 685 Web({ src: $rawfile('index.html'), controller: this.controller }) 686 .verticalScrollBarAccess(true) 687 } 688 } 689 } 690 ``` 691 692 HTML file to be loaded: 693 ```html 694 <!--index.html--> 695 <!DOCTYPE html> 696 <html> 697 <head> 698 <title>Demo</title> 699 <style> 700 body { 701 width:3000px; 702 height:3000px; 703 padding-right:170px; 704 padding-left:170px; 705 border:5px solid blueviolet 706 } 707 </style> 708 </head> 709 <body> 710 Scroll Test 711 </body> 712 </html> 713 ``` 714 715### password<sup>(deprecated)</sup> 716 717password(password: boolean) 718 719Sets whether the password should be saved. This API is a void API. 720 721> **NOTE** 722> 723> This API is deprecated since API version 10, and no new API is provided as a substitute. 724 725### cacheMode 726 727cacheMode(cacheMode: CacheMode) 728 729Sets the cache mode. 730 731**Parameters** 732 733| Name | Type | Mandatory | Default Value | Description | 734| --------- | --------------------------- | ---- | ----------------- | --------- | 735| cacheMode | [CacheMode](#cachemode)| Yes | CacheMode.Default | Cache mode to set.| 736 737**Example** 738 739 ```ts 740 // xxx.ets 741 import web_webview from '@ohos.web.webview' 742 743 @Entry 744 @Component 745 struct WebComponent { 746 controller: web_webview.WebviewController = new web_webview.WebviewController() 747 @State mode: CacheMode = CacheMode.None 748 build() { 749 Column() { 750 Web({ src: 'www.example.com', controller: this.controller }) 751 .cacheMode(this.mode) 752 } 753 } 754 } 755 ``` 756 757### textZoomAtio<sup>(deprecated)</sup> 758 759textZoomAtio(textZoomAtio: number) 760 761Sets the text zoom ratio of the page. The default value is **100**, which indicates 100%. 762 763This API is deprecated since API version 9. You are advised to use [textZoomRatio<sup>9+</sup>](#textzoomratio9) instead. 764 765**Parameters** 766 767| Name | Type | Mandatory | Default Value | Description | 768| ------------- | ------ | ---- | ---- | --------------- | 769| textZoomAtio | number | Yes | 100 | Text zoom ratio to set. The value is an integer. The value range is (0, +∞).| 770 771**Example** 772 773 ```ts 774 // xxx.ets 775 @Entry 776 @Component 777 struct WebComponent { 778 controller: WebController = new WebController() 779 @State atio: number = 150 780 build() { 781 Column() { 782 Web({ src: 'www.example.com', controller: this.controller }) 783 .textZoomAtio(this.atio) 784 } 785 } 786 } 787 ``` 788 789### textZoomRatio<sup>9+</sup> 790 791textZoomRatio(textZoomRatio: number) 792 793Sets the text zoom ratio of the page. The default value is **100**, which indicates 100%. 794 795**Parameters** 796 797| Name | Type | Mandatory | Default Value | Description | 798| ------------- | ------ | ---- | ---- | --------------- | 799| textZoomRatio | number | Yes | 100 | Text zoom ratio to set. The value is an integer. The value range is (0, +∞).| 800 801**Example** 802 803 ```ts 804 // xxx.ets 805 import web_webview from '@ohos.web.webview' 806 807 @Entry 808 @Component 809 struct WebComponent { 810 controller: web_webview.WebviewController = new web_webview.WebviewController() 811 @State atio: number = 150 812 build() { 813 Column() { 814 Web({ src: 'www.example.com', controller: this.controller }) 815 .textZoomRatio(this.atio) 816 } 817 } 818 } 819 ``` 820 821### initialScale<sup>9+</sup> 822 823initialScale(percent: number) 824 825Sets the scale factor of the entire page. The default value is 100%. 826 827**Parameters** 828 829| Name | Type | Mandatory | Default Value | Description | 830| ------- | ------ | ---- | ---- | ----------------------------- | 831| percent | number | Yes | 100 | Scale factor of the entire page.| 832 833**Example** 834 835 ```ts 836 // xxx.ets 837 import web_webview from '@ohos.web.webview' 838 839 @Entry 840 @Component 841 struct WebComponent { 842 controller: web_webview.WebviewController = new web_webview.WebviewController() 843 @State percent: number = 100 844 build() { 845 Column() { 846 Web({ src: 'www.example.com', controller: this.controller }) 847 .initialScale(this.percent) 848 } 849 } 850 } 851 ``` 852 853### userAgent<sup>(deprecated)</sup> 854 855userAgent(userAgent: string) 856 857Sets the user agent. 858 859> **NOTE** 860> 861> This API is supported since API version 8 and deprecated since API version 10. You are advised to use [setCustomUserAgent](../apis/js-apis-webview.md#setcustomuseragent10)<sup>10+</sup> instead. 862 863**Parameters** 864 865| Name | Type | Mandatory | Default Value | Description | 866| --------- | ------ | ---- | ---- | --------- | 867| userAgent | string | Yes | - | User agent to set.| 868 869**Example** 870 871 ```ts 872 // xxx.ets 873 import web_webview from '@ohos.web.webview' 874 875 @Entry 876 @Component 877 struct WebComponent { 878 controller: web_webview.WebviewController = new web_webview.WebviewController() 879 @State userAgent:string = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36' 880 build() { 881 Column() { 882 Web({ src: 'www.example.com', controller: this.controller }) 883 .userAgent(this.userAgent) 884 } 885 } 886 } 887 ``` 888 889### blockNetwork<sup>9+</sup> 890 891blockNetwork(block: boolean) 892 893Sets whether to block online downloads. 894 895**Parameters** 896 897| Name| Type| Mandatory| Default Value| Description | 898| ------ | -------- | ---- | ------ | ----------------------------------- | 899| block | boolean | Yes | false | Whether to block online downloads.| 900 901**Example** 902 903 ```ts 904 // xxx.ets 905 import web_webview from '@ohos.web.webview' 906 @Entry 907 @Component 908 struct WebComponent { 909 controller: web_webview.WebviewController = new web_webview.WebviewController() 910 @State block: boolean = true 911 build() { 912 Column() { 913 Web({ src: 'www.example.com', controller: this.controller }) 914 .blockNetwork(this.block) 915 } 916 } 917 } 918 ``` 919 920### defaultFixedFontSize<sup>9+</sup> 921 922defaultFixedFontSize(size: number) 923 924Sets the default fixed font size for the web page. 925 926**Parameters** 927 928| Name| Type| Mandatory| Default Value| Description | 929| ------ | -------- | ---- | ------ | ---------------------------- | 930| size | number | Yes | 13 | 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. | 931 932**Example** 933 934 ```ts 935 // xxx.ets 936 import web_webview from '@ohos.web.webview' 937 @Entry 938 @Component 939 struct WebComponent { 940 controller: web_webview.WebviewController = new web_webview.WebviewController() 941 @State fontSize: number = 16 942 build() { 943 Column() { 944 Web({ src: 'www.example.com', controller: this.controller }) 945 .defaultFixedFontSize(this.fontSize) 946 } 947 } 948 } 949 ``` 950 951### defaultFontSize<sup>9+</sup> 952 953defaultFontSize(size: number) 954 955Sets the default font size for the web page. 956 957**Parameters** 958 959| Name| Type| Mandatory| Default Value| Description | 960| ------ | -------- | ---- | ------ | ------------------------ | 961| size | number | Yes | 16 | 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. | 962 963**Example** 964 965 ```ts 966 // xxx.ets 967 import web_webview from '@ohos.web.webview' 968 @Entry 969 @Component 970 struct WebComponent { 971 controller: web_webview.WebviewController = new web_webview.WebviewController() 972 @State fontSize: number = 13 973 build() { 974 Column() { 975 Web({ src: 'www.example.com', controller: this.controller }) 976 .defaultFontSize(this.fontSize) 977 } 978 } 979 } 980 ``` 981 982### minFontSize<sup>9+</sup> 983 984minFontSize(size: number) 985 986Sets the minimum font size for the web page. 987 988**Parameters** 989 990| Name| Type| Mandatory| Default Value| Description | 991| ------ | -------- | ---- | ------ | ------------------------ | 992| size | number | Yes | 8 | 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. | 993 994**Example** 995 996 ```ts 997 // xxx.ets 998 import web_webview from '@ohos.web.webview' 999 @Entry 1000 @Component 1001 struct WebComponent { 1002 controller: web_webview.WebviewController = new web_webview.WebviewController() 1003 @State fontSize: number = 13 1004 build() { 1005 Column() { 1006 Web({ src: 'www.example.com', controller: this.controller }) 1007 .minFontSize(this.fontSize) 1008 } 1009 } 1010 } 1011 ``` 1012 1013### minLogicalFontSize<sup>9+</sup> 1014 1015minLogicalFontSize(size: number) 1016 1017Sets the minimum logical font size for the web page. 1018 1019**Parameters** 1020 1021| Name| Type| Mandatory| Default Value| Description | 1022| ------ | -------- | ---- | ------ | ------------------------ | 1023| size | number | Yes | 8 | 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. | 1024 1025**Example** 1026 1027 ```ts 1028 // xxx.ets 1029 import web_webview from '@ohos.web.webview' 1030 @Entry 1031 @Component 1032 struct WebComponent { 1033 controller: web_webview.WebviewController = new web_webview.WebviewController() 1034 @State fontSize: number = 13 1035 build() { 1036 Column() { 1037 Web({ src: 'www.example.com', controller: this.controller }) 1038 .minLogicalFontSize(this.fontSize) 1039 } 1040 } 1041 } 1042 ``` 1043 1044### webFixedFont<sup>9+</sup> 1045 1046webFixedFont(family: string) 1047 1048Sets the fixed font family for the web page. 1049 1050**Parameters** 1051 1052| Name| Type| Mandatory| Default Value | Description | 1053| ------ | -------- | ---- | --------- | ---------------------------- | 1054| family | string | Yes | monospace | Fixed font family to set.| 1055 1056**Example** 1057 1058 ```ts 1059 // xxx.ets 1060 import web_webview from '@ohos.web.webview' 1061 @Entry 1062 @Component 1063 struct WebComponent { 1064 controller: web_webview.WebviewController = new web_webview.WebviewController() 1065 @State family: string = "monospace" 1066 build() { 1067 Column() { 1068 Web({ src: 'www.example.com', controller: this.controller }) 1069 .webFixedFont(this.family) 1070 } 1071 } 1072 } 1073 ``` 1074 1075### webSansSerifFont<sup>9+</sup> 1076 1077webSansSerifFont(family: string) 1078 1079Sets the sans serif font family for the web page. 1080 1081**Parameters** 1082 1083| Name| Type| Mandatory| Default Value | Description | 1084| ------ | -------- | ---- | ---------- | --------------------------------- | 1085| family | string | Yes | sans-serif | Sans serif font family to set.| 1086 1087**Example** 1088 1089 ```ts 1090 // xxx.ets 1091 import web_webview from '@ohos.web.webview' 1092 @Entry 1093 @Component 1094 struct WebComponent { 1095 controller: web_webview.WebviewController = new web_webview.WebviewController() 1096 @State family: string = "sans-serif" 1097 build() { 1098 Column() { 1099 Web({ src: 'www.example.com', controller: this.controller }) 1100 .webSansSerifFont(this.family) 1101 } 1102 } 1103 } 1104 ``` 1105 1106### webSerifFont<sup>9+</sup> 1107 1108webSerifFont(family: string) 1109 1110Sets the serif font family for the web page. 1111 1112**Parameters** 1113 1114| Name| Type| Mandatory| Default Value| Description | 1115| ------ | -------- | ---- | ------ | ---------------------------- | 1116| family | string | Yes | serif | Serif font family to set.| 1117 1118**Example** 1119 1120 ```ts 1121 // xxx.ets 1122 import web_webview from '@ohos.web.webview' 1123 @Entry 1124 @Component 1125 struct WebComponent { 1126 controller: web_webview.WebviewController = new web_webview.WebviewController() 1127 @State family: string = "serif" 1128 build() { 1129 Column() { 1130 Web({ src: 'www.example.com', controller: this.controller }) 1131 .webSerifFont(this.family) 1132 } 1133 } 1134 } 1135 ``` 1136 1137### webStandardFont<sup>9+</sup> 1138 1139webStandardFont(family: string) 1140 1141Sets the standard font family for the web page. 1142 1143**Parameters** 1144 1145| Name| Type| Mandatory| Default Value | Description | 1146| ------ | -------- | ---- | ---------- | ------------------------------- | 1147| family | string | Yes | sans serif | Standard font family to set.| 1148 1149**Example** 1150 1151 ```ts 1152 // xxx.ets 1153 import web_webview from '@ohos.web.webview' 1154 @Entry 1155 @Component 1156 struct WebComponent { 1157 controller: web_webview.WebviewController = new web_webview.WebviewController() 1158 @State family: string = "sans-serif" 1159 build() { 1160 Column() { 1161 Web({ src: 'www.example.com', controller: this.controller }) 1162 .webStandardFont(this.family) 1163 } 1164 } 1165 } 1166 ``` 1167 1168### webFantasyFont<sup>9+</sup> 1169 1170webFantasyFont(family: string) 1171 1172Sets the fantasy font family for the web page. 1173 1174**Parameters** 1175 1176| Name| Type| Mandatory| Default Value | Description | 1177| ------ | -------- | ---- | ------- | ------------------------------ | 1178| family | string | Yes | fantasy | Fantasy font family to set.| 1179 1180**Example** 1181 1182 ```ts 1183 // xxx.ets 1184 import web_webview from '@ohos.web.webview' 1185 @Entry 1186 @Component 1187 struct WebComponent { 1188 controller: web_webview.WebviewController = new web_webview.WebviewController() 1189 @State family: string = "fantasy" 1190 build() { 1191 Column() { 1192 Web({ src: 'www.example.com', controller: this.controller }) 1193 .webFantasyFont(this.family) 1194 } 1195 } 1196 } 1197 ``` 1198 1199### webCursiveFont<sup>9+</sup> 1200 1201webCursiveFont(family: string) 1202 1203Sets the cursive font family for the web page. 1204 1205**Parameters** 1206 1207| Name| Type| Mandatory| Default Value | Description | 1208| ------ | -------- | ---- | ------- | ------------------------------ | 1209| family | string | Yes | cursive | Cursive font family to set.| 1210 1211**Example** 1212 1213 ```ts 1214 // xxx.ets 1215 import web_webview from '@ohos.web.webview' 1216 @Entry 1217 @Component 1218 struct WebComponent { 1219 controller: web_webview.WebviewController = new web_webview.WebviewController() 1220 @State family: string = "cursive" 1221 build() { 1222 Column() { 1223 Web({ src: 'www.example.com', controller: this.controller }) 1224 .webCursiveFont(this.family) 1225 } 1226 } 1227 } 1228 ``` 1229 1230### darkMode<sup>9+</sup> 1231 1232darkMode(mode: WebDarkMode) 1233 1234Sets 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). 1235 1236**Parameters** 1237 1238| Name| Type| Mandatory| Default Value | Description | 1239| ------ | ----------- | ---- | --------------- | ------------------ | 1240| mode | [WebDarkMode](#webdarkmode9) | Yes | WebDarkMode.Off | Web dark mode to set.| 1241 1242**Example** 1243 1244 ```ts 1245 // xxx.ets 1246 import web_webview from '@ohos.web.webview' 1247 @Entry 1248 @Component 1249 struct WebComponent { 1250 controller: web_webview.WebviewController = new web_webview.WebviewController() 1251 @State mode: WebDarkMode = WebDarkMode.On 1252 build() { 1253 Column() { 1254 Web({ src: 'www.example.com', controller: this.controller }) 1255 .darkMode(this.mode) 1256 } 1257 } 1258 } 1259 ``` 1260 1261### forceDarkAccess<sup>9+</sup> 1262 1263forceDarkAccess(access: boolean) 1264 1265Sets 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). 1266 1267**Parameters** 1268 1269| Name| Type| Mandatory| Default Value | Description | 1270| ------ | ------- | ---- | ----- | ------------------ | 1271| access | boolean | Yes | false | Whether to enable forcible dark mode for the web page.| 1272 1273**Example** 1274 1275 ```ts 1276 // xxx.ets 1277 import web_webview from '@ohos.web.webview' 1278 @Entry 1279 @Component 1280 struct WebComponent { 1281 controller: web_webview.WebviewController = new web_webview.WebviewController() 1282 @State mode: WebDarkMode = WebDarkMode.On 1283 @State access: boolean = true 1284 build() { 1285 Column() { 1286 Web({ src: 'www.example.com', controller: this.controller }) 1287 .darkMode(this.mode) 1288 .forceDarkAccess(this.access) 1289 } 1290 } 1291 } 1292 ``` 1293 1294### tableData<sup>(deprecated)</sup> 1295 1296tableData(tableData: boolean) 1297 1298Sets whether form data should be saved. This API is a void API. 1299 1300> **NOTE** 1301> 1302> This API is deprecated since API version 10, and no new API is provided as a substitute. 1303 1304### wideViewModeAccess<sup>(deprecated)</sup> 1305 1306wideViewModeAccess(wideViewModeAccess: boolean) 1307 1308Sets whether to support the viewport attribute of the HTML **\<meta>** tag. This API is a void API. 1309 1310> **NOTE** 1311> 1312> This API is deprecated since API version 10, and no new API is provided as a substitute. 1313 1314### pinchSmooth<sup>9+</sup> 1315 1316pinchSmooth(isEnabled: boolean) 1317 1318Sets whether to enable smooth pinch mode for the web page. 1319 1320**Parameters** 1321 1322| Name | Type| Mandatory| Default Value| Description | 1323| --------- | -------- | ---- | ------ | -------------------------- | 1324| isEnabled | boolean | Yes | false | Whether to enable smooth pinch mode for the web page.| 1325 1326**Example** 1327 1328 ```ts 1329 // xxx.ets 1330 import web_webview from '@ohos.web.webview' 1331 @Entry 1332 @Component 1333 struct WebComponent { 1334 controller: web_webview.WebviewController = new web_webview.WebviewController() 1335 build() { 1336 Column() { 1337 Web({ src: 'www.example.com', controller: this.controller }) 1338 .pinchSmooth(true) 1339 } 1340 } 1341 } 1342 ``` 1343 1344### allowWindowOpenMethod<sup>10+</sup> 1345 1346allowWindowOpenMethod(flag: boolean) 1347 1348Sets whether to allow a new window to automatically open through JavaScript. 1349 1350When **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. 1351 1352This API takes effect only when [javaScriptAccess](#javascriptaccess) is enabled. 1353 1354This API opens a new window when [multiWindowAccess](#multiwindowaccess9) is enabled and opens a local window when [multiWindowAccess](#multiwindowaccess9) is disabled. 1355 1356The 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**. 1357 1358To check the settings of **persist.web.allowWindowOpenMethod.enabled**, 1359 1360run the **hdc shell param get persist.web.allowWindowOpenMethod.enabled** command. If the attribute is set to 0 or does not exist, 1361you can run the **hdc shell param set persist.web.allowWindowOpenMethod.enabled 1** command to enable it. 1362 1363**Parameters** 1364 1365| Name| Type| Mandatory| Default Value | Description | 1366| ------ | ------- | ---- | ----- | ------------------ | 1367| flag | boolean | Yes | Subject to the settings of the **persist.web.allowWindowOpenMethod.enabled** system attribute. If this attribute is set, the default value of **flag** is **true**. Otherwise, the default value of **flag** is **false**. | Whether to allow a new window to automatically open through JavaScript.| 1368 1369**Example** 1370 1371 ```ts 1372 // xxx.ets 1373 import web_webview from '@ohos.web.webview' 1374 // There are two <Web> components on the same page. When the WebComponent object opens a new window, the NewWebViewComp object is displayed. 1375 @CustomDialog 1376 struct NewWebViewComp { 1377 controller?: CustomDialogController 1378 webviewController1: web_webview.WebviewController = new web_webview.WebviewController() 1379 build() { 1380 Column() { 1381 Web({ src: "", controller: this.webviewController1 }) 1382 .javaScriptAccess(true) 1383 .multiWindowAccess(false) 1384 .onWindowExit(()=> { 1385 console.info("NewWebViewComp onWindowExit") 1386 if (this.controller) { 1387 this.controller.close() 1388 } 1389 }) 1390 } 1391 } 1392 } 1393 1394 @Entry 1395 @Component 1396 struct WebComponent { 1397 controller: web_webview.WebviewController = new web_webview.WebviewController() 1398 dialogController: CustomDialogController | null = null 1399 build() { 1400 Column() { 1401 Web({ src: 'www.example.com', controller: this.controller }) 1402 .javaScriptAccess(true) 1403 // MultiWindowAccess needs to be enabled. 1404 .multiWindowAccess(true) 1405 .allowWindowOpenMethod(true) 1406 .onWindowNew((event) => { 1407 if (this.dialogController) { 1408 this.dialogController.close() 1409 } 1410 let popController:web_webview.WebviewController = new web_webview.WebviewController() 1411 this.dialogController = new CustomDialogController({ 1412 builder: NewWebViewComp({webviewController1: popController}) 1413 }) 1414 this.dialogController.open() 1415 // Return the WebviewController object corresponding to the new window to the <Web> kernel. 1416 // If opening a new window is not needed, set the parameter to null when calling the event.handler.setWebController API. 1417 // If the event.handler.setWebController API is not called, the render process will be blocked. 1418 event.handler.setWebController(popController) 1419 }) 1420 } 1421 } 1422 } 1423 ``` 1424 1425### mediaOptions<sup>10+</sup> 1426 1427mediaOptions(options: WebMediaOptions) 1428 1429Sets 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. 1430 1431> **NOTE** 1432> 1433> - Audios in the same **\<Web>** instance are considered as the same audio. 1434> - The media playback policy controls videos with an audio track. 1435> - After the parameter settings are updated, the playback must be started again for the settings to take effect. 1436> - It is recommended that you set the same **audioExclusive** value for all **\<Web>** components. 1437 1438**Parameters** 1439 1440| Name| Type| Mandatory| Default Value | Description | 1441| ------ | ----------- | ---- | --------------- | ------------------ | 1442| options | [WebMediaOptions](#webmediaoptions10) | Yes | {resumeInterval: 0, audioExclusive: true} | Web-based media playback policy. The default value of **resumeInterval** is **0**, indicating that the playback is not automatically resumed.| 1443 1444**Example** 1445 1446 ```ts 1447 // xxx.ets 1448 import web_webview from '@ohos.web.webview' 1449 @Entry 1450 @Component 1451 struct WebComponent { 1452 controller: web_webview.WebviewController = new web_webview.WebviewController() 1453 @State options: WebMediaOptions = {resumeInterval: 10, audioExclusive: true} 1454 build() { 1455 Column() { 1456 Web({ src: 'www.example.com', controller: this.controller }) 1457 .mediaOptions(this.options) 1458 } 1459 } 1460 } 1461 ``` 1462 1463## Events 1464 1465The following universal events are supported: [onAppear](ts-universal-events-show-hide.md#events), [onDisAppear](ts-universal-events-show-hide.md#events), [onBlur](ts-universal-focus-event.md#events), [onFocus](ts-universal-focus-event.md#events), [onDragEnd](ts-universal-events-drag-drop.md#events). [onDragEnter](ts-universal-events-drag-drop.md#events), [onDragStart](ts-universal-events-drag-drop.md#events), [onDragMove](ts-universal-events-drag-drop.md#events), [onDragLeave](ts-universal-events-drag-drop.md#events), [onDrop](ts-universal-events-drag-drop.md#events), [onHover](ts-universal-mouse-key.md#events), [onMouse](ts-universal-mouse-key.md#events), [onKeyEvent](ts-universal-events-key.md#events), [onTouch](ts-universal-events-touch.md#events), and [onVisibleAreaChange](ts-universal-component-visible-area-change-event.md#events). 1466 1467### onAlert 1468 1469onAlert(callback: (event?: { url: string; message: string; result: JsResult }) => boolean) 1470 1471Called when **alert()** is invoked to display an alert dialog box on the web page. 1472 1473**Parameters** 1474 1475| Name | Type | Description | 1476| ------- | --------------------- | --------------- | 1477| url | string | URL of the web page where the dialog box is displayed.| 1478| message | string | Message displayed in the dialog box. | 1479| result | [JsResult](#jsresult) | User operation. | 1480 1481**Return value** 1482 1483| Type | Description | 1484| ------- | ---------------------------------------- | 1485| boolean | If the callback returns **true**, the application can use the system 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. If the callback returns **false**, the **\<Web>** component cannot trigger the system dialog box.| 1486 1487**Example** 1488 1489 ```ts 1490 // xxx.ets 1491 import web_webview from '@ohos.web.webview' 1492 1493 @Entry 1494 @Component 1495 struct WebComponent { 1496 controller: web_webview.WebviewController = new web_webview.WebviewController() 1497 build() { 1498 Column() { 1499 Web({ src: $rawfile("index.html"), controller: this.controller }) 1500 .onAlert((event) => { 1501 if (event) { 1502 console.log("event.url:" + event.url) 1503 console.log("event.message:" + event.message) 1504 AlertDialog.show({ 1505 title: 'onAlert', 1506 message: 'text', 1507 primaryButton: { 1508 value: 'cancel', 1509 action: () => { 1510 event.result.handleCancel() 1511 } 1512 }, 1513 secondaryButton: { 1514 value: 'ok', 1515 action: () => { 1516 event.result.handleConfirm() 1517 } 1518 }, 1519 cancel: () => { 1520 event.result.handleCancel() 1521 } 1522 }) 1523 } 1524 return true 1525 }) 1526 } 1527 } 1528 } 1529 ``` 1530 1531 HTML file to be loaded: 1532 ```html 1533 <!--index.html--> 1534 <!DOCTYPE html> 1535 <html> 1536 <head> 1537 <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8"> 1538 </head> 1539 <body> 1540 <h1>WebView onAlert Demo</h1> 1541 <button onclick="myFunction()">Click here</button> 1542 <script> 1543 function myFunction() { 1544 alert("Hello World"); 1545 } 1546 </script> 1547 </body> 1548 </html> 1549 ``` 1550 1551### onBeforeUnload 1552 1553onBeforeUnload(callback: (event?: { url: string; message: string; result: JsResult }) => boolean) 1554 1555Called 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. 1556 1557**Parameters** 1558 1559| Name | Type | Description | 1560| ------- | --------------------- | --------------- | 1561| url | string | URL of the web page where the dialog box is displayed.| 1562| message | string | Message displayed in the dialog box. | 1563| result | [JsResult](#jsresult) | User operation. | 1564 1565**Return value** 1566 1567| Type | Description | 1568| ------- | ---------------------------------------- | 1569| boolean | If the callback returns **true**, the application can use the system 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. If the callback returns **false**, the **\<Web>** component cannot trigger the system dialog box.| 1570 1571**Example** 1572 1573 ```ts 1574 // xxx.ets 1575 import web_webview from '@ohos.web.webview' 1576 1577 @Entry 1578 @Component 1579 struct WebComponent { 1580 controller: web_webview.WebviewController = new web_webview.WebviewController() 1581 1582 build() { 1583 Column() { 1584 Web({ src: $rawfile("index.html"), controller: this.controller }) 1585 .onBeforeUnload((event) => { 1586 if (event) { 1587 console.log("event.url:" + event.url) 1588 console.log("event.message:" + event.message) 1589 AlertDialog.show({ 1590 title: 'onBeforeUnload', 1591 message: 'text', 1592 primaryButton: { 1593 value: 'cancel', 1594 action: () => { 1595 event.result.handleCancel() 1596 } 1597 }, 1598 secondaryButton: { 1599 value: 'ok', 1600 action: () => { 1601 event.result.handleConfirm() 1602 } 1603 }, 1604 cancel: () => { 1605 event.result.handleCancel() 1606 } 1607 }) 1608 } 1609 return true 1610 }) 1611 } 1612 } 1613 } 1614 ``` 1615 1616 HTML file to be loaded: 1617 ```html 1618 <!--index.html--> 1619 <!DOCTYPE html> 1620 <html> 1621 <head> 1622 <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8"> 1623 </head> 1624 <body onbeforeunload="return myFunction()"> 1625 <h1>WebView onBeforeUnload Demo</h1> 1626 <a href="https://www.example.com">Click here</a> 1627 <script> 1628 function myFunction() { 1629 return "onBeforeUnload Event"; 1630 } 1631 </script> 1632 </body> 1633 </html> 1634 ``` 1635 1636### onConfirm 1637 1638onConfirm(callback: (event?: { url: string; message: string; result: JsResult }) => boolean) 1639 1640Called when **confirm()** is invoked by the web page. 1641 1642**Parameters** 1643 1644| Name | Type | Description | 1645| ------- | --------------------- | --------------- | 1646| url | string | URL of the web page where the dialog box is displayed.| 1647| message | string | Message displayed in the dialog box. | 1648| result | [JsResult](#jsresult) | User operation. | 1649 1650**Return value** 1651 1652| Type | Description | 1653| ------- | ---------------------------------------- | 1654| boolean | If the callback returns **true**, the application can use the system 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. If the callback returns **false**, the custom dialog box drawn in the function is ineffective.| 1655 1656**Example** 1657 1658 ```ts 1659 // xxx.ets 1660 import web_webview from '@ohos.web.webview' 1661 1662 @Entry 1663 @Component 1664 struct WebComponent { 1665 controller: web_webview.WebviewController = new web_webview.WebviewController() 1666 1667 build() { 1668 Column() { 1669 Web({ src: $rawfile("index.html"), controller: this.controller }) 1670 .onConfirm((event) => { 1671 if (event) { 1672 console.log("event.url:" + event.url) 1673 console.log("event.message:" + event.message) 1674 AlertDialog.show({ 1675 title: 'onConfirm', 1676 message: 'text', 1677 primaryButton: { 1678 value: 'cancel', 1679 action: () => { 1680 event.result.handleCancel() 1681 } 1682 }, 1683 secondaryButton: { 1684 value: 'ok', 1685 action: () => { 1686 event.result.handleConfirm() 1687 } 1688 }, 1689 cancel: () => { 1690 event.result.handleCancel() 1691 } 1692 }) 1693 } 1694 return true 1695 }) 1696 } 1697 } 1698 } 1699 ``` 1700 1701 HTML file to be loaded: 1702 ```html 1703 <!--index.html--> 1704 <!DOCTYPE html> 1705 <html> 1706 <head> 1707 <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8"> 1708 </head> 1709 1710 <body> 1711 <h1>WebView onConfirm Demo</h1> 1712 <button onclick="myFunction()">Click here</button> 1713 <p id="demo"></p> 1714 <script> 1715 function myFunction() { 1716 let x; 1717 let r = confirm("click button!"); 1718 if (r == true) { 1719 x = "ok"; 1720 } else { 1721 x = "cancel"; 1722 } 1723 document.getElementById("demo").innerHTML = x; 1724 } 1725 </script> 1726 </body> 1727 </html> 1728 ``` 1729 1730### onPrompt<sup>9+</sup> 1731 1732onPrompt(callback: (event?: { url: string; message: string; value: string; result: JsResult }) => boolean) 1733 1734Triggered when **prompt()** is invoked by the web page. 1735 1736**Parameters** 1737 1738| Name | Type | Description | 1739| ------- | --------------------- | --------------- | 1740| url | string | URL of the web page where the dialog box is displayed.| 1741| message | string | Message displayed in the dialog box. | 1742| result | [JsResult](#jsresult) | User operation. | 1743 1744**Return value** 1745 1746| Type | Description | 1747| ------- | ---------------------------------------- | 1748| boolean | If the callback returns **true**, the application can use the system 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. If the callback returns **false**, the **\<Web>** component cannot trigger the system dialog box.| 1749 1750**Example** 1751 1752 ```ts 1753 // xxx.ets 1754 import web_webview from '@ohos.web.webview' 1755 1756 @Entry 1757 @Component 1758 struct WebComponent { 1759 controller: web_webview.WebviewController = new web_webview.WebviewController() 1760 1761 build() { 1762 Column() { 1763 Web({ src: $rawfile("index.html"), controller: this.controller }) 1764 .onPrompt((event) => { 1765 if (event) { 1766 console.log("url:" + event.url) 1767 console.log("message:" + event.message) 1768 console.log("value:" + event.value) 1769 AlertDialog.show({ 1770 title: 'onPrompt', 1771 message: 'text', 1772 primaryButton: { 1773 value: 'cancel', 1774 action: () => { 1775 event.result.handleCancel() 1776 } 1777 }, 1778 secondaryButton: { 1779 value: 'ok', 1780 action: () => { 1781 event.result.handlePromptConfirm(event.value) 1782 } 1783 }, 1784 cancel: () => { 1785 event.result.handleCancel() 1786 } 1787 }) 1788 } 1789 return true 1790 }) 1791 } 1792 } 1793 } 1794 ``` 1795 1796 HTML file to be loaded: 1797 ```html 1798 <!--index.html--> 1799 <!DOCTYPE html> 1800 <html> 1801 <head> 1802 <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8"> 1803 </head> 1804 1805 <body> 1806 <h1>WebView onPrompt Demo</h1> 1807 <button onclick="myFunction()">Click here</button> 1808 <p id="demo"></p> 1809 <script> 1810 function myFunction() { 1811 let message = prompt("Message info", "Hello World"); 1812 if (message != null && message != "") { 1813 document.getElementById("demo").innerHTML = message; 1814 } 1815 } 1816 </script> 1817 </body> 1818 </html> 1819 ``` 1820 1821### onConsole 1822 1823onConsole(callback: (event?: { message: ConsoleMessage }) => boolean) 1824 1825Called to notify the host application of a JavaScript console message. 1826 1827**Parameters** 1828 1829| Name | Type | Description | 1830| ------- | --------------------------------- | --------- | 1831| message | [ConsoleMessage](#consolemessage) | Console message.| 1832 1833**Return value** 1834 1835| Type | Description | 1836| ------- | ----------------------------------- | 1837| boolean | Returns **true** if the message will not be printed to the console; returns **false** otherwise.| 1838 1839**Example** 1840 1841 ```ts 1842 // xxx.ets 1843 import web_webview from '@ohos.web.webview' 1844 1845 @Entry 1846 @Component 1847 struct WebComponent { 1848 controller: web_webview.WebviewController = new web_webview.WebviewController() 1849 1850 build() { 1851 Column() { 1852 Web({ src: 'www.example.com', controller: this.controller }) 1853 .onConsole((event) => { 1854 if (event) { 1855 console.log('getMessage:' + event.message.getMessage()) 1856 console.log('getSourceId:' + event.message.getSourceId()) 1857 console.log('getLineNumber:' + event.message.getLineNumber()) 1858 console.log('getMessageLevel:' + event.message.getMessageLevel()) 1859 } 1860 return false 1861 }) 1862 } 1863 } 1864 } 1865 ``` 1866 1867### onDownloadStart 1868 1869onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisposition: string, mimetype: string, contentLength: number }) => void) 1870 1871Instructs the main application to start downloading a file. 1872 1873**Parameters** 1874 1875| Name | Type | Description | 1876| ------------------ | ------------- | ----------------------------------- | 1877| url | string | URL for the download task. | 1878| userAgent | string | User agent used for download. | 1879| contentDisposition | string | Content-Disposition response header returned by the server, which may be empty.| 1880| mimetype | string | MIME type of the content returned by the server. | 1881| contentLength | contentLength | Length of the content returned by the server. | 1882 1883**Example** 1884 1885 ```ts 1886 // xxx.ets 1887 import web_webview from '@ohos.web.webview' 1888 1889 @Entry 1890 @Component 1891 struct WebComponent { 1892 controller: web_webview.WebviewController = new web_webview.WebviewController() 1893 1894 build() { 1895 Column() { 1896 Web({ src: 'www.example.com', controller: this.controller }) 1897 .onDownloadStart((event) => { 1898 if (event) { 1899 console.log('url:' + event.url) 1900 console.log('userAgent:' + event.userAgent) 1901 console.log('contentDisposition:' + event.contentDisposition) 1902 console.log('contentLength:' + event.contentLength) 1903 console.log('mimetype:' + event.mimetype) 1904 } 1905 }) 1906 } 1907 } 1908 } 1909 ``` 1910 1911### onErrorReceive 1912 1913onErrorReceive(callback: (event?: { request: WebResourceRequest, error: WebResourceError }) => void) 1914 1915Called when an error occurs during web page loading. For better results, simplify the implementation logic in the callback. This API is called when there is no network connection. 1916 1917**Parameters** 1918 1919| Name | Type | Description | 1920| ------- | ---------------------------------------- | --------------- | 1921| request | [WebResourceRequest](#webresourcerequest) | Encapsulation of a web page request. | 1922| error | [WebResourceError](#webresourceerror) | Encapsulation of a web page resource loading error.| 1923 1924**Example** 1925 1926 ```ts 1927 // xxx.ets 1928 import web_webview from '@ohos.web.webview' 1929 1930 @Entry 1931 @Component 1932 struct WebComponent { 1933 controller: web_webview.WebviewController = new web_webview.WebviewController() 1934 1935 build() { 1936 Column() { 1937 Web({ src: 'www.example.com', controller: this.controller }) 1938 .onErrorReceive((event) => { 1939 if (event) { 1940 console.log('getErrorInfo:' + event.error.getErrorInfo()) 1941 console.log('getErrorCode:' + event.error.getErrorCode()) 1942 console.log('url:' + event.request.getRequestUrl()) 1943 console.log('isMainFrame:' + event.request.isMainFrame()) 1944 console.log('isRedirect:' + event.request.isRedirect()) 1945 console.log('isRequestGesture:' + event.request.isRequestGesture()) 1946 console.log('getRequestHeader_headerKey:' + event.request.getRequestHeader().toString()) 1947 let result = event.request.getRequestHeader() 1948 console.log('The request header result size is ' + result.length) 1949 for (let i of result) { 1950 console.log('The request header key is : ' + i.headerKey + ', value is : ' + i.headerValue) 1951 } 1952 } 1953 }) 1954 } 1955 } 1956 } 1957 ``` 1958 1959### onHttpErrorReceive 1960 1961onHttpErrorReceive(callback: (event?: { request: WebResourceRequest, response: WebResourceResponse }) => void) 1962 1963Called when an HTTP error (the response code is greater than or equal to 400) occurs during web page resource loading. 1964 1965**Parameters** 1966 1967| Name | Type | Description | 1968| ------- | ---------------------------------------- | --------------- | 1969| request | [WebResourceRequest](#webresourcerequest) | Encapsulation of a web page request. | 1970| response | [WebResourceResponse](#webresourceresponse) | Encapsulation of a resource response.| 1971 1972**Example** 1973 1974 ```ts 1975 // xxx.ets 1976 import web_webview from '@ohos.web.webview' 1977 1978 @Entry 1979 @Component 1980 struct WebComponent { 1981 controller: web_webview.WebviewController = new web_webview.WebviewController() 1982 1983 build() { 1984 Column() { 1985 Web({ src: 'www.example.com', controller: this.controller }) 1986 .onHttpErrorReceive((event) => { 1987 if (event) { 1988 console.log('url:' + event.request.getRequestUrl()) 1989 console.log('isMainFrame:' + event.request.isMainFrame()) 1990 console.log('isRedirect:' + event.request.isRedirect()) 1991 console.log('isRequestGesture:' + event.request.isRequestGesture()) 1992 console.log('getResponseData:' + event.response.getResponseData()) 1993 console.log('getResponseEncoding:' + event.response.getResponseEncoding()) 1994 console.log('getResponseMimeType:' + event.response.getResponseMimeType()) 1995 console.log('getResponseCode:' + event.response.getResponseCode()) 1996 console.log('getReasonMessage:' + event.response.getReasonMessage()) 1997 let result = event.request.getRequestHeader() 1998 console.log('The request header result size is ' + result.length) 1999 for (let i of result) { 2000 console.log('The request header key is : ' + i.headerKey + ' , value is : ' + i.headerValue) 2001 } 2002 let resph = event.response.getResponseHeader() 2003 console.log('The response header result size is ' + resph.length) 2004 for (let i of resph) { 2005 console.log('The response header key is : ' + i.headerKey + ' , value is : ' + i.headerValue) 2006 } 2007 } 2008 }) 2009 } 2010 } 2011 } 2012 ``` 2013 2014### onPageBegin 2015 2016onPageBegin(callback: (event?: { url: string }) => void) 2017 2018Called 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. 2019 2020**Parameters** 2021 2022| Name | Type | Description | 2023| ---- | ------ | --------- | 2024| url | string | URL of the page.| 2025 2026**Example** 2027 2028 ```ts 2029 // xxx.ets 2030 import web_webview from '@ohos.web.webview' 2031 2032 @Entry 2033 @Component 2034 struct WebComponent { 2035 controller: web_webview.WebviewController = new web_webview.WebviewController() 2036 2037 build() { 2038 Column() { 2039 Web({ src: 'www.example.com', controller: this.controller }) 2040 .onPageBegin((event) => { 2041 if (event) { 2042 console.log('url:' + event.url) 2043 } 2044 }) 2045 } 2046 } 2047 } 2048 ``` 2049 2050### onPageEnd 2051 2052onPageEnd(callback: (event?: { url: string }) => void) 2053 2054Called when the web page loading is complete. This API takes effect only for the main frame content. 2055 2056**Parameters** 2057 2058| Name | Type | Description | 2059| ---- | ------ | --------- | 2060| url | string | URL of the page.| 2061 2062**Example** 2063 2064 ```ts 2065 // xxx.ets 2066 import web_webview from '@ohos.web.webview' 2067 2068 @Entry 2069 @Component 2070 struct WebComponent { 2071 controller: web_webview.WebviewController = new web_webview.WebviewController() 2072 2073 build() { 2074 Column() { 2075 Web({ src: 'www.example.com', controller: this.controller }) 2076 .onPageEnd((event) => { 2077 if (event) { 2078 console.log('url:' + event.url) 2079 } 2080 }) 2081 } 2082 } 2083 } 2084 ``` 2085 2086### onProgressChange 2087 2088onProgressChange(callback: (event?: { newProgress: number }) => void) 2089 2090Called when the web page loading progress changes. 2091 2092**Parameters** 2093 2094| Name | Type | Description | 2095| ----------- | ------ | --------------------- | 2096| newProgress | number | New loading progress. The value is an integer ranging from 0 to 100.| 2097 2098**Example** 2099 2100 ```ts 2101 // xxx.ets 2102 import web_webview from '@ohos.web.webview' 2103 2104 @Entry 2105 @Component 2106 struct WebComponent { 2107 controller: web_webview.WebviewController = new web_webview.WebviewController() 2108 2109 build() { 2110 Column() { 2111 Web({ src: 'www.example.com', controller: this.controller }) 2112 .onProgressChange((event) => { 2113 if (event) { 2114 console.log('newProgress:' + event.newProgress) 2115 } 2116 }) 2117 } 2118 } 2119 } 2120 ``` 2121 2122### onTitleReceive 2123 2124onTitleReceive(callback: (event?: { title: string }) => void) 2125 2126Called when the document title of the web page is changed. 2127 2128**Parameters** 2129 2130| Name | Type | Description | 2131| ----- | ------ | ------------- | 2132| title | string | Document title.| 2133 2134**Example** 2135 2136 ```ts 2137 // xxx.ets 2138 import web_webview from '@ohos.web.webview' 2139 2140 @Entry 2141 @Component 2142 struct WebComponent { 2143 controller: web_webview.WebviewController = new web_webview.WebviewController() 2144 2145 build() { 2146 Column() { 2147 Web({ src: 'www.example.com', controller: this.controller }) 2148 .onTitleReceive((event) => { 2149 if (event) { 2150 console.log('title:' + event.title) 2151 } 2152 }) 2153 } 2154 } 2155 } 2156 ``` 2157 2158### onRefreshAccessedHistory 2159 2160onRefreshAccessedHistory(callback: (event?: { url: string, isRefreshed: boolean }) => void) 2161 2162Called when loading of the web page is complete. This API is used by an application to update the historical link it accessed. 2163 2164**Parameters** 2165 2166| Name | Type | Description | 2167| ----------- | ------- | ---------------------------------------- | 2168| url | string | URL to be accessed. | 2169| isRefreshed | boolean | Whether the page is reloaded. The value **true** means that the page is reloaded by invoking the [refresh<sup>9+</sup>](../apis/js-apis-webview.md#refresh) API, and **false** means the opposite.| 2170 2171**Example** 2172 2173 ```ts 2174 // xxx.ets 2175 import web_webview from '@ohos.web.webview' 2176 2177 @Entry 2178 @Component 2179 struct WebComponent { 2180 controller: web_webview.WebviewController = new web_webview.WebviewController() 2181 2182 build() { 2183 Column() { 2184 Web({ src: 'www.example.com', controller: this.controller }) 2185 .onRefreshAccessedHistory((event) => { 2186 if (event) { 2187 console.log('url:' + event.url + ' isReload:' + event.isRefreshed) 2188 } 2189 }) 2190 } 2191 } 2192 } 2193 ``` 2194 2195### onSslErrorReceive<sup>(deprecated)</sup> 2196 2197onSslErrorReceive(callback: (event?: { handler: Function, error: object }) => void) 2198 2199Called when an SSL error occurs during resource loading. 2200 2201> **NOTE** 2202> 2203> 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. 2204 2205### onFileSelectorShow<sup>(deprecated)</sup> 2206 2207onFileSelectorShow(callback: (event?: { callback: Function, fileSelector: object }) => void) 2208 2209Called to process an HTML form whose input type is **file**, in response to the tapping of the **Select File** button. 2210 2211> **NOTE** 2212> 2213> 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. 2214 2215### onRenderExited<sup>9+</sup> 2216 2217onRenderExited(callback: (event?: { renderExitReason: RenderExitReason }) => void) 2218 2219Called when the rendering process exits abnormally. 2220 2221**Parameters** 2222 2223| Name | Type | Description | 2224| ---------------- | ---------------------------------------- | ---------------- | 2225| renderExitReason | [RenderExitReason](#renderexitreason)| Cause for the abnormal exit of the rendering process.| 2226 2227**Example** 2228 2229 ```ts 2230 // xxx.ets 2231 import web_webview from '@ohos.web.webview' 2232 2233 @Entry 2234 @Component 2235 struct WebComponent { 2236 controller: web_webview.WebviewController = new web_webview.WebviewController() 2237 2238 build() { 2239 Column() { 2240 Web({ src: 'chrome://crash/', controller: this.controller }) 2241 .onRenderExited((event) => { 2242 if (event) { 2243 console.log('reason:' + event.renderExitReason) 2244 } 2245 }) 2246 } 2247 } 2248 } 2249 ``` 2250 2251### onShowFileSelector<sup>9+</sup> 2252 2253onShowFileSelector(callback: (event?: { result: FileSelectorResult, fileSelector: FileSelectorParam }) => boolean) 2254 2255Called to process an HTML form whose input type is **file**, in response to the tapping of the **Select File** button. 2256 2257**Parameters** 2258 2259| Name | Type | Description | 2260| ------------ | ---------------------------------------- | ----------------- | 2261| result | [FileSelectorResult](#fileselectorresult9) | File selection result to be sent to the **\<Web>** component.| 2262| fileSelector | [FileSelectorParam](#fileselectorparam9) | Information about the file selector. | 2263 2264**Return value** 2265 2266| Type | Description | 2267| ------- | ---------------------------------------- | 2268| boolean | The value **true** means that the pop-up window provided by the system is displayed. If the callback returns **false**, the **\<Web>** component cannot trigger the system dialog box.| 2269 2270**Example** 2271 2272 ```ts 2273 // xxx.ets 2274 import web_webview from '@ohos.web.webview'; 2275 import picker from '@ohos.file.picker'; 2276 import { BusinessError } from '@ohos.base'; 2277 2278 @Entry 2279 @Component 2280 struct WebComponent { 2281 controller: web_webview.WebviewController = new web_webview.WebviewController() 2282 2283 build() { 2284 Column() { 2285 Web({ src: $rawfile('index.html'), controller: this.controller }) 2286 .onShowFileSelector((event) => { 2287 console.log('MyFileUploader onShowFileSelector invoked') 2288 const documentSelectOptions = new picker.DocumentSelectOptions(); 2289 let uri: string | null = null; 2290 const documentViewPicker = new picker.DocumentViewPicker(); 2291 documentViewPicker.select(documentSelectOptions).then((documentSelectResult) => { 2292 uri = documentSelectResult[0]; 2293 console.info('documentViewPicker.select to file succeed and uri is:' + uri); 2294 if (event) { 2295 event.result.handleFileList([uri]); 2296 } 2297 }).catch((err: BusinessError) => { 2298 console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`); 2299 }) 2300 return true 2301 }) 2302 } 2303 } 2304 } 2305 ``` 2306 2307 HTML file to be loaded: 2308 ```html 2309 <!DOCTYPE html> 2310 <html> 2311 <head> 2312 <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8"> 2313 </head> 2314 <body> 2315 <form id="upload-form" enctype="multipart/form-data"> 2316 <input type="file" id="upload" name="upload"/> 2317 </form> 2318 </body> 2319 </html> 2320 ``` 2321 2322### onResourceLoad<sup>9+</sup> 2323 2324onResourceLoad(callback: (event: {url: string}) => void) 2325 2326Called to notify the **\<Web>** component of the URL of the loaded resource file. 2327 2328**Parameters** 2329 2330| Name | Type | Description | 2331| ---- | ------ | -------------- | 2332| url | string | URL of the loaded resource file.| 2333 2334**Example** 2335 2336 ```ts 2337 // xxx.ets 2338 import web_webview from '@ohos.web.webview' 2339 2340 @Entry 2341 @Component 2342 struct WebComponent { 2343 controller: web_webview.WebviewController = new web_webview.WebviewController() 2344 2345 build() { 2346 Column() { 2347 Web({ src: 'www.example.com', controller: this.controller }) 2348 .onResourceLoad((event) => { 2349 console.log('onResourceLoad: ' + event.url) 2350 }) 2351 } 2352 } 2353 } 2354 ``` 2355 2356### onScaleChange<sup>9+</sup> 2357 2358onScaleChange(callback: (event: {oldScale: number, newScale: number}) => void) 2359 2360Called when the display ratio of this page changes. 2361 2362**Parameters** 2363 2364| Name | Type | Description | 2365| -------- | ------ | ------------ | 2366| oldScale | number | Display ratio of the page before the change.| 2367| newScale | number | Display ratio of the page after the change.| 2368 2369**Example** 2370 2371 ```ts 2372 // xxx.ets 2373 import web_webview from '@ohos.web.webview' 2374 2375 @Entry 2376 @Component 2377 struct WebComponent { 2378 controller: web_webview.WebviewController = new web_webview.WebviewController() 2379 2380 build() { 2381 Column() { 2382 Web({ src: 'www.example.com', controller: this.controller }) 2383 .onScaleChange((event) => { 2384 console.log('onScaleChange changed from ' + event.oldScale + ' to ' + event.newScale) 2385 }) 2386 } 2387 } 2388 } 2389 ``` 2390 2391### onUrlLoadIntercept<sup>(deprecated)</sup> 2392 2393onUrlLoadIntercept(callback: (event?: { data:string | WebResourceRequest }) => boolean) 2394 2395Called 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. 2396This API is deprecated since API version 10. You are advised to use [onLoadIntercept<sup>10+</sup>](#onloadintercept10) instead. 2397 2398**Parameters** 2399 2400| Name | Type | Description | 2401| ---- | ---------------------------------------- | --------- | 2402| data | string \| [WebResourceRequest](#webresourcerequest) | URL information.| 2403 2404**Return value** 2405 2406| Type | Description | 2407| ------- | ------------------------ | 2408| boolean | Returns **true** if the access is blocked; returns **false** otherwise.| 2409 2410**Example** 2411 2412 ```ts 2413 // xxx.ets 2414 import web_webview from '@ohos.web.webview' 2415 2416 @Entry 2417 @Component 2418 struct WebComponent { 2419 controller: web_webview.WebviewController = new web_webview.WebviewController() 2420 2421 build() { 2422 Column() { 2423 Web({ src: 'www.example.com', controller: this.controller }) 2424 .onUrlLoadIntercept((event) => { 2425 if (event) { 2426 console.log('onUrlLoadIntercept ' + event.data.toString()) 2427 } 2428 return true 2429 }) 2430 } 2431 } 2432 } 2433 ``` 2434 2435### onInterceptRequest<sup>9+</sup> 2436 2437onInterceptRequest(callback: (event?: { request: WebResourceRequest}) => WebResourceResponse) 2438 2439Called when the **\<Web>** component is about to access a URL. This API is used to block the URL and return the response data. 2440 2441**Parameters** 2442 2443| Name | Type | Description | 2444| ------- | ---------------------------------------- | ----------- | 2445| request | [WebResourceRequest](#webresourcerequest) | Information about the URL request.| 2446 2447**Return value** 2448 2449| Type | Description | 2450| ---------------------------------------- | ---------------------------------------- | 2451| [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.| 2452 2453**Example** 2454 2455 ```ts 2456 // xxx.ets 2457 import web_webview from '@ohos.web.webview' 2458 2459 @Entry 2460 @Component 2461 struct WebComponent { 2462 controller: web_webview.WebviewController = new web_webview.WebviewController() 2463 responseweb: WebResourceResponse = new WebResourceResponse() 2464 heads:Header[] = new Array() 2465 @State webdata: string = "<!DOCTYPE html>\n" + 2466 "<html>\n"+ 2467 "<head>\n"+ 2468 "<title>intercept test</title>\n"+ 2469 "</head>\n"+ 2470 "<body>\n"+ 2471 "<h1>intercept test</h1>\n"+ 2472 "</body>\n"+ 2473 "</html>" 2474 build() { 2475 Column() { 2476 Web({ src: 'www.example.com', controller: this.controller }) 2477 .onInterceptRequest((event) => { 2478 if (event) { 2479 console.log('url:' + event.request.getRequestUrl()) 2480 } 2481 let head1:Header = { 2482 headerKey:"Connection", 2483 headerValue:"keep-alive" 2484 } 2485 let head2:Header = { 2486 headerKey:"Cache-Control", 2487 headerValue:"no-cache" 2488 } 2489 let length = this.heads.push(head1) 2490 length = this.heads.push(head2) 2491 this.responseweb.setResponseHeader(this.heads) 2492 this.responseweb.setResponseData(this.webdata) 2493 this.responseweb.setResponseEncoding('utf-8') 2494 this.responseweb.setResponseMimeType('text/html') 2495 this.responseweb.setResponseCode(200) 2496 this.responseweb.setReasonMessage('OK') 2497 return this.responseweb 2498 }) 2499 } 2500 } 2501 } 2502 ``` 2503 2504### onHttpAuthRequest<sup>9+</sup> 2505 2506onHttpAuthRequest(callback: (event?: { handler: HttpAuthHandler, host: string, realm: string}) => boolean) 2507 2508Called when an HTTP authentication request is received. 2509 2510**Parameters** 2511 2512| Name | Type | Description | 2513| ------- | ------------------------------------ | ---------------- | 2514| handler | [HttpAuthHandler](#httpauthhandler9) | User operation. | 2515| host | string | Host to which HTTP authentication credentials apply.| 2516| realm | string | Realm to which HTTP authentication credentials apply. | 2517 2518**Return value** 2519 2520| Type | Description | 2521| ------- | --------------------- | 2522| boolean | Returns **true** if the authentication is successful; returns **false** otherwise.| 2523 2524**Example** 2525 2526 ```ts 2527 // xxx.ets 2528 import web_webview from '@ohos.web.webview' 2529 @Entry 2530 @Component 2531 struct WebComponent { 2532 controller: web_webview.WebviewController = new web_webview.WebviewController() 2533 httpAuth: boolean = false 2534 2535 build() { 2536 Column() { 2537 Web({ src: 'www.example.com', controller: this.controller }) 2538 .onHttpAuthRequest((event) => { 2539 if (event) { 2540 AlertDialog.show({ 2541 title: 'onHttpAuthRequest', 2542 message: 'text', 2543 primaryButton: { 2544 value: 'cancel', 2545 action: () => { 2546 event.handler.cancel() 2547 } 2548 }, 2549 secondaryButton: { 2550 value: 'ok', 2551 action: () => { 2552 this.httpAuth = event.handler.isHttpAuthInfoSaved() 2553 if (this.httpAuth == false) { 2554 web_webview.WebDataBase.saveHttpAuthCredentials( 2555 event.host, 2556 event.realm, 2557 "2222", 2558 "2222" 2559 ) 2560 event.handler.cancel() 2561 } 2562 } 2563 }, 2564 cancel: () => { 2565 event.handler.cancel() 2566 } 2567 }) 2568 } 2569 return true 2570 }) 2571 } 2572 } 2573 } 2574 ``` 2575### onSslErrorEventReceive<sup>9+</sup> 2576 2577onSslErrorEventReceive(callback: (event: { handler: SslErrorHandler, error: SslError }) => void) 2578 2579Called when an SSL error occurs during resource loading. 2580 2581**Parameters** 2582 2583| Name | Type | Description | 2584| ------- | ------------------------------------ | -------------- | 2585| handler | [SslErrorHandler](#sslerrorhandler9) | User operation.| 2586| error | [SslError](#sslerror9) | Error code. | 2587 2588**Example** 2589 2590 ```ts 2591 // xxx.ets 2592 import web_webview from '@ohos.web.webview' 2593 @Entry 2594 @Component 2595 struct WebComponent { 2596 controller: web_webview.WebviewController = new web_webview.WebviewController() 2597 2598 build() { 2599 Column() { 2600 Web({ src: 'www.example.com', controller: this.controller }) 2601 .onSslErrorEventReceive((event) => { 2602 AlertDialog.show({ 2603 title: 'onSslErrorEventReceive', 2604 message: 'text', 2605 primaryButton: { 2606 value: 'confirm', 2607 action: () => { 2608 event.handler.handleConfirm() 2609 } 2610 }, 2611 secondaryButton: { 2612 value: 'cancel', 2613 action: () => { 2614 event.handler.handleCancel() 2615 } 2616 }, 2617 cancel: () => { 2618 event.handler.handleCancel() 2619 } 2620 }) 2621 }) 2622 } 2623 } 2624 } 2625 ``` 2626 2627### onClientAuthenticationRequest<sup>9+</sup> 2628 2629onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationHandler, host : string, port : number, keyTypes : Array<string>, issuers : Array<string>}) => void) 2630 2631Called when an SSL client certificate request is received. 2632 2633**Parameters** 2634 2635| Name | Type | Description | 2636| -------- | ---------------------------------------- | --------------- | 2637| handler | [ClientAuthenticationHandler](#clientauthenticationhandler9) | User operation. | 2638| host | string | Host name of the server that requests a certificate. | 2639| port | number | Port number of the server that requests a certificate. | 2640| keyTypes | Array<string\> | Acceptable asymmetric private key types. | 2641| issuers | Array<string\> | Issuer of the certificate that matches the private key.| 2642 2643 **Example** 2644 This example shows two-way authentication when interconnection with certificate management is not supported. 2645 ```ts 2646 // xxx.ets API9 2647 import web_webview from '@ohos.web.webview' 2648 @Entry 2649 @Component 2650 struct WebComponent { 2651 controller: web_webview.WebviewController = new web_webview.WebviewController() 2652 2653 build() { 2654 Column() { 2655 Web({ src: 'www.example.com', controller: this.controller }) 2656 .onClientAuthenticationRequest((event) => { 2657 AlertDialog.show({ 2658 title: 'onClientAuthenticationRequest', 2659 message: 'text', 2660 primaryButton: { 2661 value: 'confirm', 2662 action: () => { 2663 event.handler.confirm("/system/etc/user.pk8", "/system/etc/chain-user.pem") 2664 } 2665 }, 2666 secondaryButton: { 2667 value: 'cancel', 2668 action: () => { 2669 event.handlqq 2670 er.cancel() 2671 } 2672 }, 2673 cancel: () => { 2674 event.handler.ignore() 2675 } 2676 }) 2677 }) 2678 } 2679 } 2680 } 2681 ``` 2682 2683 This example shows two-way authentication when interconnection with certificate management is supported. 2684 2685 1. Construct the singleton object **GlobalContext**. 2686 2687 ```ts 2688 // GlobalContext.ts 2689 export class GlobalContext { 2690 private constructor() {} 2691 private static instance: GlobalContext; 2692 private _objects = new Map<string, Object>(); 2693 2694 public static getContext(): GlobalContext { 2695 if (!GlobalContext.instance) { 2696 GlobalContext.instance = new GlobalContext(); 2697 } 2698 return GlobalContext.instance; 2699 } 2700 2701 getObject(value: string): Object | undefined { 2702 return this._objects.get(value); 2703 } 2704 2705 setObject(key: string, objectClass: Object): void { 2706 this._objects.set(key, objectClass); 2707 } 2708 } 2709 ``` 2710 2711 2. Implement two-way authentication. 2712 2713 ```ts 2714 // xxx.ets API10 2715 import common from '@ohos.app.ability.common'; 2716 import Want from '@ohos.app.ability.Want'; 2717 import web_webview from '@ohos.web.webview' 2718 import { BusinessError } from '@ohos.base'; 2719 import bundleManager from '@ohos.bundle.bundleManager' 2720 import { GlobalContext } from '../GlobalContext' 2721 2722 let uri = ""; 2723 2724 export default class CertManagerService { 2725 private static sInstance: CertManagerService; 2726 private authUri = ""; 2727 private appUid = ""; 2728 2729 public static getInstance(): CertManagerService { 2730 if (CertManagerService.sInstance == null) { 2731 CertManagerService.sInstance = new CertManagerService(); 2732 } 2733 return CertManagerService.sInstance; 2734 } 2735 2736 async grantAppPm(callback: (message: string) => void) { 2737 let message = ''; 2738 let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION; 2739 // Note: Replace com.example.myapplication with the actual application name. 2740 try { 2741 bundleManager.getBundleInfoForSelf(bundleFlags).then((data) => { 2742 console.info('getBundleInfoForSelf successfully. Data: %{public}s', JSON.stringify(data)); 2743 this.appUid = data.appInfo.uid.toString(); 2744 }).catch((err: BusinessError) => { 2745 console.error('getBundleInfoForSelf failed. Cause: %{public}s', err.message); 2746 }); 2747 } catch (err) { 2748 let message = (err as BusinessError).message; 2749 console.error('getBundleInfoForSelf failed: %{public}s', message); 2750 } 2751 2752 // Note: Add GlobalContext.getContext().setObject("AbilityContext", this.context) to the onCreate function in the MainAbility.ts file. 2753 let abilityContext = GlobalContext.getContext().getObject("AbilityContext") as common.UIAbilityContext 2754 await abilityContext.startAbilityForResult( 2755 { 2756 bundleName: "com.ohos.certmanager", 2757 abilityName: "MainAbility", 2758 uri: "requestAuthorize", 2759 parameters: { 2760 appUid: this.appUid, // Pass the UID of the requesting application. 2761 } 2762 } as Want) 2763 .then((data: common.AbilityResult) => { 2764 if (!data.resultCode && data.want) { 2765 if (data.want.parameters) { 2766 this.authUri = data.want.parameters.authUri as string; // Obtain the returned authUri after successful authorization. 2767 } 2768 } 2769 }) 2770 message += "after grantAppPm authUri: " + this.authUri; 2771 uri = this.authUri; 2772 callback(message) 2773 } 2774 } 2775 2776 @Entry 2777 @Component 2778 struct WebComponent { 2779 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2780 @State message: string = 'Hello World' // message is used for debugging and observation. 2781 certManager = CertManagerService.getInstance(); 2782 2783 build() { 2784 Row() { 2785 Column() { 2786 Row() { 2787 // Step 1: Perform authorization to obtain the URI. 2788 Button('GrantApp') 2789 .onClick(() => { 2790 this.certManager.grantAppPm((data) => { 2791 this.message = data; 2792 }); 2793 }) 2794 // Step 2: After the authorization, in two-way authentication, the onClientAuthenticationRequest callback is used to send the URI to the web server for authentication. 2795 Button("ClientCertAuth") 2796 .onClick(() => { 2797 this.controller.loadUrl('https://www.example2.com'); // Server website that supports two-way authentication. 2798 }) 2799 } 2800 2801 Web({ src: 'https://www.example1.com', controller: this.controller }) 2802 .fileAccess(true) 2803 .javaScriptAccess(true) 2804 .domStorageAccess(true) 2805 .onlineImageAccess(true) 2806 2807 .onClientAuthenticationRequest((event) => { 2808 AlertDialog.show({ 2809 title: 'ClientAuth', 2810 message: 'Text', 2811 confirm: { 2812 value: 'Confirm', 2813 action: () => { 2814 event.handler.confirm(uri); 2815 } 2816 }, 2817 cancel: () => { 2818 event.handler.cancel(); 2819 } 2820 }) 2821 }) 2822 } 2823 } 2824 .width('100%') 2825 .height('100%') 2826 } 2827 } 2828 ``` 2829 2830### onPermissionRequest<sup>9+</sup> 2831 2832onPermissionRequest(callback: (event?: { request: PermissionRequest }) => void) 2833 2834Called when a permission request is received. 2835 2836**Parameters** 2837 2838| Name | Type | Description | 2839| ------- | ---------------------------------------- | -------------- | 2840| request | [PermissionRequest](#permissionrequest9) | User operation.| 2841 2842**Example** 2843 2844 ```ts 2845 // xxx.ets 2846 import web_webview from '@ohos.web.webview' 2847 2848 @Entry 2849 @Component 2850 struct WebComponent { 2851 controller: web_webview.WebviewController = new web_webview.WebviewController() 2852 build() { 2853 Column() { 2854 Web({ src: $rawfile('index.html'), controller: this.controller }) 2855 .onPermissionRequest((event) => { 2856 if (event) { 2857 AlertDialog.show({ 2858 title: 'title', 2859 message: 'text', 2860 primaryButton: { 2861 value: 'deny', 2862 action: () => { 2863 event.request.deny() 2864 } 2865 }, 2866 secondaryButton: { 2867 value: 'onConfirm', 2868 action: () => { 2869 event.request.grant(event.request.getAccessibleResource()) 2870 } 2871 }, 2872 cancel: () => { 2873 event.request.deny() 2874 } 2875 }) 2876 } 2877 }) 2878 } 2879 } 2880 } 2881 ``` 2882 2883 HTML file to be loaded: 2884 ```html 2885 <!-- index.html --> 2886 <!DOCTYPE html> 2887 <html> 2888 <head> 2889 <meta charset="UTF-8"> 2890 </head> 2891 <body> 2892 <video id="video" width="500px" height="500px" autoplay="autoplay"></video> 2893 <canvas id="canvas" width="500px" height="500px"></canvas> 2894 <br> 2895 <input type="button" title="HTML5 Camera" value="Enable Camera" onclick="getMedia()"/> 2896 <script> 2897 function getMedia() 2898 { 2899 let constraints = { 2900 video: {width: 500, height: 500}, 2901 audio: true 2902 }; 2903 // Obtain the video camera area. 2904 let video = document.getElementByld("video"); 2905 // Returned Promise object 2906 let promise = navigator.mediaDevices.getUserMedia(constraints); 2907 // then() is asynchronous. Invoke the MediaStream object as a parameter. 2908 promise.then(function (MediaStream) { 2909 video.srcObject = MediaStream; 2910 video.play(); 2911 }); 2912 } 2913 </script> 2914 </body> 2915 </html> 2916 ``` 2917 2918### onContextMenuShow<sup>9+</sup> 2919 2920onContextMenuShow(callback: (event?: { param: WebContextMenuParam, result: WebContextMenuResult }) => boolean) 2921 2922Called 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. 2923 2924**Parameters** 2925 2926| Name | Type | Description | 2927| ------ | ---------------------------------------- | ----------- | 2928| param | [WebContextMenuParam](#webcontextmenuparam9) | Parameters related to the context menu. | 2929| result | [WebContextMenuResult](#webcontextmenuresult9) | Result of the context menu.| 2930 2931**Return value** 2932 2933| Type | Description | 2934| ------- | ------------------------ | 2935| boolean | The value **true** means a custom menu, and **false** means the default menu.| 2936 2937**Example** 2938 2939 ```ts 2940 // xxx.ets 2941 import web_webview from '@ohos.web.webview' 2942 import pasteboard from '@ohos.pasteboard' 2943 const TAG = 'ContextMenu'; 2944 2945 @Entry 2946 @Component 2947 struct WebComponent { 2948 controller: web_webview.WebviewController = new web_webview.WebviewController() 2949 private result: WebContextMenuResult | undefined = undefined; 2950 @State linkUrl: string = ''; 2951 @State offsetX: number = 0; 2952 @State offsetY: number = 0; 2953 @State showMenu: boolean = false; 2954 @Builder 2955 // Build and trigger a custom menu. 2956 MenuBuilder(){ 2957 // A component that is used to present a vertical list of items to the user. 2958 Menu(){ 2959 // A component that is used to represent an item in a menu. 2960 MenuItem({ 2961 content: 'Copy Image', 2962 }) 2963 .width(100) 2964 .height(50) 2965 .onClick(() => { 2966 this.result?.copyImage(); 2967 this.showMenu = false; 2968 }) 2969 MenuItem({ 2970 content: 'Cut', 2971 }) 2972 .width(100) 2973 .height(50) 2974 .onClick(() => { 2975 this.result?.cut(); 2976 this.showMenu = false; 2977 }) 2978 MenuItem({ 2979 content: 'Copy', 2980 }) 2981 .width(100) 2982 .height(50) 2983 .onClick(() => { 2984 this.result?.copy(); 2985 this.showMenu = false; 2986 }) 2987 MenuItem({ 2988 content: 'Paste', 2989 }) 2990 .width(100) 2991 .height(50) 2992 .onClick(() => { 2993 this.result?.paste(); 2994 this.showMenu = false; 2995 }) 2996 MenuItem({ 2997 content: 'Copy Link', 2998 }) 2999 .width(100) 3000 .height(50) 3001 .onClick(() => { 3002 let pasteData = pasteboard.createData('text/plain', this.linkUrl); 3003 pasteboard.getSystemPasteboard().setData(pasteData, (error)=>{ 3004 if(error){ 3005 return; 3006 } 3007 }) 3008 this.showMenu = false; 3009 }) 3010 MenuItem({ 3011 content: 'Select All', 3012 }) 3013 .width(100) 3014 .height(50) 3015 .onClick(() => { 3016 this.result?.selectAll(); 3017 this.showMenu = false; 3018 }) 3019 } 3020 .width(150) 3021 .height(300) 3022 } 3023 3024 build() { 3025 Column() { 3026 Web({ src: $rawfile("index.html"), controller: this.controller }) 3027 // Trigger a custom dialog box. 3028 .onContextMenuShow((event) => { 3029 if (event) { 3030 this.result = event.result 3031 console.info("x coord = " + event.param.x()) 3032 console.info("link url = " + event.param.getLinkUrl()) 3033 this.linkUrl = event.param.getLinkUrl() 3034 } 3035 console.info(TAG, `x: ${this.offsetX}, y: ${this.offsetY}`); 3036 this.showMenu = true; 3037 this.offsetX = 250; 3038 this.offsetY = Math.max(px2vp(event?.param.y() ?? 0) - 0, 0); 3039 return true 3040 }) 3041 .bindPopup(this.showMenu, 3042 { 3043 builder: this.MenuBuilder(), 3044 enableArrow: false, 3045 placement: Placement.LeftTop, 3046 offset: { x: this.offsetX, y: this.offsetY}, 3047 mask: false, 3048 onStateChange: (e) => { 3049 if(!e.isVisible){ 3050 this.showMenu = false; 3051 this.result!.closeContextMenu(); 3052 } 3053 } 3054 }) 3055 } 3056 } 3057 } 3058 ``` 3059 3060 HTML file to be loaded: 3061 ```html 3062 <!-- index.html --> 3063 <!DOCTYPE html> 3064 <html lang="en"> 3065 <body> 3066 <h1>onContextMenuShow</h1> 3067 <a href="http://www.example.com" style="font-size:27px">URL www.example.com</a> 3068 // Place any image in the rawfile directory and name it example.png. 3069 <div><img src="example.png"></div> 3070 <p>Right-click text to display the context menu</p> 3071 </body> 3072 </html> 3073 ``` 3074 3075### onScroll<sup>9+</sup> 3076 3077onScroll(callback: (event: {xOffset: number, yOffset: number}) => void) 3078 3079Called when the scrollbar of the page scrolls. 3080 3081**Parameters** 3082 3083| Name | Type | Description | 3084| ------- | ------ | ------------ | 3085| xOffset | number | Position of the scrollbar on the x-axis relative to the leftmost of the web page.| 3086| yOffset | number | Position of the scrollbar on the y-axis relative to the top of the web page.| 3087 3088**Example** 3089 3090 ```ts 3091 // xxx.ets 3092 import web_webview from '@ohos.web.webview' 3093 3094 @Entry 3095 @Component 3096 struct WebComponent { 3097 controller: web_webview.WebviewController = new web_webview.WebviewController() 3098 build() { 3099 Column() { 3100 Web({ src: 'www.example.com', controller: this.controller }) 3101 .onScroll((event) => { 3102 console.info("x = " + event.xOffset) 3103 console.info("y = " + event.yOffset) 3104 }) 3105 } 3106 } 3107 } 3108 ``` 3109 3110### onGeolocationShow 3111 3112onGeolocationShow(callback: (event?: { origin: string, geolocation: JsGeolocation }) => void) 3113 3114Called when a request to obtain the geolocation information is received. 3115 3116**Parameters** 3117 3118| Name | Type | Description | 3119| ----------- | ------------------------------- | -------------- | 3120| origin | string | Index of the origin. | 3121| geolocation | [JsGeolocation](#jsgeolocation) | User operation.| 3122 3123**Example** 3124 3125 ```ts 3126 // xxx.ets 3127 import web_webview from '@ohos.web.webview' 3128 3129 @Entry 3130 @Component 3131 struct WebComponent { 3132 controller: web_webview.WebviewController = new web_webview.WebviewController() 3133 build() { 3134 Column() { 3135 Web({ src:$rawfile('index.html'), controller:this.controller }) 3136 .geolocationAccess(true) 3137 .onGeolocationShow((event) => { 3138 if (event) { 3139 AlertDialog.show({ 3140 title: 'title', 3141 message: 'text', 3142 confirm: { 3143 value: 'onConfirm', 3144 action: () => { 3145 event.geolocation.invoke(event.origin, true, true) 3146 } 3147 }, 3148 cancel: () => { 3149 event.geolocation.invoke(event.origin, false, true) 3150 } 3151 }) 3152 } 3153 }) 3154 } 3155 } 3156 } 3157 ``` 3158 3159 HTML file to be loaded: 3160 ```html 3161 <!DOCTYPE html> 3162 <html> 3163 <body> 3164 <p id="locationInfo">Location information</p> 3165 <button onclick="getLocation()">Get Location</button> 3166 <script> 3167 var locationInfo=document.getElementById("locationInfo"); 3168 function getLocation(){ 3169 if (navigator.geolocation) { 3170 <!-- Access to the device location by the frontend page --> 3171 navigator.geolocation.getCurrentPosition(showPosition); 3172 } 3173 } 3174 function showPosition(position){ 3175 locationInfo.innerHTML="Latitude: " + position.coords.latitude + "<br />Longitude: " + position.coords.longitude; 3176 } 3177 </script> 3178 </body> 3179 </html> 3180 ``` 3181 3182### onGeolocationHide 3183 3184onGeolocationHide(callback: () => void) 3185 3186Called to notify the user that the request for obtaining the geolocation information received when **[onGeolocationShow](#ongeolocationshow)** is called has been canceled. 3187 3188**Parameters** 3189 3190| Name | Type | Description | 3191| -------- | ---------- | -------------------- | 3192| callback | () => void | Callback invoked when the request for obtaining geolocation information has been canceled. | 3193 3194**Example** 3195 3196 ```ts 3197 // xxx.ets 3198 import web_webview from '@ohos.web.webview' 3199 3200 @Entry 3201 @Component 3202 struct WebComponent { 3203 controller: web_webview.WebviewController = new web_webview.WebviewController() 3204 build() { 3205 Column() { 3206 Web({ src:'www.example.com', controller:this.controller }) 3207 .geolocationAccess(true) 3208 .onGeolocationHide(() => { 3209 console.log("onGeolocationHide...") 3210 }) 3211 } 3212 } 3213 } 3214 ``` 3215 3216### onFullScreenEnter<sup>9+</sup> 3217 3218onFullScreenEnter(callback: (event: { handler: FullScreenExitHandler }) => void) 3219 3220Called when the component enters full screen mode. 3221 3222**Parameters** 3223 3224| Name | Type | Description | 3225| ------- | ---------------------------------------- | -------------- | 3226| handler | [FullScreenExitHandler](#fullscreenexithandler9) | Function handle for exiting full screen mode.| 3227 3228**Example** 3229 3230 ```ts 3231 // xxx.ets 3232 import web_webview from '@ohos.web.webview' 3233 3234 @Entry 3235 @Component 3236 struct WebComponent { 3237 controller: web_webview.WebviewController = new web_webview.WebviewController() 3238 handler: FullScreenExitHandler | null = null 3239 build() { 3240 Column() { 3241 Web({ src:'www.example.com', controller:this.controller }) 3242 .onFullScreenEnter((event) => { 3243 console.log("onFullScreenEnter...") 3244 this.handler = event.handler 3245 }) 3246 } 3247 } 3248 } 3249 ``` 3250 3251### onFullScreenExit<sup>9+</sup> 3252 3253onFullScreenExit(callback: () => void) 3254 3255Called when the component exits full screen mode. 3256 3257**Parameters** 3258 3259| Name | Type | Description | 3260| -------- | ---------- | ------------- | 3261| callback | () => void | Callback invoked when the component exits full screen mode.| 3262 3263**Example** 3264 3265 ```ts 3266 // xxx.ets 3267 import web_webview from '@ohos.web.webview' 3268 3269 @Entry 3270 @Component 3271 struct WebComponent { 3272 controller: web_webview.WebviewController = new web_webview.WebviewController() 3273 handler: FullScreenExitHandler | null = null 3274 build() { 3275 Column() { 3276 Web({ src:'www.example.com', controller:this.controller }) 3277 .onFullScreenExit(() => { 3278 console.log("onFullScreenExit...") 3279 if (this.handler) { 3280 this.handler.exitFullScreen() 3281 } 3282 }) 3283 .onFullScreenEnter((event) => { 3284 this.handler = event.handler 3285 }) 3286 } 3287 } 3288 } 3289 ``` 3290 3291### onWindowNew<sup>9+</sup> 3292 3293onWindowNew(callback: (event: {isAlert: boolean, isUserTrigger: boolean, targetUrl: string, handler: ControllerHandler}) => void) 3294 3295Called when a new window is created. This API takes effect when **multiWindowAccess** is enabled. 3296If the **event.handler.setWebController** API is not called, the render process will be blocked. 3297If opening a new window is not needed, set the parameter to **null** when calling the **event.handler.setWebController** API. 3298 3299**Parameters** 3300 3301| Name | Type | Description | 3302| ------------- | ---------------------------------------- | -------------------------- | 3303| isAlert | boolean | 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.| 3304| isUserTrigger | boolean | 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. | 3305| targetUrl | string | Target URL. | 3306| handler | [ControllerHandler](#controllerhandler9) | **WebviewController** instance for setting the new window. | 3307 3308**Example** 3309 3310 ```ts 3311 // xxx.ets 3312 import web_webview from '@ohos.web.webview' 3313 3314 // There are two <Web> components on the same page. When the WebComponent object opens a new window, the NewWebViewComp object is displayed. 3315 @CustomDialog 3316 struct NewWebViewComp { 3317 controller?: CustomDialogController 3318 webviewController1: web_webview.WebviewController = new web_webview.WebviewController() 3319 build() { 3320 Column() { 3321 Web({ src: "", controller: this.webviewController1 }) 3322 .javaScriptAccess(true) 3323 .multiWindowAccess(false) 3324 .onWindowExit(()=> { 3325 console.info("NewWebViewComp onWindowExit") 3326 if (this.controller) { 3327 this.controller.close() 3328 } 3329 }) 3330 } 3331 } 3332 } 3333 3334 @Entry 3335 @Component 3336 struct WebComponent { 3337 controller: web_webview.WebviewController = new web_webview.WebviewController() 3338 dialogController: CustomDialogController | null = null 3339 build() { 3340 Column() { 3341 Web({ src: 'www.example.com', controller: this.controller }) 3342 .javaScriptAccess(true) 3343 // MultiWindowAccess needs to be enabled. 3344 .multiWindowAccess(true) 3345 .allowWindowOpenMethod(true) 3346 .onWindowNew((event) => { 3347 if (this.dialogController) { 3348 this.dialogController.close() 3349 } 3350 let popController:web_webview.WebviewController = new web_webview.WebviewController() 3351 this.dialogController = new CustomDialogController({ 3352 builder: NewWebViewComp({webviewController1: popController}) 3353 }) 3354 this.dialogController.open() 3355 // Return the WebviewController object corresponding to the new window to the <Web> kernel. 3356 // If opening a new window is not needed, set the parameter to null when calling the event.handler.setWebController API. 3357 // If the event.handler.setWebController API is not called, the render process will be blocked. 3358 event.handler.setWebController(popController) 3359 }) 3360 } 3361 } 3362 } 3363 ``` 3364 3365### onWindowExit<sup>9+</sup> 3366 3367onWindowExit(callback: () => void) 3368 3369Called when this window is closed. 3370 3371**Parameters** 3372 3373| Name | Type | Description | 3374| -------- | ---------- | ------------ | 3375| callback | () => void | Callback invoked when the window is closed.| 3376 3377**Example** 3378 3379 ```ts 3380 // xxx.ets 3381 import web_webview from '@ohos.web.webview' 3382 3383 @Entry 3384 @Component 3385 struct WebComponent { 3386 controller: web_webview.WebviewController = new web_webview.WebviewController() 3387 build() { 3388 Column() { 3389 Web({ src:'www.example.com', controller: this.controller }) 3390 .onWindowExit(() => { 3391 console.log("onWindowExit...") 3392 }) 3393 } 3394 } 3395 } 3396 ``` 3397 3398### onSearchResultReceive<sup>9+</sup> 3399 3400onSearchResultReceive(callback: (event?: {activeMatchOrdinal: number, numberOfMatches: number, isDoneCounting: boolean}) => void): WebAttribute 3401 3402Called to notify the caller of the search result on the web page. 3403 3404**Parameters** 3405 3406| Name | Type | Description | 3407| ------------------ | ------- | ---------------------------------------- | 3408| activeMatchOrdinal | number | Sequence number of the current match, which starts from 0. | 3409| numberOfMatches | number | Total number of matches. | 3410| isDoneCounting | boolean | Whether the search operation on the current page is complete. This API may be called multiple times until **isDoneCounting** is **true**.| 3411 3412**Example** 3413 3414 ```ts 3415 // xxx.ets 3416 import web_webview from '@ohos.web.webview' 3417 3418 @Entry 3419 @Component 3420 struct WebComponent { 3421 controller: web_webview.WebviewController = new web_webview.WebviewController() 3422 3423 build() { 3424 Column() { 3425 Web({ src: 'www.example.com', controller: this.controller }) 3426 .onSearchResultReceive(ret => { 3427 if (ret) { 3428 console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal + 3429 "[total]" + ret.numberOfMatches + "[isDone]"+ ret.isDoneCounting) 3430 } 3431 }) 3432 } 3433 } 3434 } 3435 ``` 3436 3437### onDataResubmitted<sup>9+</sup> 3438 3439onDataResubmitted(callback: (event: {handler: DataResubmissionHandler}) => void) 3440 3441Called when the web form data is resubmitted. 3442 3443**Parameters** 3444 3445| Name | Type | Description | 3446| ------- | ---------------------------------------------------- | ---------------------- | 3447| handler | [DataResubmissionHandler](#dataresubmissionhandler9) | Handler for resubmitting web form data.| 3448 3449**Example** 3450 3451 ```ts 3452 // xxx.ets 3453 import web_webview from '@ohos.web.webview' 3454 import business_error from '@ohos.base'; 3455 @Entry 3456 @Component 3457 struct WebComponent { 3458 controller: web_webview.WebviewController = new web_webview.WebviewController() 3459 build() { 3460 Column() { 3461 // After you click Submit on the web page, you can click Refresh to trigger the function again. 3462 Button('refresh') 3463 .onClick(() => { 3464 try { 3465 this.controller.refresh(); 3466 } catch (error) { 3467 let e: business_error.BusinessError = error as business_error.BusinessError; 3468 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3469 } 3470 }) 3471 Web({ src:$rawfile('index.html'), controller: this.controller }) 3472 .onDataResubmitted((event) => { 3473 console.log('onDataResubmitted') 3474 event.handler.resend(); 3475 }) 3476 } 3477 } 3478 } 3479 ``` 3480 3481 HTML file to be loaded: 3482 ```html 3483 <!-- index.html --> 3484 <!DOCTYPE html> 3485 <html> 3486 <head> 3487 <meta charset="utf-8"> 3488 </head> 3489 <body> 3490 <form action="http://httpbin.org/post" method="post"> 3491 <input type="text" name="username"> 3492 <input type="submit" name="Submit"> 3493 </form> 3494 </body> 3495 </html> 3496 ``` 3497 3498### onPageVisible<sup>9+</sup> 3499 3500onPageVisible(callback: (event: {url: string}) => void) 3501 3502Called when the old page is not displayed and the new page is about to be visible. 3503 3504**Parameters** 3505 3506| Name| Type| Description | 3507| ------ | -------- | ------------------------------------------------- | 3508| url | string | URL of the new page that is able to be visible when the old page is not displayed.| 3509 3510**Example** 3511 3512 ```ts 3513 // xxx.ets 3514 import web_webview from '@ohos.web.webview' 3515 @Entry 3516 @Component 3517 struct WebComponent { 3518 controller: web_webview.WebviewController = new web_webview.WebviewController() 3519 build() { 3520 Column() { 3521 Web({ src:'www.example.com', controller: this.controller }) 3522 .onPageVisible((event) => { 3523 console.log('onPageVisible url:' + event.url) 3524 }) 3525 } 3526 } 3527 } 3528 ``` 3529 3530### onInterceptKeyEvent<sup>9+</sup> 3531 3532onInterceptKeyEvent(callback: (event: KeyEvent) => boolean) 3533 3534Called when the key event is intercepted and before it is consumed by the webview. 3535 3536**Parameters** 3537 3538| Name| Type | Description | 3539| ------ | ------------------------------------------------------- | -------------------- | 3540| event | [KeyEvent](ts-universal-events-key.md#keyevent) | Key event that is triggered.| 3541 3542**Return value** 3543 3544| Type | Description | 3545| ------- | ------------------------------------------------------------ | 3546| boolean | Whether to continue to transfer the key event to the webview kernel.| 3547 3548**Example** 3549 3550 ```ts 3551 // xxx.ets 3552 import web_webview from '@ohos.web.webview' 3553 @Entry 3554 @Component 3555 struct WebComponent { 3556 controller: web_webview.WebviewController = new web_webview.WebviewController() 3557 build() { 3558 Column() { 3559 Web({ src:'www.example.com', controller: this.controller }) 3560 .onInterceptKeyEvent((event) => { 3561 if (event.keyCode == 2017 || event.keyCode == 2018) { 3562 console.info(`onInterceptKeyEvent get event.keyCode ${event.keyCode}`) 3563 return true; 3564 } 3565 return false; 3566 }) 3567 } 3568 } 3569 } 3570 ``` 3571 3572### onTouchIconUrlReceived<sup>9+</sup> 3573 3574onTouchIconUrlReceived(callback: (event: {url: string, precomposed: boolean}) => void) 3575 3576Called when an apple-touch-icon URL is received. 3577 3578**Parameters** 3579 3580| Name | Type| Description | 3581| ----------- | -------- | ---------------------------------- | 3582| url | string | Received apple-touch-icon URL.| 3583| precomposed | boolean | Whether the apple-touch-icon is precomposed.| 3584 3585**Example** 3586 3587 ```ts 3588 // xxx.ets 3589 import web_webview from '@ohos.web.webview' 3590 @Entry 3591 @Component 3592 struct WebComponent { 3593 controller: web_webview.WebviewController = new web_webview.WebviewController() 3594 build() { 3595 Column() { 3596 Web({ src:'www.baidu.com', controller: this.controller }) 3597 .onTouchIconUrlReceived((event) => { 3598 console.log('onTouchIconUrlReceived:' + JSON.stringify(event)) 3599 }) 3600 } 3601 } 3602 } 3603 ``` 3604 3605### onFaviconReceived<sup>9+</sup> 3606 3607onFaviconReceived(callback: (event: {favicon: image.PixelMap}) => void) 3608 3609Called when this web page receives a new favicon. 3610 3611**Parameters** 3612 3613| Name | Type | Description | 3614| ------- | ---------------------------------------------- | ----------------------------------- | 3615| favicon | [PixelMap](../apis/js-apis-image.md#pixelmap7) | **PixelMap** object of the received favicon.| 3616 3617**Example** 3618 3619 ```ts 3620 // xxx.ets 3621 import web_webview from '@ohos.web.webview' 3622 import image from "@ohos.multimedia.image" 3623 @Entry 3624 @Component 3625 struct WebComponent { 3626 controller: web_webview.WebviewController = new web_webview.WebviewController() 3627 @State icon: image.PixelMap | undefined = undefined; 3628 build() { 3629 Column() { 3630 Web({ src:'www.example.com', controller: this.controller }) 3631 .onFaviconReceived((event) => { 3632 console.log('onFaviconReceived'); 3633 this.icon = event.favicon; 3634 }) 3635 } 3636 } 3637 } 3638 ``` 3639 3640### onAudioStateChanged<sup>10+</sup> 3641 3642onAudioStateChanged(callback: (event: { playing: boolean }) => void) 3643 3644Called when the audio playback status changes on the web page. 3645 3646**Parameters** 3647 3648| Name | Type | Description | 3649| ------- | ---------------------------------------------- | ----------------------------------- | 3650| playing | boolean | Audio playback status on the current page. The value **true** means that audio is being played, and **false** means the opposite.| 3651 3652**Example** 3653 3654 ```ts 3655 // xxx.ets 3656 import web_webview from '@ohos.web.webview' 3657 @Entry 3658 @Component 3659 struct WebComponent { 3660 controller: web_webview.WebviewController = new web_webview.WebviewController() 3661 @State playing: boolean = false 3662 build() { 3663 Column() { 3664 Web({ src:'www.example.com', controller: this.controller }) 3665 .onAudioStateChanged(event => { 3666 this.playing = event.playing 3667 console.debug('onAudioStateChanged playing: ' + this.playing) 3668 }) 3669 } 3670 } 3671 } 3672 ``` 3673 3674### onFirstContentfulPaint<sup>10+</sup> 3675 3676onFirstContentfulPaint(callback: (event?: { navigationStartTick: number, firstContentfulPaintMs: number }) => void) 3677 3678Called when the web page content is first rendered. 3679 3680**Parameters** 3681 3682| Name | Type | Description | 3683| -----------------------| -------- | ----------------------------------- | 3684| navigationStartTick | number | Navigation start time, in microseconds.| 3685| firstContentfulPaintMs | number | Time between navigation and when the content is first rendered, in milliseconds.| 3686 3687**Example** 3688 3689 ```ts 3690 // xxx.ets 3691 import web_webview from '@ohos.web.webview' 3692 @Entry 3693 @Component 3694 struct WebComponent { 3695 controller: web_webview.WebviewController = new web_webview.WebviewController() 3696 3697 build() { 3698 Column() { 3699 Web({ src:'www.example.com', controller: this.controller }) 3700 .onFirstContentfulPaint(event => { 3701 if (event) { 3702 console.log("onFirstContentfulPaint:" + "[navigationStartTick]:" + 3703 event.navigationStartTick + ", [firstContentfulPaintMs]:" + 3704 event.firstContentfulPaintMs) 3705 } 3706 }) 3707 } 3708 } 3709 } 3710 ``` 3711 3712### onLoadIntercept<sup>10+</sup> 3713 3714onLoadIntercept(callback: (event: { data: WebResourceRequest }) => boolean) 3715 3716Called 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. 3717 3718**Parameters** 3719 3720| Name | Type | Description | 3721| ------- | ---------------------------------------- | --------- | 3722| data | [WebResourceRequest](#webresourcerequest) | Information about the URL request.| 3723 3724**Return value** 3725 3726| Type | Description | 3727| ------- | ------------------------ | 3728| boolean | Returns **true** if the access is blocked; returns **false** otherwise.| 3729 3730**Example** 3731 3732 ```ts 3733 // xxx.ets 3734 import web_webview from '@ohos.web.webview' 3735 3736 @Entry 3737 @Component 3738 struct WebComponent { 3739 controller: web_webview.WebviewController = new web_webview.WebviewController() 3740 3741 build() { 3742 Column() { 3743 Web({ src: 'www.example.com', controller: this.controller }) 3744 .onLoadIntercept((event) => { 3745 console.log('url:' + event.data.getRequestUrl()) 3746 console.log('isMainFrame:' + event.data.isMainFrame()) 3747 console.log('isRedirect:' + event.data.isRedirect()) 3748 console.log('isRequestGesture:' + event.data.isRequestGesture()) 3749 return true 3750 }) 3751 } 3752 } 3753 } 3754 ``` 3755 3756### onRequestSelected 3757 3758onRequestSelected(callback: () => void) 3759 3760Called when the **\<Web>** component obtains the focus. 3761 3762**Example** 3763 3764 ```ts 3765 // xxx.ets 3766 import web_webview from '@ohos.web.webview' 3767 3768 @Entry 3769 @Component 3770 struct WebComponent { 3771 controller: web_webview.WebviewController = new web_webview.WebviewController() 3772 3773 build() { 3774 Column() { 3775 Web({ src: 'www.example.com', controller: this.controller }) 3776 .onRequestSelected(() => { 3777 console.log('onRequestSelected') 3778 }) 3779 } 3780 } 3781 } 3782 ``` 3783### onScreenCaptureRequest<sup>10+</sup> 3784 3785onScreenCaptureRequest(callback: (event?: { handler: ScreenCaptureHandler }) => void) 3786 3787Called when a screen capture request is received. 3788 3789**Parameters** 3790 3791| Name | Type | Description | 3792| ------- | ---------------------------------------- | -------------- | 3793| handler | [ScreenCaptureHandler](#screencapturehandler10) | User operation.| 3794 3795**Example** 3796 3797 ```ts 3798 // xxx.ets 3799 import web_webview from '@ohos.web.webview' 3800 3801 @Entry 3802 @Component 3803 struct WebComponent { 3804 controller: web_webview.WebviewController = new web_webview.WebviewController() 3805 build() { 3806 Column() { 3807 Web({ src: 'www.example.com', controller: this.controller }) 3808 .onScreenCaptureRequest((event) => { 3809 if (event) { 3810 AlertDialog.show({ 3811 title: 'title: ' + event.handler.getOrigin(), 3812 message: 'text', 3813 primaryButton: { 3814 value: 'deny', 3815 action: () => { 3816 event.handler.deny() 3817 } 3818 }, 3819 secondaryButton: { 3820 value: 'onConfirm', 3821 action: () => { 3822 event.handler.grant({ captureMode: WebCaptureMode.HOME_SCREEN }) 3823 } 3824 }, 3825 cancel: () => { 3826 event.handler.deny() 3827 } 3828 }) 3829 } 3830 }) 3831 } 3832 } 3833 } 3834 ``` 3835 3836### onOverScroll<sup>10+</sup> 3837 3838onOverScroll(callback: (event: {xOffset: number, yOffset: number}) => void) 3839 3840Called to indicate the offset by which the web page overscrolls. 3841 3842**Parameters** 3843 3844| Name | Type | Description | 3845| ------- | ------ | ------------ | 3846| xOffset | number | Horizontal overscroll offset based on the leftmost edge of the web page.| 3847| yOffset | number | Vertical overscroll offset based on the top edge of the web page.| 3848 3849**Example** 3850 3851 ```ts 3852 // xxx.ets 3853 import web_webview from '@ohos.web.webview' 3854 3855 @Entry 3856 @Component 3857 struct WebComponent { 3858 controller: web_webview.WebviewController = new web_webview.WebviewController() 3859 build() { 3860 Column() { 3861 Web({ src: 'www.example.com', controller: this.controller }) 3862 .onOverScroll((event) => { 3863 console.info("x = " + event.xOffset) 3864 console.info("y = " + event.yOffset) 3865 }) 3866 } 3867 } 3868 } 3869 ``` 3870 3871### onControllerAttached<sup>10+</sup> 3872 3873onControllerAttached(callback: () => void) 3874 3875Called when the controller is successfully bound to the **\<Web>** component. The controller must be WebviewController. 3876As the web page is not yet loaded when this callback is called, APIs for operating the web page cannot be used in the callback, for example, [zoomIn](../apis/js-apis-webview.md#zoomin) and [zoomOut](../apis/js-apis-webview.md#zoomout). Other APIs, such as [loadUrl](../apis/js-apis-webview.md#loadurl) and [getWebId](../apis/js-apis-webview.md#getwebid), which do not involve web page operations, can be used properly. 3877 3878**Example** 3879 3880The following example uses **loadUrl** in the callback to load the web page. 3881 ```ts 3882 // xxx.ets 3883 import web_webview from '@ohos.web.webview' 3884 3885 @Entry 3886 @Component 3887 struct WebComponent { 3888 controller: web_webview.WebviewController = new web_webview.WebviewController() 3889 3890 build() { 3891 Column() { 3892 Web({ src: '', controller: this.controller }) 3893 .onControllerAttached(() => { 3894 this.controller.loadUrl($rawfile("index.html")); 3895 }) 3896 } 3897 } 3898 } 3899 ``` 3900The following example uses **getWebId** in the callback 3901 ```ts 3902 // xxx.ets 3903 import web_webview from '@ohos.web.webview' 3904 import { BusinessError } from '@ohos.base'; 3905 3906 @Entry 3907 @Component 3908 struct WebComponent { 3909 controller: web_webview.WebviewController = new web_webview.WebviewController() 3910 3911 build() { 3912 Column() { 3913 Web({ src: $rawfile("index.html"), controller: this.controller }) 3914 .onControllerAttached(() => { 3915 try { 3916 let id = this.controller.getWebId(); 3917 console.log("id: " + id); 3918 } catch (error) { 3919 let code = (error as BusinessError).code; 3920 let message = (error as BusinessError).message; 3921 console.error(`ErrorCode: ${code}, Message: ${message}`); 3922 } 3923 }) 3924 } 3925 } 3926 } 3927 ``` 3928 HTML file to be loaded: 3929 ```html 3930 <!-- index.html --> 3931 <!DOCTYPE html> 3932 <html> 3933 <body> 3934 <p>Hello World</p> 3935 </body> 3936 </html> 3937 ``` 3938## ConsoleMessage 3939 3940Implements the **ConsoleMessage** object. For the sample code, see [onConsole](#onconsole). 3941 3942### getLineNumber 3943 3944getLineNumber(): number 3945 3946Obtains the number of rows in this console message. 3947 3948**Return value** 3949 3950| Type | Description | 3951| ------ | -------------------- | 3952| number | Number of rows in the console message.| 3953 3954### getMessage 3955 3956getMessage(): string 3957 3958Obtains the log information of this console message. 3959 3960**Return value** 3961 3962| Type | Description | 3963| ------ | ---------------------- | 3964| string | Log information of the console message.| 3965 3966### getMessageLevel 3967 3968getMessageLevel(): MessageLevel 3969 3970Obtains the level of this console message. 3971 3972**Return value** 3973 3974| Type | Description | 3975| --------------------------------- | ---------------------- | 3976| [MessageLevel](#messagelevel)| Level of the console message.| 3977 3978### getSourceId 3979 3980getSourceId(): string 3981 3982Obtains the path and name of the web page source file. 3983 3984**Return value** 3985 3986| Type | Description | 3987| ------ | ------------- | 3988| string | Path and name of the web page source file.| 3989 3990## JsResult 3991 3992Implements 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). 3993 3994### handleCancel 3995 3996handleCancel(): void 3997 3998Notifies the **\<Web>** component of the user's cancel operation in the dialog box. 3999 4000### handleConfirm 4001 4002handleConfirm(): void 4003 4004Notifies the **\<Web>** component of the user's confirm operation in the dialog box. 4005 4006### handlePromptConfirm<sup>9+</sup> 4007 4008handlePromptConfirm(result: string): void 4009 4010Notifies the **\<Web>** component of the user's confirm operation in the dialog box as well as the dialog box content. 4011 4012**Parameters** 4013 4014| Name | Type | Mandatory | Default Value | Description | 4015| ------ | ------ | ---- | ---- | ----------- | 4016| result | string | Yes | - | User input in the dialog box.| 4017 4018## FullScreenExitHandler<sup>9+</sup> 4019 4020Implements a **FullScreenExitHandler** object for listening for exiting full screen mode. For the sample code, see [onFullScreenEnter](#onfullscreenenter9). 4021 4022### constructor<sup>9+</sup> 4023 4024constructor() 4025 4026### exitFullScreen<sup>9+</sup> 4027 4028exitFullScreen(): void 4029 4030Exits full screen mode. 4031 4032## ControllerHandler<sup>9+</sup> 4033 4034Implements a **WebviewController** object for new **\<Web>** components. For the sample code, see [onWindowNew](#onwindownew9). 4035 4036### setWebController<sup>9+</sup> 4037 4038setWebController(controller: WebviewController): void 4039 4040Sets a **WebviewController** object. If opening a new window is not needed, set the parameter to **null**. 4041 4042**Parameters** 4043 4044| Name | Type | Mandatory | Default Value | Description | 4045| ---------- | ------------- | ---- | ---- | ------------------------- | 4046| controller | [WebviewController](../apis/js-apis-webview.md#webviewcontroller) | Yes | - | **WebviewController** object of the **\<Web>** component. If opening a new window is not needed, set it to **null**.| 4047 4048## WebResourceError 4049 4050Implements the **WebResourceError** object. For the sample code, see [onErrorReceive](#onerrorreceive). 4051 4052### getErrorCode 4053 4054getErrorCode(): number 4055 4056Obtains the error code for resource loading. 4057 4058**Return value** 4059 4060| Type | Description | 4061| ------ | ----------- | 4062| number | Error code for resource loading.| 4063 4064### getErrorInfo 4065 4066getErrorInfo(): string 4067 4068Obtains error information about resource loading. 4069 4070**Return value** 4071 4072| Type | Description | 4073| ------ | ------------ | 4074| string | Error information about resource loading.| 4075 4076## WebResourceRequest 4077 4078Implements the **WebResourceRequest** object. For the sample code, see [onErrorReceive](#onerrorreceive). 4079 4080### getRequestHeader 4081 4082getRequestHeader(): Array\<Header\> 4083 4084Obtains the information about the resource request header. 4085 4086**Return value** 4087 4088| Type | Description | 4089| -------------------------- | ---------- | 4090| Array\<[Header](#header)\> | Information about the resource request header.| 4091 4092### getRequestUrl 4093 4094getRequestUrl(): string 4095 4096Obtains the URL of the resource request. 4097 4098**Return value** 4099 4100| Type | Description | 4101| ------ | ------------- | 4102| string | URL of the resource request.| 4103 4104### isMainFrame 4105 4106isMainFrame(): boolean 4107 4108Checks whether the resource request is in the main frame. 4109 4110**Return value** 4111 4112| Type | Description | 4113| ------- | ---------------- | 4114| boolean | Whether the resource request is in the main frame.| 4115 4116### isRedirect 4117 4118isRedirect(): boolean 4119 4120Checks whether the resource request is redirected by the server. 4121 4122**Return value** 4123 4124| Type | Description | 4125| ------- | ---------------- | 4126| boolean | Whether the resource request is redirected by the server.| 4127 4128### isRequestGesture 4129 4130isRequestGesture(): boolean 4131 4132Checks whether the resource request is associated with a gesture (for example, a tap). 4133 4134**Return value** 4135 4136| Type | Description | 4137| ------- | -------------------- | 4138| boolean | Whether the resource request is associated with a gesture (for example, a tap).| 4139 4140### getRequestMethod<sup>9+</sup> 4141 4142getRequestMethod(): string 4143 4144Obtains the request method. 4145 4146**Return value** 4147 4148| Type | Description | 4149| ------- | -------------------- | 4150| string | Request method.| 4151 4152## Header 4153 4154Describes the request/response header returned by the **\<Web>** component. 4155 4156| Name | Type | Description | 4157| ----------- | ------ | ------------- | 4158| headerKey | string | Key of the request/response header. | 4159| headerValue | string | Value of the request/response header.| 4160 4161## WebResourceResponse 4162 4163Implements the **WebResourceResponse** object. For the sample code, see [onHttpErrorReceive](#onhttperrorreceive). 4164 4165### getReasonMessage 4166 4167getReasonMessage(): string 4168 4169Obtains the status code description of the resource response. 4170 4171**Return value** 4172 4173| Type | Description | 4174| ------ | ------------- | 4175| string | Status code description of the resource response.| 4176 4177### getResponseCode 4178 4179getResponseCode(): number 4180 4181Obtains the status code of the resource response. 4182 4183**Return value** 4184 4185| Type | Description | 4186| ------ | ----------- | 4187| number | Status code of the resource response.| 4188 4189### getResponseData 4190 4191getResponseData(): string 4192 4193Obtains the data in the resource response. 4194 4195**Return value** 4196 4197| Type | Description | 4198| ------ | --------- | 4199| string | Data in the resource response.| 4200 4201### getResponseEncoding 4202 4203getResponseEncoding(): string 4204 4205Obtains the encoding string of the resource response. 4206 4207**Return value** 4208 4209| Type | Description | 4210| ------ | ---------- | 4211| string | Encoding string of the resource response.| 4212 4213### getResponseHeader 4214 4215getResponseHeader() : Array\<Header\> 4216 4217Obtains the resource response header. 4218 4219**Return value** 4220 4221| Type | Description | 4222| -------------------------- | -------- | 4223| Array\<[Header](#header)\> | Resource response header.| 4224 4225### getResponseMimeType 4226 4227getResponseMimeType(): string 4228 4229Obtains the MIME type of the resource response. 4230 4231**Return value** 4232 4233| Type | Description | 4234| ------ | ------------------ | 4235| string | MIME type of the resource response.| 4236 4237### setResponseData<sup>9+</sup> 4238 4239setResponseData(data: string | number \| Resource) 4240 4241Sets the data in the resource response. 4242 4243**Parameters** 4244 4245| Name| Type | Mandatory| Default Value| Description | 4246| ------ | ---------------- | ---- | ------ | ------------------------------------------------------------ | 4247| data | string \| number \| [Resource](ts-types.md)<sup>10+</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.| 4248 4249### setResponseEncoding<sup>9+</sup> 4250 4251setResponseEncoding(encoding: string) 4252 4253Sets the encoding string of the resource response. 4254 4255**Parameters** 4256 4257| Name | Type | Mandatory | Default Value | Description | 4258| -------- | ------ | ---- | ---- | ------------ | 4259| encoding | string | Yes | - | Encoding string to set.| 4260 4261### setResponseMimeType<sup>9+</sup> 4262 4263setResponseMimeType(mimeType: string) 4264 4265Sets the MIME type of the resource response. 4266 4267**Parameters** 4268 4269| Name | Type | Mandatory | Default Value | Description | 4270| -------- | ------ | ---- | ---- | -------------------- | 4271| mimeType | string | Yes | - | MIME type to set.| 4272 4273### setReasonMessage<sup>9+</sup> 4274 4275setReasonMessage(reason: string) 4276 4277Sets the status code description of the resource response. 4278 4279**Parameters** 4280 4281| Name | Type | Mandatory | Default Value | Description | 4282| ------ | ------ | ---- | ---- | --------------- | 4283| reason | string | Yes | - | Status code description to set.| 4284 4285### setResponseHeader<sup>9+</sup> 4286 4287setResponseHeader(header: Array\<Header\>) 4288 4289Sets the resource response header. 4290 4291**Parameters** 4292 4293| Name | Type | Mandatory | Default Value | Description | 4294| ------ | -------------------------- | ---- | ---- | ---------- | 4295| header | Array\<[Header](#header)\> | Yes | - | Resource response header to set.| 4296 4297### setResponseCode<sup>9+</sup> 4298 4299setResponseCode(code: number) 4300 4301Sets the status code of the resource response. 4302 4303**Parameters** 4304 4305| Name | Type | Mandatory | Default Value | Description | 4306| ---- | ------ | ---- | ---- | ------------- | 4307| code | number | Yes | - | Status code to set.| 4308 4309### setResponseIsReady<sup>9+</sup> 4310 4311setResponseIsReady(IsReady: boolean) 4312 4313Sets whether the resource response data is ready. 4314 4315**Parameters** 4316 4317| Name | Type| Mandatory| Default Value| Description | 4318| ------- | -------- | ---- | ------ | -------------------------- | 4319| IsReady | boolean | Yes | true | Whether the resource response data is ready.| 4320 4321## FileSelectorResult<sup>9+</sup> 4322 4323Notifies the **\<Web>** component of the file selection result. For the sample code, see [onShowFileSelector](#onshowfileselector9). 4324 4325### handleFileList<sup>9+</sup> 4326 4327handleFileList(fileList: Array\<string\>): void 4328 4329Instructs the **\<Web>** component to select a file. 4330 4331**Parameters** 4332 4333| Name | Type | Mandatory | Default Value | Description | 4334| -------- | --------------- | ---- | ---- | ------------ | 4335| fileList | Array\<string\> | Yes | - | List of files to operate.| 4336 4337## FileSelectorParam<sup>9+</sup> 4338 4339Implements the **FileSelectorParam** object. For the sample code, see [onShowFileSelector](#onshowfileselector9). 4340 4341### getTitle<sup>9+</sup> 4342 4343getTitle(): string 4344 4345Obtains the title of this file selector. 4346 4347**Return value** 4348 4349| Type | Description | 4350| ------ | -------- | 4351| string | Title of the file selector.| 4352 4353### getMode<sup>9+</sup> 4354 4355getMode(): FileSelectorMode 4356 4357Obtains the mode of the file selector. 4358 4359**Return value** 4360 4361| Type | Description | 4362| ---------------------------------------- | ----------- | 4363| [FileSelectorMode](#fileselectormode)| Mode of the file selector.| 4364 4365### getAcceptType<sup>9+</sup> 4366 4367getAcceptType(): Array\<string\> 4368 4369Obtains the file filtering type. 4370 4371**Return value** 4372 4373| Type | Description | 4374| --------------- | --------- | 4375| Array\<string\> | File filtering type.| 4376 4377### isCapture<sup>9+</sup> 4378 4379isCapture(): boolean 4380 4381Checks whether multimedia capabilities are invoked. 4382 4383**Return value** 4384 4385| Type | Description | 4386| ------- | ------------ | 4387| boolean | Whether multimedia capabilities are invoked.| 4388 4389## HttpAuthHandler<sup>9+</sup> 4390 4391Implements the **HttpAuthHandler** object. For the sample code, see [onHttpAuthRequest](#onhttpauthrequest9). 4392 4393### cancel<sup>9+</sup> 4394 4395cancel(): void 4396 4397Cancels HTTP authentication as requested by the user. 4398 4399### confirm<sup>9+</sup> 4400 4401confirm(userName: string, pwd: string): boolean 4402 4403Performs HTTP authentication with the user name and password provided by the user. 4404 4405**Parameters** 4406 4407| Name | Type | Mandatory | Default Value | Description | 4408| -------- | ------ | ---- | ---- | ---------- | 4409| userName | string | Yes | - | HTTP authentication user name.| 4410| password | string | Yes | - | HTTP authentication password. | 4411 4412**Return value** 4413 4414| Type | Description | 4415| ------- | --------------------- | 4416| boolean | Returns **true** if the authentication is successful; returns **false** otherwise.| 4417 4418### isHttpAuthInfoSaved<sup>9+</sup> 4419 4420isHttpAuthInfoSaved(): boolean 4421 4422Uses the account name and password cached on the server for authentication. 4423 4424**Return value** 4425 4426| Type | Description | 4427| ------- | ------------------------- | 4428| boolean | Returns **true** if the authentication is successful; returns **false** otherwise.| 4429 4430## SslErrorHandler<sup>9+</sup> 4431 4432Implements an **SslErrorHandler** object. For the sample code, see [onSslErrorEventReceive Event](#onsslerroreventreceive9). 4433 4434### handleCancel<sup>9+</sup> 4435 4436handleCancel(): void 4437 4438Cancels this request. 4439 4440### handleConfirm<sup>9+</sup> 4441 4442handleConfirm(): void 4443 4444Continues using the SSL certificate. 4445 4446## ClientAuthenticationHandler<sup>9+</sup> 4447 4448Implements a **ClientAuthenticationHandler** object returned by the **\<Web>** component. For the sample code, see [onClientAuthenticationRequest](#onclientauthenticationrequest9). 4449 4450### confirm<sup>9+</sup> 4451 4452confirm(priKeyFile : string, certChainFile : string): void 4453 4454Uses the specified private key and client certificate chain. 4455 4456**Parameters** 4457 4458| Name | Type | Mandatory | Description | 4459| ------------- | ------ | ---- | ------------------ | 4460| priKeyFile | string | Yes | File that stores the private key, which is a directory including the file name. | 4461| certChainFile | string | Yes | File that stores the certificate chain, which is a directory including the file name.| 4462 4463### confirm<sup>10+</sup> 4464 4465confirm(authUri : string): void 4466 4467**Required permissions**: ohos.permission.ACCESS_CERT_MANAGER 4468 4469Instructs the **\<Web>** component to use the specified credentials (obtained from the certificate management module). 4470 4471**Parameters** 4472 4473| Name | Type | Mandatory | Description | 4474| ------- | ------ | ---- | ------------- | 4475| authUri | string | Yes | Key value of the credentials. | 4476 4477### cancel<sup>9+</sup> 4478 4479cancel(): void 4480 4481Cancels 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. 4482 4483### ignore<sup>9+</sup> 4484 4485ignore(): void 4486 4487Ignores this request. 4488 4489## PermissionRequest<sup>9+</sup> 4490 4491Implements the **PermissionRequest** object. For the sample code, see [onPermissionRequest](#onpermissionrequest9). 4492 4493### deny<sup>9+</sup> 4494 4495deny(): void 4496 4497Denies the permission requested by the web page. 4498 4499### getOrigin<sup>9+</sup> 4500 4501getOrigin(): string 4502 4503Obtains the origin of this web page. 4504 4505**Return value** 4506 4507| Type | Description | 4508| ------ | ------------ | 4509| string | Origin of the web page that requests the permission.| 4510 4511### getAccessibleResource<sup>9+</sup> 4512 4513getAccessibleResource(): Array\<string\> 4514 4515Obtains the list of accessible resources requested for the web page. For details about the resource types, see [ProtectedResourceType](#protectedresourcetype9). 4516 4517**Return value** 4518 4519| Type | Description | 4520| --------------- | ------------- | 4521| Array\<string\> | List of accessible resources requested by the web page.| 4522 4523### grant<sup>9+</sup> 4524 4525grant(resources: Array\<string\>): void 4526 4527Grants the permission for resources requested by the web page. 4528 4529**Parameters** 4530 4531| Name | Type | Mandatory | Default Value | Description | 4532| --------- | --------------- | ---- | ---- | ------------- | 4533| resources | Array\<string\> | Yes | - | List of resources that can be requested by the web page with the permission to grant.| 4534 4535## ScreenCaptureHandler<sup>10+</sup> 4536 4537Implements the **ScreenCaptureHandler** object for accepting or rejecting a screen capture request. For the sample code, see [onScreenCaptureRequest Event](#onscreencapturerequest10). 4538 4539### deny<sup>10+</sup> 4540 4541deny(): void 4542 4543Rejects this screen capture request. 4544 4545### getOrigin<sup>10+</sup> 4546 4547getOrigin(): string 4548 4549Obtains the origin of this web page. 4550 4551**Return value** 4552 4553| Type | Description | 4554| ------ | ------------ | 4555| string | Origin of the web page that requests the permission.| 4556 4557### grant<sup>10+</sup> 4558 4559grant(config: ScreenCaptureConfig): void 4560 4561**Required permissions**: ohos.permission.MICROPHONE, ohos.permission.CAPTURE_SCREEN 4562 4563Grants the screen capture permission. 4564 4565**Parameters** 4566 4567| Name | Type | Mandatory | Default Value | Description | 4568| --------- | --------------- | ---- | ---- | ------------- | 4569| config | [ScreenCaptureConfig](#screencaptureconfig10) | Yes | - | Screen capture configuration.| 4570 4571## ContextMenuSourceType<sup>9+</sup> 4572 4573| Name | Value| Description | 4574| --------- | -- |------------ | 4575| None | 0 | Other event sources.| 4576| Mouse | 1 | Mouse event. | 4577| LongPress | 2 | Long press event. | 4578 4579## ContextMenuMediaType<sup>9+</sup> 4580 4581| Name | Value| Description | 4582| ----- | -- | ------------- | 4583| None | 0 | Non-special media or other media types.| 4584| Image | 1 | Image. | 4585 4586## ContextMenuInputFieldType<sup>9+</sup> 4587 4588| Name | Value| Description | 4589| --------- | -- | --------------------------- | 4590| None | 0 | Non-input field. | 4591| PlainText | 1 | Plain text field, such as the text, search, or email field.| 4592| Password | 2 | Password field. | 4593| Number | 3 | Numeric field. | 4594| Telephone | 4 | Phone number field. | 4595| Other | 5 | Field of any other type. | 4596 4597## ContextMenuEditStateFlags<sup>9+</sup> 4598 4599| Name | Value| Description | 4600| -------------- | -- | -------- | 4601| NONE | 0 | Editing is not allowed.| 4602| CAN_CUT | 1 | The cut operation is allowed.| 4603| CAN_COPY | 2 | The copy operation is allowed.| 4604| CAN_PASTE | 4 | The paste operation is allowed.| 4605| CAN_SELECT_ALL | 8 | The select all operation is allowed.| 4606 4607## WebContextMenuParam<sup>9+</sup> 4608 4609Implements 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). 4610 4611### x<sup>9+</sup> 4612 4613x(): number 4614 4615Obtains the X coordinate of the context menu. 4616 4617**Return value** 4618 4619| Type | Description | 4620| ------ | ------------------ | 4621| number | If the display is normal, a non-negative integer is returned. Otherwise, **-1** is returned.| 4622 4623### y<sup>9+</sup> 4624 4625y(): number 4626 4627Obtains the Y coordinate of the context menu. 4628 4629**Return value** 4630 4631| Type | Description | 4632| ------ | ------------------ | 4633| number | If the display is normal, a non-negative integer is returned. Otherwise, **-1** is returned.| 4634 4635### getLinkUrl<sup>9+</sup> 4636 4637getLinkUrl(): string 4638 4639Obtains the URL of the destination link. 4640 4641**Return value** 4642 4643| Type | Description | 4644| ------ | ------------------------- | 4645| string | If it is a link that is being long pressed, the URL that has passed the security check is returned.| 4646 4647### getUnfilteredLinkUrl<sup>9+</sup> 4648 4649getUnfilteredLinkUrl(): string 4650 4651Obtains the URL of the destination link. 4652 4653**Return value** 4654 4655| Type | Description | 4656| ------ | --------------------- | 4657| string | If it is a link that is being long pressed, the original URL is returned.| 4658 4659### getSourceUrl<sup>9+</sup> 4660 4661getSourceUrl(): string 4662 4663Obtain the source URL. 4664 4665**Return value** 4666 4667| Type | Description | 4668| ------ | ------------------------ | 4669| string | If the selected element has the **src** attribute, the URL in the **src** is returned.| 4670 4671### existsImageContents<sup>9+</sup> 4672 4673existsImageContents(): boolean 4674 4675Checks whether image content exists. 4676 4677**Return value** 4678 4679| Type | Description | 4680| ------- | ------------------------- | 4681| boolean | The value **true** means that there is image content in the element being long pressed, and **false** means the opposite.| 4682 4683### getMediaType<sup>9+</sup> 4684 4685getMediaType(): ContextMenuMediaType 4686 4687Obtains the media type of this web page element. 4688 4689**Return value** 4690 4691| Type | Description | 4692| ---------------------------------------- | ----------- | 4693| [ContextMenuMediaType](#contextmenumediatype9) | Media type of the web page element.| 4694 4695### getSelectionText<sup>9+</sup> 4696 4697getSelectionText(): string 4698 4699Obtains the selected text. 4700 4701**Return value** 4702 4703| Type | Description | 4704| ------- | ------------------------- | 4705| string | Selected text for the context menu. If no text is selected, null is returned.| 4706 4707### getSourceType<sup>9+</sup> 4708 4709getSourceType(): ContextMenuSourceType 4710 4711Obtains the event source of the context menu. 4712 4713**Return value** 4714 4715| Type | Description | 4716| ---------------------------------------- | ----------- | 4717| [ContextMenuSourceType](#contextmenusourcetype9) | Event source of the context menu.| 4718 4719### getInputFieldType<sup>9+</sup> 4720 4721getInputFieldType(): ContextMenuInputFieldType 4722 4723Obtains the input field type of this web page element. 4724 4725**Return value** 4726 4727| Type | Description | 4728| ---------------------------------------- | ----------- | 4729| [ContextMenuInputFieldType](#contextmenuinputfieldtype9) | Input field type.| 4730 4731### isEditable<sup>9+</sup> 4732 4733isEditable(): boolean 4734 4735Checks whether this web page element is editable. 4736 4737**Return value** 4738 4739| Type | Description | 4740| ------- | ------------------------- | 4741| boolean | Returns **true** if the web page element is editable; returns **false** otherwise.| 4742 4743### getEditStateFlags<sup>9+</sup> 4744 4745getEditStateFlags(): number 4746 4747Obtains the edit state flag of this web page element. 4748 4749**Return value** 4750 4751| Type | Description | 4752| ------- | ------------------------- | 4753| number | Edit state flag of the web page element. For details, see [ContextMenuEditStateFlags](#contextmenueditstateflags9).| 4754 4755## WebContextMenuResult<sup>9+</sup> 4756 4757Implements a **WebContextMenuResult** object. For the sample code, see [onContextMenuShow](#oncontextmenushow9). 4758 4759### closeContextMenu<sup>9+</sup> 4760 4761closeContextMenu(): void 4762 4763Closes this context menu. This API must be called when no operations in **WebContextMenuResult** are performed. 4764 4765### copyImage<sup>9+</sup> 4766 4767copyImage(): void 4768 4769Copies the image specified in **WebContextMenuParam**. 4770 4771### copy<sup>9+</sup> 4772 4773copy(): void 4774 4775Performs the copy operation related to this context menu. 4776 4777### paste<sup>9+</sup> 4778 4779paste(): void 4780 4781Performs the paste operation related to this context menu. 4782 4783### cut<sup>9+</sup> 4784 4785cut(): void 4786 4787Performs the cut operation related to this context menu. 4788 4789### selectAll<sup>9+</sup> 4790 4791selectAll(): void 4792 4793Performs the select all operation related to this context menu. 4794 4795## JsGeolocation 4796 4797Implements the **PermissionRequest** object. For the sample code, see [onGeolocationShow Event](#ongeolocationshow). 4798 4799### invoke 4800 4801invoke(origin: string, allow: boolean, retain: boolean): void 4802 4803Sets the geolocation permission status of a web page. 4804 4805**Parameters** 4806 4807| Name | Type | Mandatory | Default Value | Description | 4808| ------ | ------- | ---- | ---- | ---------------------------------------- | 4809| origin | string | Yes | - | Index of the origin. | 4810| allow | boolean | Yes | - | Geolocation permission status. | 4811| 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>](../apis/js-apis-webview.md#geolocationpermissions).| 4812 4813## MessageLevel 4814 4815| Name | Value| Description | 4816| ----- | -- | ---- | 4817| Debug | 0 | Debug level.| 4818| Error | 1 | Error level.| 4819| Info | 2 | Information level.| 4820| Log | 3 | Log level.| 4821| Warn | 4 | Warning level.| 4822 4823## RenderExitReason<sup>9+</sup> 4824 4825Enumerates the reasons why the rendering process exits. 4826 4827| Name | Value| Description | 4828| -------------------------- | -- | ----------------- | 4829| ProcessAbnormalTermination | 0 | The rendering process exits abnormally. | 4830| ProcessWasKilled | 1 | The rendering process receives a SIGKILL message or is manually terminated.| 4831| ProcessCrashed | 2 | The rendering process crashes due to segmentation or other errors. | 4832| ProcessOom | 3 | The program memory is running low. | 4833| ProcessExitUnknown | 4 | Other reason. | 4834 4835## MixedMode 4836 4837| Name | Value| Description | 4838| ---------- | -- | ---------------------------------- | 4839| All | 0 | HTTP and HTTPS hybrid content can be loaded. This means that all insecure content can be loaded.| 4840| Compatible | 1 | HTTP and HTTPS hybrid content can be loaded in compatibility mode. This means that some insecure content may be loaded. | 4841| None | 2 | HTTP and HTTPS hybrid content cannot be loaded. | 4842 4843## CacheMode<sup>9+</sup> 4844 4845| Name | Value| Description | 4846| ------- | -- | ------------------------------------ | 4847| Default | 0 | The cache that has not expired is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet.| 4848| None | 1 | The cache is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet. | 4849| Online | 2 | The cache is not used to load the resources. All resources are obtained from the Internet. | 4850| Only | 3 | The cache alone is used to load the resources. | 4851 4852## FileSelectorMode<sup>9+</sup> 4853 4854| Name | Value| Description | 4855| -------------------- | -- | ---------- | 4856| FileOpenMode | 0 | Open and upload a file. | 4857| FileOpenMultipleMode | 1 | Open and upload multiple files. | 4858| FileOpenFolderMode | 2 | Open and upload a folder.| 4859| FileSaveMode | 3 | Save a file. | 4860 4861 ## HitTestType 4862 4863| Name | Value| Description | 4864| ------------- | -- | ------------------------ | 4865| EditText | 0 | Editable area. | 4866| Email | 1 | Email address. | 4867| HttpAnchor | 2 | Hyperlink whose **src** is **http**. | 4868| HttpAnchorImg | 3 | Image with a hyperlink, where **src** is **http**.| 4869| Img | 4 | HTML::img tag. | 4870| Map | 5 | Geographical address. | 4871| Phone | 6 | Phone number. | 4872| Unknown | 7 | Unknown content. | 4873 4874## SslError<sup>9+</sup> 4875 4876Enumerates the error codes returned by **onSslErrorEventReceive** API. 4877 4878| Name | Value| Description | 4879| ------------ | -- | ----------- | 4880| Invalid | 0 | Minor error. | 4881| HostMismatch | 1 | The host name does not match. | 4882| DateInvalid | 2 | The certificate has an invalid date. | 4883| Untrusted | 3 | The certificate issuer is not trusted.| 4884 4885## ProtectedResourceType<sup>9+</sup> 4886 4887| Name | Value| Description | Remarks | 4888| --------------------------- | --------------- | ------------- | -------------------------- | 4889| MidiSysex | TYPE_MIDI_SYSEX | MIDI SYSEX resource.| Currently, only permission events can be reported. MIDI devices are not yet supported.| 4890| VIDEO_CAPTURE<sup>10+</sup> | TYPE_VIDEO_CAPTURE | Video capture resource, such as a camera. | | 4891| AUDIO_CAPTURE<sup>10+</sup> | TYPE_AUDIO_CAPTURE | Audio capture resource, such as a microphone.| | 4892 4893## WebDarkMode<sup>9+</sup> 4894 4895| Name | Value| Description | 4896| ---- | -- | ------------ | 4897| Off | 0 | The web dark mode is disabled. | 4898| On | 1 | The web dark mode is enabled. | 4899| Auto | 2 | The web dark mode setting follows the system settings.| 4900 4901## WebCaptureMode<sup>10+</sup> 4902 4903| Name | Value| Description | 4904| ----------- | -- | ------- | 4905| HOME_SCREEN | 0 | Capture of the home screen.| 4906 4907## WebMediaOptions<sup>10+</sup> 4908 4909Describes the web-based media playback policy. 4910 4911| Name | Type | Readable| Writable| Mandatory| Description | 4912| -------------- | --------- | ---- | ---- | --- | ---------------------------- | 4913| resumeInterval | number | Yes | Yes | 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.| 4914| audioExclusive | boolean | Yes | Yes | No | Whether the audio of multiple **\<Web>** instances in an application is exclusive. | 4915 4916## ScreenCaptureConfig<sup>10+</sup> 4917 4918Provides the web screen capture configuration. 4919 4920| Name | Type | Readable| Writable| Mandatory| Description | 4921| -------------- | --------- | ---- | ---- | --- | ---------------------------- | 4922| captureMode | [WebCaptureMode](#webcapturemode10) | Yes | Yes | Yes | Web screen capture mode.| 4923 4924## DataResubmissionHandler<sup>9+</sup> 4925 4926Implements the **DataResubmissionHandler** object for resubmitting or canceling the web form data. 4927 4928### resend<sup>9+</sup> 4929 4930resend(): void 4931 4932Resends the web form data. 4933 4934**Example** 4935 4936 ```ts 4937 // xxx.ets 4938 import web_webview from '@ohos.web.webview' 4939 @Entry 4940 @Component 4941 struct WebComponent { 4942 controller: web_webview.WebviewController = new web_webview.WebviewController() 4943 build() { 4944 Column() { 4945 Web({ src:'www.example.com', controller: this.controller }) 4946 .onDataResubmitted((event) => { 4947 console.log('onDataResubmitted') 4948 event.handler.resend(); 4949 }) 4950 } 4951 } 4952 } 4953 ``` 4954 4955### cancel<sup>9+</sup> 4956 4957cancel(): void 4958 4959Cancels the resending of web form data. 4960 4961**Example** 4962 4963 ```ts 4964 // xxx.ets 4965 import web_webview from '@ohos.web.webview' 4966 @Entry 4967 @Component 4968 struct WebComponent { 4969 controller: web_webview.WebviewController = new web_webview.WebviewController() 4970 build() { 4971 Column() { 4972 Web({ src:'www.example.com', controller: this.controller }) 4973 .onDataResubmitted((event) => { 4974 console.log('onDataResubmitted') 4975 event.handler.cancel(); 4976 }) 4977 } 4978 } 4979 } 4980 ``` 4981 4982 ## WebController 4983 4984Implements 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. 4985 4986This API is deprecated since API version 9. You are advised to use [WebviewController<sup>9+</sup>](../apis/js-apis-webview.md#webviewcontroller) instead. 4987 4988### Creating an Object 4989 4990```ts 4991let webController: WebController = new WebController() 4992``` 4993 4994### getCookieManager<sup>(deprecated)</sup> 4995 4996getCookieManager(): WebCookie 4997 4998Obtains the cookie management object of the **\<Web>** component. 4999 5000This API is deprecated since API version 9. You are advised to use [getCookie](../apis/js-apis-webview.md#getcookie) instead. 5001 5002**Return value** 5003 5004| Type | Description | 5005| --------- | ---------------------------------------- | 5006| WebCookie | Cookie management object. For details, see [WebCookie](#webcookiedeprecated).| 5007 5008**Example** 5009 5010 ```ts 5011 // xxx.ets 5012 @Entry 5013 @Component 5014 struct WebComponent { 5015 controller: WebController = new WebController() 5016 5017 build() { 5018 Column() { 5019 Button('getCookieManager') 5020 .onClick(() => { 5021 let cookieManager = this.controller.getCookieManager() 5022 }) 5023 Web({ src: 'www.example.com', controller: this.controller }) 5024 } 5025 } 5026 } 5027 ``` 5028 5029### requestFocus<sup>(deprecated)</sup> 5030 5031requestFocus() 5032 5033Requests focus for this web page. 5034 5035This API is deprecated since API version 9. You are advised to use [requestFocus<sup>9+</sup>](../apis/js-apis-webview.md#requestfocus) instead. 5036 5037**Example** 5038 5039 ```ts 5040 // xxx.ets 5041 @Entry 5042 @Component 5043 struct WebComponent { 5044 controller: WebController = new WebController() 5045 5046 build() { 5047 Column() { 5048 Button('requestFocus') 5049 .onClick(() => { 5050 this.controller.requestFocus() 5051 }) 5052 Web({ src: 'www.example.com', controller: this.controller }) 5053 } 5054 } 5055 } 5056 ``` 5057 5058### accessBackward<sup>(deprecated)</sup> 5059 5060accessBackward(): boolean 5061 5062Checks whether going to the previous page can be performed on the current page. 5063 5064This API is deprecated since API version 9. You are advised to use [accessBackward<sup>9+</sup>](../apis/js-apis-webview.md#accessbackward) instead. 5065 5066**Return value** 5067 5068| Type | Description | 5069| ------- | --------------------- | 5070| boolean | Returns **true** if going to the previous page can be performed on the current page; returns **false** otherwise.| 5071 5072**Example** 5073 5074 ```ts 5075 // xxx.ets 5076 @Entry 5077 @Component 5078 struct WebComponent { 5079 controller: WebController = new WebController() 5080 5081 build() { 5082 Column() { 5083 Button('accessBackward') 5084 .onClick(() => { 5085 let result = this.controller.accessBackward() 5086 console.log('result:' + result) 5087 }) 5088 Web({ src: 'www.example.com', controller: this.controller }) 5089 } 5090 } 5091 } 5092 ``` 5093 5094### accessForward<sup>(deprecated)</sup> 5095 5096accessForward(): boolean 5097 5098Checks whether going to the next page can be performed on the current page. 5099 5100This API is deprecated since API version 9. You are advised to use [accessForward<sup>9+</sup>](../apis/js-apis-webview.md#accessforward) instead. 5101 5102**Return value** 5103 5104| Type | Description | 5105| ------- | --------------------- | 5106| boolean | Returns **true** if going to the next page can be performed on the current page; returns **false** otherwise.| 5107 5108**Example** 5109 5110 ```ts 5111 // xxx.ets 5112 @Entry 5113 @Component 5114 struct WebComponent { 5115 controller: WebController = new WebController() 5116 5117 build() { 5118 Column() { 5119 Button('accessForward') 5120 .onClick(() => { 5121 let result = this.controller.accessForward() 5122 console.log('result:' + result) 5123 }) 5124 Web({ src: 'www.example.com', controller: this.controller }) 5125 } 5126 } 5127 } 5128 ``` 5129 5130### accessStep<sup>(deprecated)</sup> 5131 5132accessStep(step: number): boolean 5133 5134Performs a specific number of steps forward or backward from the current page. 5135 5136This API is deprecated since API version 9. You are advised to use [accessStep<sup>9+</sup>](../apis/js-apis-webview.md#accessstep) instead. 5137 5138**Parameters** 5139 5140| Name | Type | Mandatory | Default Value | Description | 5141| ---- | ------ | ---- | ---- | --------------------- | 5142| step | number | Yes | - | Number of the steps to take. A positive number means to go forward, and a negative number means to go backward.| 5143 5144**Return value** 5145 5146| Type | Description | 5147| ------- | --------- | 5148| boolean | Whether going forward or backward from the current page is successful.| 5149 5150**Example** 5151 5152 ```ts 5153 // xxx.ets 5154 @Entry 5155 @Component 5156 struct WebComponent { 5157 controller: WebController = new WebController() 5158 @State steps: number = 2 5159 5160 build() { 5161 Column() { 5162 Button('accessStep') 5163 .onClick(() => { 5164 let result = this.controller.accessStep(this.steps) 5165 console.log('result:' + result) 5166 }) 5167 Web({ src: 'www.example.com', controller: this.controller }) 5168 } 5169 } 5170 } 5171 ``` 5172 5173### backward<sup>(deprecated)</sup> 5174 5175backward(): void 5176 5177Goes to the previous page based on the history stack. This API is generally used together with **accessBackward**. 5178 5179This API is deprecated since API version 9. You are advised to use [backward<sup>9+</sup>](../apis/js-apis-webview.md#backward) instead. 5180 5181**Example** 5182 5183 ```ts 5184 // xxx.ets 5185 @Entry 5186 @Component 5187 struct WebComponent { 5188 controller: WebController = new WebController() 5189 5190 build() { 5191 Column() { 5192 Button('backward') 5193 .onClick(() => { 5194 this.controller.backward() 5195 }) 5196 Web({ src: 'www.example.com', controller: this.controller }) 5197 } 5198 } 5199 } 5200 ``` 5201 5202### forward<sup>(deprecated)</sup> 5203 5204forward(): void 5205 5206Goes to the next page based on the history stack. This API is generally used together with **accessForward**. 5207 5208This API is deprecated since API version 9. You are advised to use [forward<sup>9+</sup>](../apis/js-apis-webview.md#forward) instead. 5209 5210**Example** 5211 5212 ```ts 5213 // xxx.ets 5214 @Entry 5215 @Component 5216 struct WebComponent { 5217 controller: WebController = new WebController() 5218 5219 build() { 5220 Column() { 5221 Button('forward') 5222 .onClick(() => { 5223 this.controller.forward() 5224 }) 5225 Web({ src: 'www.example.com', controller: this.controller }) 5226 } 5227 } 5228 } 5229 ``` 5230 5231### deleteJavaScriptRegister<sup>(deprecated)</sup> 5232 5233deleteJavaScriptRegister(name: string) 5234 5235Deletes 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. 5236 5237This API is deprecated since API version 9. You are advised to use [deleteJavaScriptRegister<sup>9+</sup>](../apis/js-apis-webview.md#deletejavascriptregister) instead. 5238 5239**Parameters** 5240 5241| Name | Type | Mandatory | Default Value | Description | 5242| ---- | ------ | ---- | ---- | ---------------------------------------- | 5243| 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.| 5244 5245**Example** 5246 5247 ```ts 5248 // xxx.ets 5249 @Entry 5250 @Component 5251 struct WebComponent { 5252 controller: WebController = new WebController() 5253 @State name: string = 'Object' 5254 5255 build() { 5256 Column() { 5257 Button('deleteJavaScriptRegister') 5258 .onClick(() => { 5259 this.controller.deleteJavaScriptRegister(this.name) 5260 }) 5261 Web({ src: 'www.example.com', controller: this.controller }) 5262 } 5263 } 5264 } 5265 ``` 5266 5267### getHitTest<sup>(deprecated)</sup> 5268 5269getHitTest(): HitTestType 5270 5271Obtains the element type of the area being clicked. 5272 5273This API is deprecated since API version 9. You are advised to use [getHitTest<sup>9+</sup>](../apis/js-apis-webview.md#gethittest) instead. 5274 5275**Return value** 5276 5277| Type | Description | 5278| ------------------------------- | ----------- | 5279| [HitTestType](#hittesttype)| Element type of the area being clicked.| 5280 5281**Example** 5282 5283 ```ts 5284 // xxx.ets 5285 @Entry 5286 @Component 5287 struct WebComponent { 5288 controller: WebController = new WebController() 5289 5290 build() { 5291 Column() { 5292 Button('getHitTest') 5293 .onClick(() => { 5294 let hitType = this.controller.getHitTest() 5295 console.log("hitType: " + hitType) 5296 }) 5297 Web({ src: 'www.example.com', controller: this.controller }) 5298 } 5299 } 5300 } 5301 ``` 5302 5303### loadData<sup>(deprecated)</sup> 5304 5305loadData(options: { data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string }) 5306 5307Loads data. If **baseUrl** is empty, the specified character string will be loaded using the data protocol. 5308 5309If **baseUrl** is set to a data URL, the encoded string will be loaded by the **\<Web>** component using the data protocol. 5310 5311If **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**. 5312 5313This API is deprecated since API version 9. You are advised to use [loadData<sup>9+</sup>](../apis/js-apis-webview.md#loaddata) instead. 5314 5315**Parameters** 5316 5317| Name | Type | Mandatory | Default Value | Description | 5318| ---------- | ------ | ---- | ---- | ---------------------------------------- | 5319| data | string | Yes | - | Character string obtained after being Base64 or URL encoded. | 5320| mimeType | string | Yes | - | Media type (MIME). | 5321| encoding | string | Yes | - | Encoding type, which can be Base64 or URL. | 5322| baseUrl | string | No | - | URL (HTTP/HTTPS/data compliant), which is assigned by the **\<Web>** component to **window.origin**.| 5323| 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.| 5324 5325**Example** 5326 5327 ```ts 5328 // xxx.ets 5329 @Entry 5330 @Component 5331 struct WebComponent { 5332 controller: WebController = new WebController() 5333 5334 build() { 5335 Column() { 5336 Button('loadData') 5337 .onClick(() => { 5338 this.controller.loadData({ 5339 data: "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>", 5340 mimeType: "text/html", 5341 encoding: "UTF-8" 5342 }) 5343 }) 5344 Web({ src: 'www.example.com', controller: this.controller }) 5345 } 5346 } 5347 } 5348 ``` 5349 5350### loadUrl<sup>(deprecated)</sup> 5351 5352loadUrl(options: { url: string | Resource, headers?: Array\<Header\> }) 5353 5354Loads a URL using the specified HTTP header. 5355 5356The object injected through **loadUrl** is valid only in the current document. It will be invalid on a new page navigated to through **loadUrl**. 5357 5358The object injected through **registerJavaScriptProxy** is still valid on a new page redirected through **loadUrl**. 5359 5360This API is deprecated since API version 9. You are advised to use [loadUrl<sup>9+</sup>](../apis/js-apis-webview.md#loadurl) instead. 5361 5362**Parameters** 5363 5364| Name | Type | Mandatory | Default Value | Description | 5365| ------- | -------------------------- | ---- | ---- | -------------- | 5366| url | string \| Resource | Yes | - | URL to load. | 5367| headers | Array\<[Header](#header)\> | No | [] | Additional HTTP request header of the URL.| 5368 5369**Example** 5370 5371 ```ts 5372 // xxx.ets 5373 @Entry 5374 @Component 5375 struct WebComponent { 5376 controller: WebController = new WebController() 5377 5378 build() { 5379 Column() { 5380 Button('loadUrl') 5381 .onClick(() => { 5382 this.controller.loadUrl({ url: 'www.example.com' }) 5383 }) 5384 Web({ src: 'www.example.com', controller: this.controller }) 5385 } 5386 } 5387 } 5388 ``` 5389 5390### onActive<sup>(deprecated)</sup> 5391 5392onActive(): void 5393 5394Called when the **\<Web>** component enters the active state. 5395 5396This API is deprecated since API version 9. You are advised to use [onActive<sup>9+</sup>](../apis/js-apis-webview.md#onactive) instead. 5397 5398**Example** 5399 5400 ```ts 5401 // xxx.ets 5402 @Entry 5403 @Component 5404 struct WebComponent { 5405 controller: WebController = new WebController() 5406 5407 build() { 5408 Column() { 5409 Button('onActive') 5410 .onClick(() => { 5411 this.controller.onActive() 5412 }) 5413 Web({ src: 'www.example.com', controller: this.controller }) 5414 } 5415 } 5416 } 5417 ``` 5418 5419### onInactive<sup>(deprecated)</sup> 5420 5421onInactive(): void 5422 5423Called when the **\<Web>** component enters the inactive state. 5424 5425This API is deprecated since API version 9. You are advised to use [onInactive<sup>9+</sup>](../apis/js-apis-webview.md#oninactive) instead. 5426 5427**Example** 5428 5429 ```ts 5430 // xxx.ets 5431 @Entry 5432 @Component 5433 struct WebComponent { 5434 controller: WebController = new WebController() 5435 5436 build() { 5437 Column() { 5438 Button('onInactive') 5439 .onClick(() => { 5440 this.controller.onInactive() 5441 }) 5442 Web({ src: 'www.example.com', controller: this.controller }) 5443 } 5444 } 5445 } 5446 ``` 5447 5448### zoom<sup>(deprecated)</sup> 5449zoom(factor: number): void 5450 5451Sets a zoom factor for the current web page. 5452 5453This API is deprecated since API version 9. You are advised to use [zoom<sup>9+</sup>](../apis/js-apis-webview.md#zoom) instead. 5454 5455**Parameters** 5456 5457| Name | Type | Mandatory | Description | 5458| ------ | ------ | ---- | ------------------------------ | 5459| factor | number | Yes | Zoom factor to set. A positive value indicates zoom-in, and a negative value indicates zoom-out.| 5460 5461**Example** 5462 5463 ```ts 5464 // xxx.ets 5465 @Entry 5466 @Component 5467 struct WebComponent { 5468 controller: WebController = new WebController() 5469 @State factor: number = 1 5470 5471 build() { 5472 Column() { 5473 Button('zoom') 5474 .onClick(() => { 5475 this.controller.zoom(this.factor) 5476 }) 5477 Web({ src: 'www.example.com', controller: this.controller }) 5478 } 5479 } 5480 } 5481 ``` 5482 5483### refresh<sup>(deprecated)</sup> 5484 5485refresh() 5486 5487Called when the **\<Web>** component refreshes the web page. 5488 5489This API is deprecated since API version 9. You are advised to use [refresh<sup>9+</sup>](../apis/js-apis-webview.md#refresh) instead. 5490 5491**Example** 5492 5493 ```ts 5494 // xxx.ets 5495 @Entry 5496 @Component 5497 struct WebComponent { 5498 controller: WebController = new WebController() 5499 5500 build() { 5501 Column() { 5502 Button('refresh') 5503 .onClick(() => { 5504 this.controller.refresh() 5505 }) 5506 Web({ src: 'www.example.com', controller: this.controller }) 5507 } 5508 } 5509 } 5510 ``` 5511 5512### registerJavaScriptProxy<sup>(deprecated)</sup> 5513 5514registerJavaScriptProxy(options: { object: object, name: string, methodList: Array\<string\> }) 5515 5516Registers 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. 5517 5518This API is deprecated since API version 9. You are advised to use [registerJavaScriptProxy<sup>9+</sup>](../apis/js-apis-webview.md#registerjavascriptproxy) instead. 5519 5520**Parameters** 5521 5522| Name | Type | Mandatory | Default Value | Description | 5523| ---------- | --------------- | ---- | ---- | ---------------------------------------- | 5524| object | object | Yes | - | Application-side JavaScript object to be registered. Methods can be declared, but attributes cannot. The parameters and return value can only be of the string, number, or Boolean type.| 5525| 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.| 5526| methodList | Array\<string\> | Yes | - | Methods of the JavaScript object to be registered at the application side. | 5527 5528**Example** 5529 5530 ```ts 5531 // xxx.ets 5532 class TestObj { 5533 constructor() { 5534 } 5535 5536 test(): string { 5537 return "ArkUI Web Component" 5538 } 5539 5540 toString(): void { 5541 console.log('Web Component toString') 5542 } 5543 } 5544 5545 @Entry 5546 @Component 5547 struct Index { 5548 controller: WebController = new WebController() 5549 testObj = new TestObj(); 5550 build() { 5551 Column() { 5552 Row() { 5553 Button('Register JavaScript To Window').onClick(() => { 5554 this.controller.registerJavaScriptProxy({ 5555 object: this.testObj, 5556 name: "objName", 5557 methodList: ["test", "toString"], 5558 }) 5559 }) 5560 } 5561 Web({ src: $rawfile('index.html'), controller: this.controller }) 5562 .javaScriptAccess(true) 5563 } 5564 } 5565 } 5566 ``` 5567 5568 HTML file to be loaded: 5569 ```html 5570 <!-- index.html --> 5571 <!DOCTYPE html> 5572 <html> 5573 <meta charset="utf-8"> 5574 <body> 5575 Hello world! 5576 </body> 5577 <script type="text/javascript"> 5578 function htmlTest() { 5579 str = objName.test("test function") 5580 console.log('objName.test result:'+ str) 5581 } 5582 </script> 5583 </html> 5584 5585 ``` 5586 5587### runJavaScript<sup>(deprecated)</sup> 5588 5589runJavaScript(options: { script: string, callback?: (result: string) => void }) 5590 5591Executes 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**. 5592 5593This API is deprecated since API version 9. You are advised to use [runJavaScript<sup>9+</sup>](../apis/js-apis-webview.md#runjavascript) instead. 5594 5595**Parameters** 5596 5597| Name | Type | Mandatory | Default Value | Description | 5598| -------- | ------------------------ | ---- | ---- | ---------------------------------------- | 5599| script | string | Yes | - | JavaScript script. | 5600| 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.| 5601 5602**Example** 5603 5604 ```ts 5605 // xxx.ets 5606 @Entry 5607 @Component 5608 struct WebComponent { 5609 controller: WebController = new WebController() 5610 @State webResult: string = '' 5611 build() { 5612 Column() { 5613 Text(this.webResult).fontSize(20) 5614 Web({ src: $rawfile('index.html'), controller: this.controller }) 5615 .javaScriptAccess(true) 5616 .onPageEnd((event) => { 5617 this.controller.runJavaScript({ 5618 script: 'test()', 5619 callback: (result: string)=> { 5620 this.webResult = result 5621 console.info(`The test() return value is: ${result}`) 5622 }}) 5623 if (event) { 5624 console.info('url: ', event.url) 5625 } 5626 }) 5627 } 5628 } 5629 } 5630 ``` 5631 HTML file to be loaded: 5632 ```html 5633 <!-- index.html --> 5634 <!DOCTYPE html> 5635 <html> 5636 <meta charset="utf-8"> 5637 <body> 5638 Hello world! 5639 </body> 5640 <script type="text/javascript"> 5641 function test() { 5642 console.log('Ark WebComponent') 5643 return "This value is from index.html" 5644 } 5645 </script> 5646 </html> 5647 ``` 5648 5649### stop<sup>(deprecated)</sup> 5650 5651stop() 5652 5653Stops page loading. 5654 5655This API is deprecated since API version 9. You are advised to use [stop<sup>9+</sup>](../apis/js-apis-webview.md#stop) instead. 5656 5657**Example** 5658 5659 ```ts 5660 // xxx.ets 5661 @Entry 5662 @Component 5663 struct WebComponent { 5664 controller: WebController = new WebController() 5665 5666 build() { 5667 Column() { 5668 Button('stop') 5669 .onClick(() => { 5670 this.controller.stop() 5671 }) 5672 Web({ src: 'www.example.com', controller: this.controller }) 5673 } 5674 } 5675 } 5676 ``` 5677 5678### clearHistory<sup>(deprecated)</sup> 5679 5680clearHistory(): void 5681 5682Clears the browsing history. 5683 5684This API is deprecated since API version 9. You are advised to use [clearHistory<sup>9+</sup>](../apis/js-apis-webview.md#clearhistory) instead. 5685 5686**Example** 5687 5688 ```ts 5689 // xxx.ets 5690 @Entry 5691 @Component 5692 struct WebComponent { 5693 controller: WebController = new WebController() 5694 5695 build() { 5696 Column() { 5697 Button('clearHistory') 5698 .onClick(() => { 5699 this.controller.clearHistory() 5700 }) 5701 Web({ src: 'www.example.com', controller: this.controller }) 5702 } 5703 } 5704 } 5705 ``` 5706 5707## WebCookie<sup>(deprecated)</sup> 5708 5709Manages 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. 5710 5711### setCookie<sup>(deprecated)</sup> 5712 5713setCookie() 5714 5715Sets the cookie. This API returns the result synchronously. Returns **true** if the operation is successful; returns **false** otherwise. 5716 5717This API is deprecated since API version 9. You are advised to use [setCookie<sup>9+</sup>](../apis/js-apis-webview.md#setcookie) instead. 5718 5719### saveCookie<sup>(deprecated)</sup> 5720 5721saveCookie(): boolean 5722 5723Saves the cookies in the memory to the drive. This API returns the result synchronously. 5724 5725This API is deprecated since API version 9. You are advised to use [saveCookieAsync<sup>9+</sup>](../apis/js-apis-webview.md#savecookieasync) instead. 5726