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