1 2 3# @ohos.web.webview (Webview) 4 5The **Webview** module provides APIs for web control. It can be used with the **[<Web\>](../arkui-ts/ts-basic-components-web.md)** component, which can be used to display web pages. 6 7> **NOTE** 8> 9> - The initial APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. 10> 11> - You can preview how the APIs of this module work on a real device. The preview is not yet available in the DevEco Studio Previewer. 12 13## Required Permissions 14 15**ohos.permission.INTERNET**, required for accessing online web pages. For details about how to apply for a permission, see [Declaring Permissions](../../security/accesstoken-guidelines.md). 16 17## Modules to Import 18 19```ts 20import web_webview from '@ohos.web.webview'; 21``` 22 23## once 24 25once(type: string, callback: Callback\<void\>): void 26 27Registers a one-time callback for web events of the specified type. 28 29**System capability**: SystemCapability.Web.Webview.Core 30 31**Parameters** 32 33| Name | Type | Mandatory| Description | 34| ------- | ---------------- | ---- | -------------------- | 35| type | string | Yes | Web event type. The value can be **"webInited"**, indicating completion of web initialization. | 36| headers | Callback\<void\> | Yes | Callback to register.| 37 38**Example** 39 40```ts 41// xxx.ets 42import web_webview from '@ohos.web.webview' 43 44web_webview.once("webInited", () => { 45 console.log("setCookie") 46 web_webview.WebCookieManager.setCookie("https://www.example.com", "a=b") 47}) 48 49@Entry 50@Component 51struct WebComponent { 52 controller: web_webview.WebviewController = new web_webview.WebviewController(); 53 54 build() { 55 Column() { 56 Web({ src: 'www.example.com', controller: this.controller }) 57 } 58 } 59} 60``` 61 62## WebMessagePort 63 64Implements a **WebMessagePort** object to send and receive messages. 65 66### close 67 68close(): void 69 70Closes this message port. 71 72**System capability**: SystemCapability.Web.Webview.Core 73 74**Example** 75 76```ts 77// xxx.ets 78import web_webview from '@ohos.web.webview' 79 80@Entry 81@Component 82struct WebComponent { 83 controller: web_webview.WebviewController = new web_webview.WebviewController(); 84 msgPort: web_webview.WebMessagePort[] = null; 85 86 build() { 87 Column() { 88 Button('close') 89 .onClick(() => { 90 if (this.msgPort && this.msgPort[1]) { 91 this.msgPort[1].close(); 92 } else { 93 console.error("msgPort is null, Please initialize first"); 94 } 95 }) 96 Web({ src: 'www.example.com', controller: this.controller }) 97 } 98 } 99} 100``` 101 102### postMessageEvent 103 104postMessageEvent(message: WebMessage): void 105 106Sends a message. For the complete sample code, see [postMessage](#postmessage). 107 108**System capability**: SystemCapability.Web.Webview.Core 109 110**Parameters** 111 112| Name | Type | Mandatory| Description | 113| ------- | ------ | ---- | :------------- | 114| message | [WebMessage](#webmessage) | Yes | Message to send.| 115 116**Error codes** 117 118For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 119 120| ID| Error Message | 121| -------- | ------------------------------------- | 122| 17100010 | Can not post message using this port. | 123 124**Example** 125 126```ts 127// xxx.ets 128import web_webview from '@ohos.web.webview' 129 130@Entry 131@Component 132struct WebComponent { 133 controller: web_webview.WebviewController = new web_webview.WebviewController(); 134 ports: web_webview.WebMessagePort[]; 135 136 build() { 137 Column() { 138 Button('postMessageEvent') 139 .onClick(() => { 140 try { 141 this.ports = this.controller.createWebMessagePorts(); 142 this.controller.postMessage('__init_port__', [this.ports[0]], '*'); 143 this.ports[1].postMessageEvent("post message from ets to html5"); 144 } catch (error) { 145 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 146 } 147 }) 148 Web({ src: 'www.example.com', controller: this.controller }) 149 } 150 } 151} 152``` 153 154### onMessageEvent 155 156onMessageEvent(callback: (result: WebMessage) => void): void 157 158Registers a callback to receive messages from the HTML5 side. For the complete sample code, see [postMessage](#postmessage). 159 160**System capability**: SystemCapability.Web.Webview.Core 161 162**Parameters** 163 164| Name | Type | Mandatory| Description | 165| -------- | -------- | ---- | :------------------- | 166| result | [WebMessage](#webmessage) | Yes | Message received.| 167 168**Error codes** 169 170For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 171 172| ID| Error Message | 173| -------- | ----------------------------------------------- | 174| 17100006 | Can not register message event using this port. | 175 176**Example** 177 178```ts 179// xxx.ets 180import web_webview from '@ohos.web.webview' 181 182@Entry 183@Component 184struct WebComponent { 185 controller: web_webview.WebviewController = new web_webview.WebviewController(); 186 ports: web_webview.WebMessagePort[]; 187 188 build() { 189 Column() { 190 Button('onMessageEvent') 191 .onClick(() => { 192 try { 193 this.ports = this.controller.createWebMessagePorts(); 194 this.ports[1].onMessageEvent((msg) => { 195 if (typeof(msg) == "string") { 196 console.log("received string message from html5, string is:" + msg); 197 } else if (typeof(msg) == "object") { 198 if (msg instanceof ArrayBuffer) { 199 console.log("received arraybuffer from html5, length is:" + msg.byteLength); 200 } else { 201 console.log("not support"); 202 } 203 } else { 204 console.log("not support"); 205 } 206 }) 207 } catch (error) { 208 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 209 } 210 }) 211 Web({ src: 'www.example.com', controller: this.controller }) 212 } 213 } 214} 215``` 216 217## WebviewController 218 219Implements a **WebviewController** to control the behavior of the **\<Web>** component. A **WebviewController** can control only one **\<Web>** component, and the APIs (except static APIs) in the **WebviewController** can be invoked only after it has been bound to the target **\<Web>** component. 220 221### initializeWebEngine 222 223static initializeWebEngine(): void 224 225Loads the dynamic link library (DLL) file of the web engine. This API can be called before the **\<Web>** component is initialized to improve the startup performance. 226 227**System capability**: SystemCapability.Web.Webview.Core 228 229**Example** 230 231The following code snippet exemplifies calling this API after the MainAbility is created. 232 233```ts 234// xxx.ts 235import UIAbility from '@ohos.app.ability.UIAbility'; 236import web_webview from '@ohos.web.webview'; 237 238export default class EntryAbility extends UIAbility { 239 onCreate(want, launchParam) { 240 console.log("EntryAbility onCreate") 241 web_webview.WebviewController.initializeWebEngine() 242 globalThis.abilityWant = want 243 console.log("EntryAbility onCreate done") 244 } 245} 246``` 247 248### Creating an Object 249 250```ts 251// xxx.ets 252import web_webview from '@ohos.web.webview'; 253 254@Entry 255@Component 256struct WebComponent { 257 controller: web_webview.WebviewController = new web_webview.WebviewController(); 258 259 build() { 260 Column() { 261 Web({ src: 'www.example.com', controller: this.controller }) 262 } 263 } 264} 265``` 266 267### setWebDebuggingAccess 268 269static setWebDebuggingAccess(webDebuggingAccess: boolean): void 270 271Sets whether to enable web debugging. 272 273**System capability**: SystemCapability.Web.Webview.Core 274 275**Parameters** 276 277| Name | Type | Mandatory | Description| 278| ------------------ | ------- | ---- | ------------- | 279| webDebuggingAccess | boolean | Yes | Whether to enable web debugging.| 280 281**Example** 282 283```ts 284// xxx.ets 285import web_webview from '@ohos.web.webview'; 286 287@Entry 288@Component 289struct WebComponent { 290 controller: web_webview.WebviewController = new web_webview.WebviewController(); 291 292 aboutToAppear():void { 293 try { 294 web_webview.WebviewController.setWebDebuggingAccess(true); 295 } catch(error) { 296 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 297 } 298 } 299 300 build() { 301 Column() { 302 Web({ src: 'www.example.com', controller: this.controller }) 303 } 304 } 305} 306``` 307 308### loadUrl 309 310loadUrl(url: string | Resource, headers?: Array\<WebHeader>): void 311 312Loads a specified URL. 313 314**System capability**: SystemCapability.Web.Webview.Core 315 316**Parameters** 317 318| Name | Type | Mandatory| Description | 319| ------- | ---------------- | ---- | :-------------------- | 320| url | string \| Resource | Yes | URL to load. | 321| headers | Array\<[WebHeader](#webheader)> | No | Additional HTTP request header of the URL.| 322 323**Error codes** 324 325For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 326 327| ID| Error Message | 328| -------- | ------------------------------------------------------------ | 329| 17100001 | Init error. The WebviewController must be associated with a Web component. | 330| 17100002 | Invalid url. | 331| 17100003 | Invalid resource path or file type. | 332 333**Example** 334 335```ts 336// xxx.ets 337import web_webview from '@ohos.web.webview' 338 339@Entry 340@Component 341struct WebComponent { 342 controller: web_webview.WebviewController = new web_webview.WebviewController(); 343 344 build() { 345 Column() { 346 Button('loadUrl') 347 .onClick(() => { 348 try { 349 // The URL to be loaded is of the string type. 350 this.controller.loadUrl('www.example.com'); 351 } catch (error) { 352 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 353 } 354 }) 355 Web({ src: 'www.example.com', controller: this.controller }) 356 } 357 } 358} 359``` 360 361```ts 362// xxx.ets 363import web_webview from '@ohos.web.webview' 364 365@Entry 366@Component 367struct WebComponent { 368 controller: web_webview.WebviewController = new web_webview.WebviewController(); 369 370 build() { 371 Column() { 372 Button('loadUrl') 373 .onClick(() => { 374 try { 375 // The headers parameter is carried. 376 this.controller.loadUrl('www.example.com', [{headerKey: "headerKey", headerValue: "headerValue"}]); 377 } catch (error) { 378 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 379 } 380 }) 381 Web({ src: 'www.example.com', controller: this.controller }) 382 } 383 } 384} 385``` 386 387There are two methods for loading local resource files: 3881. Using $rawfile 389```ts 390// xxx.ets 391import web_webview from '@ohos.web.webview' 392 393@Entry 394@Component 395struct WebComponent { 396 controller: web_webview.WebviewController = new web_webview.WebviewController(); 397 398 build() { 399 Column() { 400 Button('loadUrl') 401 .onClick(() => { 402 try { 403 // The URL to be loaded is of the Resource type. 404 this.controller.loadUrl($rawfile('xxx.html')); 405 } catch (error) { 406 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 407 } 408 }) 409 Web({ src: 'www.example.com', controller: this.controller }) 410 } 411 } 412} 413``` 414 4152. Using a sandbox path. For details, see the example of loading local resource files in the sandbox in [Web](../arkui-ts/ts-basic-components-web.md#web). 416 417```html 418<!-- xxx.html --> 419<!DOCTYPE html> 420<html> 421 <body> 422 <p>Hello World</p> 423 </body> 424</html> 425``` 426 427### loadData 428 429loadData(data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string): void 430 431Loads specified data. 432 433**System capability**: SystemCapability.Web.Webview.Core 434 435**Parameters** 436 437| Name | Type | Mandatory| Description | 438| ---------- | ------ | ---- | ------------------------------------------------------------ | 439| data | string | Yes | Character string obtained after being Base64 or URL encoded. | 440| mimeType | string | Yes | Media type (MIME). | 441| encoding | string | Yes | Encoding type, which can be Base64 or URL. | 442| baseUrl | string | No | URL (HTTP/HTTPS/data compliant), which is assigned by the **\<Web>** component to **window.origin**.| 443| historyUrl | string | No | URL used for historical records. If this parameter is not empty, historical records are managed based on this URL. This parameter is invalid when **baseUrl** is left empty.| 444 445**Error codes** 446 447For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 448 449| ID| Error Message | 450| -------- | ------------------------------------------------------------ | 451| 17100001 | Init error. The WebviewController must be associated with a Web component. | 452| 17100002 | Invalid url. | 453 454**Example** 455 456```ts 457// xxx.ets 458import web_webview from '@ohos.web.webview' 459 460@Entry 461@Component 462struct WebComponent { 463 controller: web_webview.WebviewController = new web_webview.WebviewController(); 464 465 build() { 466 Column() { 467 Button('loadData') 468 .onClick(() => { 469 try { 470 this.controller.loadData( 471 "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>", 472 "text/html", 473 "UTF-8" 474 ); 475 } catch (error) { 476 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 477 } 478 }) 479 Web({ src: 'www.example.com', controller: this.controller }) 480 } 481 } 482} 483``` 484 485Example of loading local resource: 486```ts 487// xxx.ets 488import web_webview from '@ohos.web.webview' 489 490@Entry 491@Component 492struct WebComponent { 493 controller: web_webview.WebviewController = new web_webview.WebviewController(); 494 updataContent: string = '<body><div><image src=file:///data/storage/el1/bundle/entry/resources/rawfile/xxx.png alt="image -- end" width="500" height="250"></image></div></body>' 495 496 build() { 497 Column() { 498 Button('loadData') 499 .onClick(() => { 500 try { 501 this.controller.loadData(this.updataContent, "text/html", "UTF-8", " ", " "); 502 } catch (error) { 503 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 504 } 505 }) 506 Web({ src: 'www.example.com', controller: this.controller }) 507 } 508 } 509} 510``` 511 512### accessForward 513 514accessForward(): boolean 515 516Checks whether moving to the next page can be performed on the current page. 517 518**System capability**: SystemCapability.Web.Webview.Core 519 520**Return value** 521 522| Type | Description | 523| ------- | --------------------------------- | 524| boolean | Returns **true** if moving to the next page can be performed on the current page; returns **false** otherwise.| 525 526**Error codes** 527 528For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 529 530| ID| Error Message | 531| -------- | ------------------------------------------------------------ | 532| 17100001 | Init error. The WebviewController must be associated with a Web component. | 533 534**Example** 535 536```ts 537// xxx.ets 538import web_webview from '@ohos.web.webview' 539 540@Entry 541@Component 542struct WebComponent { 543 controller: web_webview.WebviewController = new web_webview.WebviewController(); 544 545 build() { 546 Column() { 547 Button('accessForward') 548 .onClick(() => { 549 try { 550 let result = this.controller.accessForward(); 551 console.log('result:' + result); 552 } catch (error) { 553 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 554 } 555 }) 556 Web({ src: 'www.example.com', controller: this.controller }) 557 } 558 } 559} 560``` 561 562### forward 563 564forward(): void 565 566Moves to the next page based on the history stack. This API is generally used together with **accessForward**. 567 568**System capability**: SystemCapability.Web.Webview.Core 569 570**Error codes** 571 572For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 573 574| ID| Error Message | 575| -------- | ------------------------------------------------------------ | 576| 17100001 | Init error. The WebviewController must be associated with a Web component. | 577 578**Example** 579 580```ts 581// xxx.ets 582import web_webview from '@ohos.web.webview' 583 584@Entry 585@Component 586struct WebComponent { 587 controller: web_webview.WebviewController = new web_webview.WebviewController(); 588 589 build() { 590 Column() { 591 Button('forward') 592 .onClick(() => { 593 try { 594 this.controller.forward(); 595 } catch (error) { 596 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 597 } 598 }) 599 Web({ src: 'www.example.com', controller: this.controller }) 600 } 601 } 602} 603``` 604 605### accessBackward 606 607accessBackward(): boolean 608 609Checks whether moving to the previous page can be performed on the current page. 610 611**System capability**: SystemCapability.Web.Webview.Core 612 613**Return value** 614 615| Type | Description | 616| ------- | -------------------------------- | 617| boolean | Returns **true** if moving to the previous page can be performed on the current page; returns **false** otherwise.| 618 619**Error codes** 620 621For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 622 623| ID| Error Message | 624| -------- | ------------------------------------------------------------ | 625| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 626 627**Example** 628 629```ts 630// xxx.ets 631import web_webview from '@ohos.web.webview' 632 633@Entry 634@Component 635struct WebComponent { 636 controller: web_webview.WebviewController = new web_webview.WebviewController(); 637 638 build() { 639 Column() { 640 Button('accessBackward') 641 .onClick(() => { 642 try { 643 let result = this.controller.accessBackward(); 644 console.log('result:' + result); 645 } catch (error) { 646 console.error(`Errorcode: ${error.code}, Message: ${error.message}`); 647 } 648 }) 649 Web({ src: 'www.example.com', controller: this.controller }) 650 } 651 } 652} 653``` 654 655### backward 656 657backward(): void 658 659Moves to the previous page based on the history stack. This API is generally used together with **accessBackward**. 660 661**System capability**: SystemCapability.Web.Webview.Core 662 663**Error codes** 664 665For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 666 667| ID| Error Message | 668| -------- | ------------------------------------------------------------ | 669| 17100001 | Init error. The WebviewController must be associated with a Web component. | 670 671**Example** 672 673```ts 674// xxx.ets 675import web_webview from '@ohos.web.webview' 676 677@Entry 678@Component 679struct WebComponent { 680 controller: web_webview.WebviewController = new web_webview.WebviewController(); 681 682 build() { 683 Column() { 684 Button('backward') 685 .onClick(() => { 686 try { 687 this.controller.backward(); 688 } catch (error) { 689 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 690 } 691 }) 692 Web({ src: 'www.example.com', controller: this.controller }) 693 } 694 } 695} 696``` 697 698### onActive 699 700onActive(): void 701 702Invoked to instruct the **\<Web>** component to enter the foreground, active state. 703 704**System capability**: SystemCapability.Web.Webview.Core 705 706**Error codes** 707 708For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 709 710| ID| Error Message | 711| -------- | ------------------------------------------------------------ | 712| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 713 714**Example** 715 716```ts 717// xxx.ets 718import web_webview from '@ohos.web.webview' 719 720@Entry 721@Component 722struct WebComponent { 723 controller: web_webview.WebviewController = new web_webview.WebviewController(); 724 725 build() { 726 Column() { 727 Button('onActive') 728 .onClick(() => { 729 try { 730 this.controller.onActive(); 731 } catch (error) { 732 console.error(`Errorcode: ${error.code}, Message: ${error.message}`); 733 } 734 }) 735 Web({ src: 'www.example.com', controller: this.controller }) 736 } 737 } 738} 739``` 740 741### onInactive 742 743onInactive(): void 744 745Invoked to instruct the **\<Web>** component to enter the inactive state. 746 747**System capability**: SystemCapability.Web.Webview.Core 748 749**Error codes** 750 751For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 752 753| ID| Error Message | 754| -------- | ------------------------------------------------------------ | 755| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 756 757**Example** 758 759```ts 760// xxx.ets 761import web_webview from '@ohos.web.webview' 762 763@Entry 764@Component 765struct WebComponent { 766 controller: web_webview.WebviewController = new web_webview.WebviewController(); 767 768 build() { 769 Column() { 770 Button('onInactive') 771 .onClick(() => { 772 try { 773 this.controller.onInactive(); 774 } catch (error) { 775 console.error(`Errorcode: ${error.code}, Message: ${error.message}`); 776 } 777 }) 778 Web({ src: 'www.example.com', controller: this.controller }) 779 } 780 } 781} 782``` 783 784### refresh 785refresh(): void 786 787Invoked to instruct the **\<Web>** component to refresh the web page. 788 789**System capability**: SystemCapability.Web.Webview.Core 790 791**Error codes** 792 793For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 794 795| ID| Error Message | 796| -------- | ------------------------------------------------------------ | 797| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 798 799**Example** 800 801```ts 802// xxx.ets 803import web_webview from '@ohos.web.webview' 804 805@Entry 806@Component 807struct WebComponent { 808 controller: web_webview.WebviewController = new web_webview.WebviewController(); 809 810 build() { 811 Column() { 812 Button('refresh') 813 .onClick(() => { 814 try { 815 this.controller.refresh(); 816 } catch (error) { 817 console.error(`Errorcode: ${error.code}, Message: ${error.message}`); 818 } 819 }) 820 Web({ src: 'www.example.com', controller: this.controller }) 821 } 822 } 823} 824``` 825 826### accessStep 827 828accessStep(step: number): boolean 829 830Checks whether a specific number of steps forward or backward can be performed on the current page. 831 832**System capability**: SystemCapability.Web.Webview.Core 833 834**Parameters** 835 836| Name| Type| Mandatory| Description | 837| ------ | -------- | ---- | ------------------------------------------ | 838| step | number | Yes | Number of the steps to take. A positive number means to move forward, and a negative number means to move backward.| 839 840**Return value** 841 842| Type | Description | 843| ------- | ------------------ | 844| boolean | Whether moving forward or backward is performed on the current page.| 845 846**Error codes** 847 848For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 849 850| ID| Error Message | 851| -------- | ------------------------------------------------------------ | 852| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 853 854**Example** 855 856```ts 857// xxx.ets 858import web_webview from '@ohos.web.webview' 859 860@Entry 861@Component 862struct WebComponent { 863 controller: web_webview.WebviewController = new web_webview.WebviewController(); 864 @State steps: number = 2; 865 866 build() { 867 Column() { 868 Button('accessStep') 869 .onClick(() => { 870 try { 871 let result = this.controller.accessStep(this.steps); 872 console.log('result:' + result); 873 } catch (error) { 874 console.error(`Errorcode: ${error.code}, Message: ${error.message}`); 875 } 876 }) 877 Web({ src: 'www.example.com', controller: this.controller }) 878 } 879 } 880} 881``` 882 883### clearHistory 884 885clearHistory(): void 886 887Clears the browsing history. 888 889**System capability**: SystemCapability.Web.Webview.Core 890 891**Error codes** 892 893For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 894 895| ID| Error Message | 896| -------- | ------------------------------------------------------------ | 897| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 898 899**Example** 900 901```ts 902// xxx.ets 903import web_webview from '@ohos.web.webview' 904 905@Entry 906@Component 907struct WebComponent { 908 controller: web_webview.WebviewController = new web_webview.WebviewController(); 909 910 build() { 911 Column() { 912 Button('clearHistory') 913 .onClick(() => { 914 try { 915 this.controller.clearHistory(); 916 } catch (error) { 917 console.error(`Errorcode: ${error.code}, Message: ${error.message}`); 918 } 919 }) 920 Web({ src: 'www.example.com', controller: this.controller }) 921 } 922 } 923} 924``` 925 926### getHitTest 927 928getHitTest(): WebHitTestType 929 930Obtains the element type of the area being clicked. 931 932**System capability**: SystemCapability.Web.Webview.Core 933 934**Return value** 935 936| Type | Description | 937| ------------------------------------------------------------ | ---------------------- | 938| [WebHitTestType](#webhittesttype)| Element type of the area being clicked.| 939 940**Error codes** 941 942For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 943 944| ID| Error Message | 945| -------- | ------------------------------------------------------------ | 946| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 947 948**Example** 949 950```ts 951// xxx.ets 952import web_webview from '@ohos.web.webview' 953 954@Entry 955@Component 956struct WebComponent { 957 controller: web_webview.WebviewController = new web_webview.WebviewController(); 958 959 build() { 960 Column() { 961 Button('getHitTest') 962 .onClick(() => { 963 try { 964 let hitTestType = this.controller.getHitTest(); 965 console.log("hitTestType: " + hitTestType); 966 } catch (error) { 967 console.error(`Errorcode: ${error.code}, Message: ${error.message}`); 968 } 969 }) 970 Web({ src: 'www.example.com', controller: this.controller }) 971 } 972 } 973} 974``` 975 976### registerJavaScriptProxy 977 978registerJavaScriptProxy(object: object, name: string, methodList: Array\<string>): void 979 980Registers a JavaScript object with the window. APIs of this object can then be invoked in the window. After this API is called, call [refresh](#refresh) for the registration to take effect. 981 982**System capability**: SystemCapability.Web.Webview.Core 983 984**Parameters** 985 986| Name | Type | Mandatory| Description | 987| ---------- | -------------- | ---- | ------------------------------------------------------------ | 988| object | object | Yes | Application-side JavaScript object to be registered. Methods can be declared, but not attributes. The parameters and return values of the methods can only be of the string, number, or Boolean type.| 989| 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.| 990| methodList | Array\<string> | Yes | Methods of the JavaScript object to be registered at the application side. | 991 992**Error codes** 993 994For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 995 996| ID| Error Message | 997| -------- | ------------------------------------------------------------ | 998| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 999 1000**Example** 1001 1002```ts 1003// xxx.ets 1004import web_webview from '@ohos.web.webview' 1005 1006@Entry 1007@Component 1008struct Index { 1009 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1010 testObj = { 1011 test: (data) => { 1012 return "ArkUI Web Component"; 1013 }, 1014 toString: () => { 1015 console.log('Web Component toString'); 1016 } 1017 } 1018 1019 build() { 1020 Column() { 1021 Button('refresh') 1022 .onClick(() => { 1023 try { 1024 this.controller.refresh(); 1025 } catch (error) { 1026 console.error(`Errorcode: ${error.code}, Message: ${error.message}`); 1027 } 1028 }) 1029 Button('Register JavaScript To Window') 1030 .onClick(() => { 1031 try { 1032 this.controller.registerJavaScriptProxy(this.testObj, "objName", ["test", "toString"]); 1033 } catch (error) { 1034 console.error(`Errorcode: ${error.code}, Message: ${error.message}`); 1035 } 1036 }) 1037 Web({ src: $rawfile('index.html'), controller: this.controller }) 1038 .javaScriptAccess(true) 1039 } 1040 } 1041} 1042``` 1043 1044### runJavaScript 1045 1046runJavaScript(script: string, callback : AsyncCallback\<string>): void 1047 1048Executes 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**. 1049 1050**System capability**: SystemCapability.Web.Webview.Core 1051 1052**Parameters** 1053 1054| Name | Type | Mandatory| Description | 1055| -------- | -------------------- | ---- | ---------------------------- | 1056| script | string | Yes | JavaScript script. | 1057| callback | AsyncCallback\<string> | Yes | Callback used to return the result. Returns **null** if the JavaScript script fails to be executed or no value is returned.| 1058 1059**Error codes** 1060 1061For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1062 1063| ID| Error Message | 1064| -------- | ------------------------------------------------------------ | 1065| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1066 1067**Example** 1068 1069```ts 1070import web_webview from '@ohos.web.webview' 1071 1072@Entry 1073@Component 1074struct WebComponent { 1075 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1076 @State webResult: string = '' 1077 1078 build() { 1079 Column() { 1080 Text(this.webResult).fontSize(20) 1081 Web({ src: $rawfile('index.html'), controller: this.controller }) 1082 .javaScriptAccess(true) 1083 .onPageEnd(e => { 1084 try { 1085 this.controller.runJavaScript( 1086 'test()', 1087 (error, result) => { 1088 if (error) { 1089 console.info(`run JavaScript error: ` + JSON.stringify(error)) 1090 return; 1091 } 1092 if (result) { 1093 this.webResult = result 1094 console.info(`The test() return value is: ${result}`) 1095 } 1096 }); 1097 console.info('url: ', e.url); 1098 } catch (error) { 1099 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 1100 } 1101 }) 1102 } 1103 } 1104} 1105``` 1106 1107### runJavaScript 1108 1109runJavaScript(script: string): Promise\<string> 1110 1111Executes a JavaScript script. This API uses a promise to return the script execution result. **runJavaScript** can be invoked only after **loadUrl** is executed. For example, it can be invoked in **onPageEnd**. 1112 1113**System capability**: SystemCapability.Web.Webview.Core 1114 1115**Parameters** 1116 1117| Name| Type| Mandatory| Description | 1118| ------ | -------- | ---- | ---------------- | 1119| script | string | Yes | JavaScript script.| 1120 1121**Return value** 1122 1123| Type | Description | 1124| --------------- | --------------------------------------------------- | 1125| Promise\<string> | Promise used to return the result if the operation is successful and null otherwise.| 1126 1127**Error codes** 1128 1129For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1130 1131| ID| Error Message | 1132| -------- | ------------------------------------------------------------ | 1133| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1134 1135**Example** 1136 1137```ts 1138// xxx.ets 1139import web_webview from '@ohos.web.webview' 1140 1141@Entry 1142@Component 1143struct WebComponent { 1144 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1145 @State webResult: string = ''; 1146 1147 build() { 1148 Column() { 1149 Text(this.webResult).fontSize(20) 1150 Web({ src: $rawfile('index.html'), controller: this.controller }) 1151 .javaScriptAccess(true) 1152 .onPageEnd(e => { 1153 try { 1154 this.controller.runJavaScript('test()') 1155 .then(function (result) { 1156 console.log('result: ' + result); 1157 }) 1158 .catch(function (error) { 1159 console.error("error: " + error); 1160 }) 1161 console.info('url: ', e.url); 1162 } catch (error) { 1163 console.error(`Errorcode: ${error.code}, Message: ${error.message}`); 1164 } 1165 }) 1166 } 1167 } 1168} 1169``` 1170 1171### deleteJavaScriptRegister 1172 1173deleteJavaScriptRegister(name: string): void 1174 1175Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. The deletion takes effect immediately without invoking the [refresh](#refresh) API. 1176 1177**System capability**: SystemCapability.Web.Webview.Core 1178 1179**Parameters** 1180 1181| Name| Type| Mandatory| Description | 1182| ------ | -------- | ---- | ---- | 1183| 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.| 1184 1185**Error codes** 1186 1187For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1188 1189| ID| Error Message | 1190| -------- | ------------------------------------------------------------ | 1191| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1192| 17100008 | Cannot delete JavaScriptProxy. | 1193 1194**Example** 1195 1196```ts 1197// xxx.ets 1198import web_webview from '@ohos.web.webview' 1199 1200@Entry 1201@Component 1202struct WebComponent { 1203 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1204 @State name: string = 'Object'; 1205 1206 build() { 1207 Column() { 1208 Button('deleteJavaScriptRegister') 1209 .onClick(() => { 1210 try { 1211 this.controller.deleteJavaScriptRegister(this.name); 1212 } catch (error) { 1213 console.error(`Errorcode: ${error.code}, Message: ${error.message}`); 1214 } 1215 }) 1216 Web({ src: 'www.example.com', controller: this.controller }) 1217 } 1218 } 1219} 1220``` 1221 1222### zoom 1223 1224zoom(factor: number): void 1225 1226Zooms in or out of this web page. 1227 1228**System capability**: SystemCapability.Web.Webview.Core 1229 1230**Parameters** 1231 1232| Name| Type| Mandatory| Description| 1233| ------ | -------- | ---- | ------------------------------------------------------------ | 1234| factor | number | Yes | Relative zoom ratio. A positive value indicates zoom-in, and a negative value indicates zoom-out.| 1235 1236**Error codes** 1237 1238For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1239 1240| ID| Error Message | 1241| -------- | ------------------------------------------------------------ | 1242| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1243| 17100004 | Function not enable. | 1244 1245**Example** 1246 1247```ts 1248// xxx.ets 1249import web_webview from '@ohos.web.webview' 1250 1251@Entry 1252@Component 1253struct WebComponent { 1254 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1255 @State factor: number = 1; 1256 1257 build() { 1258 Column() { 1259 Button('zoom') 1260 .onClick(() => { 1261 try { 1262 this.controller.zoom(this.factor); 1263 } catch (error) { 1264 console.error(`Errorcode: ${error.code}, Message: ${error.message}`); 1265 } 1266 }) 1267 Web({ src: 'www.example.com', controller: this.controller }) 1268 } 1269 } 1270} 1271``` 1272 1273### searchAllAsync 1274 1275searchAllAsync(searchString: string): void 1276 1277Searches the web page for content that matches the keyword specified by **'searchString'** and highlights the matches on the page. This API returns the result asynchronously through [onSearchResultReceive](../arkui-ts/ts-basic-components-web.md#onsearchresultreceive9). 1278 1279**System capability**: SystemCapability.Web.Webview.Core 1280 1281**Parameters** 1282 1283| Name | Type| Mandatory| Description | 1284| ------------ | -------- | ---- | -------------- | 1285| searchString | string | Yes | Search keyword.| 1286 1287**Error codes** 1288 1289For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1290 1291| ID| Error Message | 1292| -------- | ------------------------------------------------------------ | 1293| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1294 1295**Example** 1296 1297```ts 1298// xxx.ets 1299import web_webview from '@ohos.web.webview' 1300 1301@Entry 1302@Component 1303struct WebComponent { 1304 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1305 @State searchString: string = "xxx"; 1306 1307 build() { 1308 Column() { 1309 Button('searchString') 1310 .onClick(() => { 1311 try { 1312 this.controller.searchAllAsync(this.searchString); 1313 } catch (error) { 1314 console.error(`Errorcode: ${error.code}, Message: ${error.message}`); 1315 } 1316 }) 1317 Web({ src: 'www.example.com', controller: this.controller }) 1318 .onSearchResultReceive(ret => { 1319 console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal + 1320 "[total]" + ret.numberOfMatches + "[isDone]" + ret.isDoneCounting); 1321 }) 1322 } 1323 } 1324} 1325``` 1326 1327### clearMatches 1328 1329clearMatches(): void 1330 1331Clears the matches found through [searchAllAsync](#searchallasync). 1332 1333**System capability**: SystemCapability.Web.Webview.Core 1334 1335**Error codes** 1336 1337For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1338 1339| ID| Error Message | 1340| -------- | ------------------------------------------------------------ | 1341| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1342 1343**Example** 1344 1345```ts 1346// xxx.ets 1347import web_webview from '@ohos.web.webview' 1348 1349@Entry 1350@Component 1351struct WebComponent { 1352 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1353 1354 build() { 1355 Column() { 1356 Button('clearMatches') 1357 .onClick(() => { 1358 try { 1359 this.controller.clearMatches(); 1360 } catch (error) { 1361 console.error(`Errorcode: ${error.code}, Message: ${error.message}`); 1362 } 1363 }) 1364 Web({ src: 'www.example.com', controller: this.controller }) 1365 } 1366 } 1367} 1368``` 1369 1370### searchNext 1371 1372searchNext(forward: boolean): void 1373 1374Searches for and highlights the next match. 1375 1376**System capability**: SystemCapability.Web.Webview.Core 1377 1378**Parameters** 1379 1380| Name | Type| Mandatory| Description | 1381| ------- | -------- | ---- | ---------------------- | 1382| forward | boolean | Yes | Whether to search forward.| 1383 1384**Error codes** 1385 1386For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1387 1388| ID| Error Message | 1389| -------- | ------------------------------------------------------------ | 1390| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1391 1392**Example** 1393 1394```ts 1395// xxx.ets 1396import web_webview from '@ohos.web.webview' 1397 1398@Entry 1399@Component 1400struct WebComponent { 1401 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1402 1403 build() { 1404 Column() { 1405 Button('searchNext') 1406 .onClick(() => { 1407 try { 1408 this.controller.searchNext(true); 1409 } catch (error) { 1410 console.error(`Errorcode: ${error.code}, Message: ${error.message}`); 1411 } 1412 }) 1413 Web({ src: 'www.example.com', controller: this.controller }) 1414 } 1415 } 1416} 1417``` 1418 1419### clearSslCache 1420 1421clearSslCache(): void 1422 1423Clears the user operation corresponding to the SSL certificate error event recorded by the **\<Web>** component. 1424 1425**System capability**: SystemCapability.Web.Webview.Core 1426 1427**Error codes** 1428 1429For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1430 1431| ID| Error Message | 1432| -------- | ------------------------------------------------------------ | 1433| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1434 1435**Example** 1436 1437```ts 1438// xxx.ets 1439import web_webview from '@ohos.web.webview' 1440 1441@Entry 1442@Component 1443struct WebComponent { 1444 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1445 1446 build() { 1447 Column() { 1448 Button('clearSslCache') 1449 .onClick(() => { 1450 try { 1451 this.controller.clearSslCache(); 1452 } catch (error) { 1453 console.error(`Errorcode: ${error.code}, Message: ${error.message}`); 1454 } 1455 }) 1456 Web({ src: 'www.example.com', controller: this.controller }) 1457 } 1458 } 1459} 1460``` 1461 1462### clearClientAuthenticationCache 1463 1464clearClientAuthenticationCache(): void 1465 1466Clears the user operation corresponding to the client certificate request event recorded by the **\<Web>** component. 1467 1468**System capability**: SystemCapability.Web.Webview.Core 1469 1470**Error codes** 1471 1472For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1473 1474| ID| Error Message | 1475| -------- | ------------------------------------------------------------ | 1476| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1477 1478**Example** 1479 1480```ts 1481// xxx.ets 1482import web_webview from '@ohos.web.webview' 1483 1484@Entry 1485@Component 1486struct WebComponent { 1487 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1488 1489 build() { 1490 Column() { 1491 Button('clearClientAuthenticationCache') 1492 .onClick(() => { 1493 try { 1494 this.controller.clearClientAuthenticationCache(); 1495 } catch (error) { 1496 console.error(`Errorcode: ${error.code}, Message: ${error.message}`); 1497 } 1498 }) 1499 Web({ src: 'www.example.com', controller: this.controller }) 1500 } 1501 } 1502} 1503``` 1504 1505### createWebMessagePorts 1506 1507 createWebMessagePorts(): Array\<WebMessagePort> 1508 1509Creates web message ports. 1510 1511**System capability**: SystemCapability.Web.Webview.Core 1512 1513**Return value** 1514 1515| Type | Description | 1516| ---------------------- | ----------------- | 1517| Array\<WebMessagePort> | List of web message ports.| 1518 1519**Error codes** 1520 1521For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1522 1523| ID| Error Message | 1524| -------- | ------------------------------------------------------------ | 1525| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1526 1527**Example** 1528 1529 ```ts 1530// xxx.ets 1531import web_webview from '@ohos.web.webview' 1532 1533@Entry 1534@Component 1535struct WebComponent { 1536 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1537 ports: web_webview.WebMessagePort[]; 1538 1539 build() { 1540 Column() { 1541 Button('createWebMessagePorts') 1542 .onClick(() => { 1543 try { 1544 this.ports = this.controller.createWebMessagePorts(); 1545 console.log("createWebMessagePorts size:" + this.ports.length) 1546 } catch (error) { 1547 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 1548 } 1549 }) 1550 Web({ src: 'www.example.com', controller: this.controller }) 1551 } 1552 } 1553} 1554 ``` 1555 1556### postMessage 1557 1558postMessage(name: string, ports: Array\<WebMessagePort>, uri: string): void 1559 1560Sends a web message to an HTML5 window. 1561 1562**System capability**: SystemCapability.Web.Webview.Core 1563 1564**Parameters** 1565 1566| Name| Type | Mandatory| Description | 1567| ------ | ---------------------- | ---- | :------------------------------- | 1568| name | string | Yes | Message to send, including the data and message port.| 1569| ports | Array\<WebMessagePort> | Yes | Ports for receiving the message. | 1570| uri | string | Yes | URI for receiving the message. | 1571 1572**Error codes** 1573 1574For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1575 1576| ID| Error Message | 1577| -------- | ------------------------------------------------------------ | 1578| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1579 1580**Example** 1581 1582```ts 1583// xxx.ets 1584import web_webview from '@ohos.web.webview'; 1585 1586@Entry 1587@Component 1588struct WebComponent { 1589 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1590 ports: web_webview.WebMessagePort[]; 1591 @State sendFromEts: string = 'Send this message from ets to HTML'; 1592 @State receivedFromHtml: string = 'Display received message send from HTML'; 1593 1594 build() { 1595 Column() { 1596 // Display the received HTML content. 1597 Text(this.receivedFromHtml) 1598 // Send the content in the text box to an HTML window. 1599 TextInput({placeholder: 'Send this message from ets to HTML'}) 1600 .onChange((value: string) => { 1601 this.sendFromEts = value; 1602 }) 1603 1604 Button('postMessage') 1605 .onClick(() => { 1606 try { 1607 // 1. Create two message ports. 1608 this.ports = this.controller.createWebMessagePorts(); 1609 // 2. Register a callback on a message port (for example, port 1) on the application side. 1610 this.ports[1].onMessageEvent((result: web_webview.WebMessage) => { 1611 let msg = 'Got msg from HTML:'; 1612 if (typeof(result) == "string") { 1613 console.log("received string message from html5, string is:" + result); 1614 msg = msg + result; 1615 } else if (typeof(result) == "object") { 1616 if (result instanceof ArrayBuffer) { 1617 console.log("received arraybuffer from html5, length is:" + result.byteLength); 1618 msg = msg + "lenght is " + result.byteLength; 1619 } else { 1620 console.log("not support"); 1621 } 1622 } else { 1623 console.log("not support"); 1624 } 1625 this.receivedFromHtml = msg; 1626 }) 1627 // 3. Send another message port (for example, port 0) to the HTML side, which can then save the port for future use. 1628 this.controller.postMessage('__init_port__', [this.ports[0]], '*'); 1629 } catch (error) { 1630 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 1631 } 1632 }) 1633 1634 // 4. Use the port on the application side to send messages to the port that has been sent to the HTML side. 1635 Button('SendDataToHTML') 1636 .onClick(() => { 1637 try { 1638 if (this.ports && this.ports[1]) { 1639 this.ports[1].postMessageEvent(this.sendFromEts); 1640 } else { 1641 console.error(`ports is null, Please initialize first`); 1642 } 1643 } catch (error) { 1644 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 1645 } 1646 }) 1647 Web({ src: $rawfile('xxx.html'), controller: this.controller }) 1648 } 1649 } 1650} 1651``` 1652 1653```html 1654<!--xxx.html--> 1655<!DOCTYPE html> 1656<html> 1657<head> 1658 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 1659 <title>WebView Message Port Demo</title> 1660</head> 1661 1662 <body> 1663 <h1>WebView Message Port Demo</h1> 1664 <div> 1665 <input type="button" value="SendToEts" onclick="PostMsgToEts(msgFromJS.value);"/><br/> 1666 <input id="msgFromJS" type="text" value="send this message from HTML to ets"/><br/> 1667 </div> 1668 <p class="output">display received message send from ets</p> 1669 </body> 1670 <script src="xxx.js"></script> 1671</html> 1672``` 1673 1674```js 1675//xxx.js 1676var h5Port; 1677var output = document.querySelector('.output'); 1678window.addEventListener('message', function (event) { 1679 if (event.data == '__init_port__') { 1680 if (event.ports[0] != null) { 1681 h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side. 1682 h5Port.onmessage = function (event) { 1683 // 2. Receive the message sent from the eTS side. 1684 var msg = 'Got message from ets:'; 1685 var result = event.data; 1686 if (typeof(result) == "string") { 1687 console.log("received string message from html5, string is:" + result); 1688 msg = msg + result; 1689 } else if (typeof(result) == "object") { 1690 if (result instanceof ArrayBuffer) { 1691 console.log("received arraybuffer from html5, length is:" + result.byteLength); 1692 msg = msg + "lenght is " + result.byteLength; 1693 } else { 1694 console.log("not support"); 1695 } 1696 } else { 1697 console.log("not support"); 1698 } 1699 output.innerHTML = msg; 1700 } 1701 } 1702 } 1703}) 1704 1705// 3. Use h5Port to send messages to the eTS side. 1706function PostMsgToEts(data) { 1707 if (h5Port) { 1708 h5Port.postMessage(data); 1709 } else { 1710 console.error("h5Port is null, Please initialize first"); 1711 } 1712} 1713``` 1714 1715### requestFocus 1716 1717requestFocus(): void 1718 1719Requests focus for this web page. 1720 1721**System capability**: SystemCapability.Web.Webview.Core 1722 1723**Error codes** 1724 1725For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1726 1727| ID| Error Message | 1728| -------- | ------------------------------------------------------------ | 1729| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1730 1731**Example** 1732 1733```ts 1734// xxx.ets 1735import web_webview from '@ohos.web.webview'; 1736 1737@Entry 1738@Component 1739struct WebComponent { 1740 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1741 1742 build() { 1743 Column() { 1744 Button('requestFocus') 1745 .onClick(() => { 1746 try { 1747 this.controller.requestFocus(); 1748 } catch (error) { 1749 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 1750 } 1751 }); 1752 Web({ src: 'www.example.com', controller: this.controller }) 1753 } 1754 } 1755} 1756``` 1757 1758### zoomIn 1759 1760zoomIn(): void 1761 1762Zooms in on this web page by 20%. 1763 1764**System capability**: SystemCapability.Web.Webview.Core 1765 1766**Error codes** 1767 1768For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1769 1770| ID| Error Message | 1771| -------- | ------------------------------------------------------------ | 1772| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1773| 17100004 | Function not enable. | 1774 1775**Example** 1776 1777```ts 1778// xxx.ets 1779import web_webview from '@ohos.web.webview'; 1780 1781@Entry 1782@Component 1783struct WebComponent { 1784 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1785 1786 build() { 1787 Column() { 1788 Button('zoomIn') 1789 .onClick(() => { 1790 try { 1791 this.controller.zoomIn(); 1792 } catch (error) { 1793 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 1794 } 1795 }) 1796 Web({ src: 'www.example.com', controller: this.controller }) 1797 } 1798 } 1799} 1800``` 1801 1802### zoomOut 1803 1804zoomOut(): void 1805 1806Zooms out of this web page by 20%. 1807 1808**System capability**: SystemCapability.Web.Webview.Core 1809 1810**Error codes** 1811 1812For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1813 1814| ID| Error Message | 1815| -------- | ------------------------------------------------------------ | 1816| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1817| 17100004 | Function not enable. | 1818 1819**Example** 1820 1821```ts 1822// xxx.ets 1823import web_webview from '@ohos.web.webview'; 1824 1825@Entry 1826@Component 1827struct WebComponent { 1828 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1829 1830 build() { 1831 Column() { 1832 Button('zoomOut') 1833 .onClick(() => { 1834 try { 1835 this.controller.zoomOut(); 1836 } catch (error) { 1837 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 1838 } 1839 }) 1840 Web({ src: 'www.example.com', controller: this.controller }) 1841 } 1842 } 1843} 1844``` 1845 1846### getHitTestValue 1847 1848getHitTestValue(): HitTestValue 1849 1850Obtains the element information of the area being clicked. 1851 1852**System capability**: SystemCapability.Web.Webview.Core 1853 1854**Return value** 1855 1856| Type | Description | 1857| ------------ | -------------------- | 1858| [HitTestValue](#hittestvalue) | Element information of the area being clicked.| 1859 1860**Error codes** 1861 1862For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1863 1864| ID| Error Message | 1865| -------- | ------------------------------------------------------------ | 1866| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1867 1868**Example** 1869 1870```ts 1871// xxx.ets 1872import web_webview from '@ohos.web.webview'; 1873 1874@Entry 1875@Component 1876struct WebComponent { 1877 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1878 1879 build() { 1880 Column() { 1881 Button('getHitTestValue') 1882 .onClick(() => { 1883 try { 1884 let hitValue = this.controller.getHitTestValue(); 1885 console.log("hitType: " + hitValue.type); 1886 console.log("extra: " + hitValue.extra); 1887 } catch (error) { 1888 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 1889 } 1890 }) 1891 Web({ src: 'www.example.com', controller: this.controller }) 1892 } 1893 } 1894} 1895``` 1896 1897### getWebId 1898 1899getWebId(): number 1900 1901Obtains the index value of this **\<Web>** component, which can be used for **\<Web>** component management. 1902 1903**System capability**: SystemCapability.Web.Webview.Core 1904 1905**Return value** 1906 1907| Type | Description | 1908| ------ | --------------------- | 1909| number | Index value of the current **\<Web>** component.| 1910 1911**Error codes** 1912 1913For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1914 1915| ID| Error Message | 1916| -------- | ------------------------------------------------------------ | 1917| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1918 1919**Example** 1920 1921```ts 1922// xxx.ets 1923import web_webview from '@ohos.web.webview'; 1924 1925@Entry 1926@Component 1927struct WebComponent { 1928 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1929 1930 build() { 1931 Column() { 1932 Button('getWebId') 1933 .onClick(() => { 1934 try { 1935 let id = this.controller.getWebId(); 1936 console.log("id: " + id); 1937 } catch (error) { 1938 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 1939 } 1940 }) 1941 Web({ src: 'www.example.com', controller: this.controller }) 1942 } 1943 } 1944} 1945``` 1946 1947### getUserAgent 1948 1949getUserAgent(): string 1950 1951Obtains the default user agent of this web page. 1952 1953**System capability**: SystemCapability.Web.Webview.Core 1954 1955**Return value** 1956 1957| Type | Description | 1958| ------ | -------------- | 1959| string | Default user agent.| 1960 1961**Error codes** 1962 1963For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1964 1965| ID| Error Message | 1966| -------- | ------------------------------------------------------------ | 1967| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1968 1969**Example** 1970 1971```ts 1972// xxx.ets 1973import web_webview from '@ohos.web.webview'; 1974 1975@Entry 1976@Component 1977struct WebComponent { 1978 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1979 1980 build() { 1981 Column() { 1982 Button('getUserAgent') 1983 .onClick(() => { 1984 try { 1985 let userAgent = this.controller.getUserAgent(); 1986 console.log("userAgent: " + userAgent); 1987 } catch (error) { 1988 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 1989 } 1990 }) 1991 Web({ src: 'www.example.com', controller: this.controller }) 1992 } 1993 } 1994} 1995``` 1996 1997You can customize the user agent based on the default user agent. 1998```ts 1999// xxx.ets 2000import web_webview from '@ohos.web.webview'; 2001 2002@Entry 2003@Component 2004struct WebComponent { 2005 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2006 @State ua: string = "" 2007 2008 aboutToAppear():void { 2009 web_webview.once('webInited', () => { 2010 try { 2011 // Customize the user agent on the application side. 2012 this.ua = this.controller.getUserAgent() + 'xxx'; 2013 } catch(error) { 2014 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 2015 } 2016 }) 2017 } 2018 2019 build() { 2020 Column() { 2021 Web({ src: 'www.example.com', controller: this.controller }) 2022 .userAgent(this.ua) 2023 } 2024 } 2025} 2026``` 2027 2028### getTitle 2029 2030getTitle(): string 2031 2032Obtains the title of the current web page. 2033 2034**System capability**: SystemCapability.Web.Webview.Core 2035 2036**Return value** 2037 2038| Type | Description | 2039| ------ | -------------------- | 2040| string | Title of the current web page.| 2041 2042**Error codes** 2043 2044For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2045 2046| ID| Error Message | 2047| -------- | ------------------------------------------------------------ | 2048| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2049 2050**Example** 2051 2052```ts 2053// xxx.ets 2054import web_webview from '@ohos.web.webview'; 2055 2056@Entry 2057@Component 2058struct WebComponent { 2059 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2060 2061 build() { 2062 Column() { 2063 Button('getTitle') 2064 .onClick(() => { 2065 try { 2066 let title = this.controller.getTitle(); 2067 console.log("title: " + title); 2068 } catch (error) { 2069 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 2070 } 2071 }) 2072 Web({ src: 'www.example.com', controller: this.controller }) 2073 } 2074 } 2075} 2076``` 2077 2078### getPageHeight 2079 2080getPageHeight(): number 2081 2082Obtains the height of this web page. 2083 2084**System capability**: SystemCapability.Web.Webview.Core 2085 2086**Return value** 2087 2088| Type | Description | 2089| ------ | -------------------- | 2090| number | Height of the current web page.| 2091 2092**Error codes** 2093 2094For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2095 2096| ID| Error Message | 2097| -------- | ------------------------------------------------------------ | 2098| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2099 2100**Example** 2101 2102```ts 2103// xxx.ets 2104import web_webview from '@ohos.web.webview'; 2105 2106@Entry 2107@Component 2108struct WebComponent { 2109 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2110 2111 build() { 2112 Column() { 2113 Button('getPageHeight') 2114 .onClick(() => { 2115 try { 2116 let pageHeight = this.controller.getPageHeight(); 2117 console.log("pageHeight : " + pageHeight); 2118 } catch (error) { 2119 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 2120 } 2121 }) 2122 Web({ src: 'www.example.com', controller: this.controller }) 2123 } 2124 } 2125} 2126``` 2127 2128### storeWebArchive 2129 2130storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback\<string>): void 2131 2132Stores this web page. This API uses an asynchronous callback to return the result. 2133 2134**System capability**: SystemCapability.Web.Webview.Core 2135 2136**Parameters** 2137 2138| Name | Type | Mandatory| Description | 2139| -------- | --------------------- | ---- | ------------------------------------------------------------ | 2140| baseName | string | Yes | Save path. The value cannot be null. | 2141| autoName | boolean | Yes | Whether to automatically generate a file name. The value **false** means not to automatically generate a file name. The value **true** means to automatically generate a file name based on the URL of the current page and the **baseName** value. In this case, **baseName** is regarded as a directory.| 2142| callback | AsyncCallback\<string> | Yes | Callback used to return the save path if the operation is successful and null otherwise. | 2143 2144**Error codes** 2145 2146For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2147 2148| ID| Error Message | 2149| -------- | ------------------------------------------------------------ | 2150| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2151| 17100003 | Invalid resource path or file type. | 2152 2153**Example** 2154 2155```ts 2156// xxx.ets 2157import web_webview from '@ohos.web.webview' 2158 2159@Entry 2160@Component 2161struct WebComponent { 2162 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2163 2164 build() { 2165 Column() { 2166 Button('storeWebArchive') 2167 .onClick(() => { 2168 try { 2169 this.controller.storeWebArchive("/data/storage/el2/base/", true, (error, filename) => { 2170 if (error) { 2171 console.info(`save web archive error: ` + JSON.stringify(error)) 2172 return; 2173 } 2174 if (filename != null) { 2175 console.info(`save web archive success: ${filename}`) 2176 } 2177 }); 2178 } catch (error) { 2179 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 2180 } 2181 }) 2182 Web({ src: 'www.example.com', controller: this.controller }) 2183 } 2184 } 2185} 2186``` 2187 2188### storeWebArchive 2189 2190storeWebArchive(baseName: string, autoName: boolean): Promise\<string> 2191 2192Stores this web page. This API uses a promise to return the result. 2193 2194**System capability**: SystemCapability.Web.Webview.Core 2195 2196**Parameters** 2197 2198| Name | Type| Mandatory| Description | 2199| -------- | -------- | ---- | ------------------------------------------------------------ | 2200| baseName | string | Yes | Save path. The value cannot be null. | 2201| autoName | boolean | Yes | Whether to automatically generate a file name. The value **false** means not to automatically generate a file name. The value **true** means to automatically generate a file name based on the URL of the current page and the **baseName** value. In this case, **baseName** is regarded as a directory.| 2202 2203**Return value** 2204 2205| Type | Description | 2206| --------------- | ----------------------------------------------------- | 2207| Promise\<string> | Promise used to return the save path if the operation is successful and null otherwise.| 2208 2209**Error codes** 2210 2211For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2212 2213| ID| Error Message | 2214| -------- | ------------------------------------------------------------ | 2215| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2216| 17100003 | Invalid resource path or file type. | 2217 2218**Example** 2219 2220```ts 2221// xxx.ets 2222import web_webview from '@ohos.web.webview' 2223 2224@Entry 2225@Component 2226struct WebComponent { 2227 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2228 2229 build() { 2230 Column() { 2231 Button('storeWebArchive') 2232 .onClick(() => { 2233 try { 2234 this.controller.storeWebArchive("/data/storage/el2/base/", true) 2235 .then(filename => { 2236 if (filename != null) { 2237 console.info(`save web archive success: ${filename}`) 2238 } 2239 }) 2240 .catch(error => { 2241 console.log('error: ' + JSON.stringify(error)); 2242 }) 2243 } catch (error) { 2244 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 2245 } 2246 }) 2247 Web({ src: 'www.example.com', controller: this.controller }) 2248 } 2249 } 2250} 2251``` 2252 2253### getUrl 2254 2255getUrl(): string 2256 2257Obtains the URL of this page. 2258 2259**System capability**: SystemCapability.Web.Webview.Core 2260 2261**Return value** 2262 2263| Type | Description | 2264| ------ | ------------------- | 2265| string | URL of the current page.| 2266 2267**Error codes** 2268 2269For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2270 2271| ID| Error Message | 2272| -------- | ------------------------------------------------------------ | 2273| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2274 2275**Example** 2276 2277```ts 2278// xxx.ets 2279import web_webview from '@ohos.web.webview'; 2280 2281@Entry 2282@Component 2283struct WebComponent { 2284 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2285 2286 build() { 2287 Column() { 2288 Button('getUrl') 2289 .onClick(() => { 2290 try { 2291 let url = this.controller.getUrl(); 2292 console.log("url: " + url); 2293 } catch (error) { 2294 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 2295 } 2296 }) 2297 Web({ src: 'www.example.com', controller: this.controller }) 2298 } 2299 } 2300} 2301``` 2302 2303### stop 2304 2305stop(): void 2306 2307Stops page loading. 2308 2309**System capability**: SystemCapability.Web.Webview.Core 2310 2311**Error codes** 2312 2313For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2314 2315| ID| Error Message | 2316| -------- | ------------------------------------------------------------ | 2317| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2318 2319**Example** 2320 2321```ts 2322// xxx.ets 2323import web_webview from '@ohos.web.webview'; 2324 2325@Entry 2326@Component 2327struct WebComponent { 2328 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2329 2330 build() { 2331 Column() { 2332 Button('stop') 2333 .onClick(() => { 2334 try { 2335 this.controller.stop(); 2336 } catch (error) { 2337 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 2338 } 2339 }); 2340 Web({ src: 'www.example.com', controller: this.controller }) 2341 } 2342 } 2343} 2344``` 2345 2346### backOrForward 2347 2348backOrForward(step: number): void 2349 2350Performs a specific number of steps forward or backward on the current page based on the history stack. No redirection will be performed if the corresponding page does not exist in the history stack. 2351 2352Because the previously loaded web pages are used for the operation, no page reloading is involved. 2353 2354**System capability**: SystemCapability.Web.Webview.Core 2355 2356**Parameters** 2357 2358| Name| Type| Mandatory| Description | 2359| ------ | -------- | ---- | ---------------------- | 2360| step | number | Yes | Number of the steps to take.| 2361 2362**Error codes** 2363 2364For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2365 2366| ID| Error Message | 2367| -------- | ------------------------------------------------------------ | 2368| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2369 2370**Example** 2371 2372```ts 2373// xxx.ets 2374import web_webview from '@ohos.web.webview'; 2375 2376@Entry 2377@Component 2378struct WebComponent { 2379 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2380 @State step: number = -2; 2381 2382 build() { 2383 Column() { 2384 Button('backOrForward') 2385 .onClick(() => { 2386 try { 2387 this.controller.backOrForward(this.step); 2388 } catch (error) { 2389 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 2390 } 2391 }) 2392 Web({ src: 'www.example.com', controller: this.controller }) 2393 } 2394 } 2395} 2396``` 2397 2398### scrollTo 2399 2400scrollTo(x:number, y:number): void 2401 2402Scrolls the page to the specified absolute position. 2403 2404**System capability**: SystemCapability.Web.Webview.Core 2405 2406**Parameters** 2407 2408| Name| Type| Mandatory| Description | 2409| ------ | -------- | ---- | ---------------------- | 2410| x | number | Yes | X coordinate of the absolute position. If the value is a negative number, the value 0 is used.| 2411| y | number | Yes | Y coordinate of the absolute position. If the value is a negative number, the value 0 is used.| 2412 2413**Error codes** 2414 2415For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2416 2417| ID| Error Message | 2418| -------- | ------------------------------------------------------------ | 2419| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2420 2421**Example** 2422 2423```ts 2424// xxx.ets 2425import web_webview from '@ohos.web.webview'; 2426 2427@Entry 2428@Component 2429struct WebComponent { 2430 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2431 2432 build() { 2433 Column() { 2434 Button('scrollTo') 2435 .onClick(() => { 2436 try { 2437 this.controller.scrollTo(50, 50); 2438 } catch (error) { 2439 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 2440 } 2441 }) 2442 Web({ src: 'www.example.com', controller: this.controller }) 2443 } 2444 } 2445} 2446``` 2447 2448```html 2449<!--xxx.html--> 2450<!DOCTYPE html> 2451<html> 2452<head> 2453 <title>Demo</title> 2454 <style> 2455 body { 2456 width:3000px; 2457 height:3000px; 2458 padding-right:170px; 2459 padding-left:170px; 2460 border:5px solid blueviolet 2461 } 2462 </style> 2463</head> 2464<body> 2465Scroll Test 2466</body> 2467</html> 2468``` 2469 2470### scrollBy 2471 2472scrollBy(deltaX:number, deltaY:number): void 2473 2474Scrolls the page by the specified amount. 2475 2476**System capability**: SystemCapability.Web.Webview.Core 2477 2478**Parameters** 2479 2480| Name| Type| Mandatory| Description | 2481| ------ | -------- | ---- | ---------------------- | 2482| deltaX | number | Yes | Amount to scroll by along the x-axis. The positive direction is rightward.| 2483| deltaY | number | Yes | Amount to scroll by along the y-axis. The positive direction is downward.| 2484 2485**Error codes** 2486 2487For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2488 2489| ID| Error Message | 2490| -------- | ------------------------------------------------------------ | 2491| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2492 2493**Example** 2494 2495```ts 2496// xxx.ets 2497import web_webview from '@ohos.web.webview'; 2498 2499@Entry 2500@Component 2501struct WebComponent { 2502 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2503 2504 build() { 2505 Column() { 2506 Button('scrollBy') 2507 .onClick(() => { 2508 try { 2509 this.controller.scrollBy(50, 50); 2510 } catch (error) { 2511 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 2512 } 2513 }) 2514 Web({ src: 'www.example.com', controller: this.controller }) 2515 } 2516 } 2517} 2518``` 2519 2520```html 2521<!--xxx.html--> 2522<!DOCTYPE html> 2523<html> 2524<head> 2525 <title>Demo</title> 2526 <style> 2527 body { 2528 width:3000px; 2529 height:3000px; 2530 padding-right:170px; 2531 padding-left:170px; 2532 border:5px solid blueviolet 2533 } 2534 </style> 2535</head> 2536<body> 2537Scroll Test 2538</body> 2539</html> 2540``` 2541 2542### slideScroll 2543 2544slideScroll(vx:number, vy:number): void 2545 2546Simulates a slide-to-scroll action on the page at the specified velocity. 2547 2548**System capability**: SystemCapability.Web.Webview.Core 2549 2550**Parameters** 2551 2552| Name| Type| Mandatory| Description | 2553| ------ | -------- | ---- | ---------------------- | 2554| vx | number | Yes | Horizontal velocity component of the slide-to-scroll action, where the positive direction is rightward.| 2555| vy | number | Yes | Vertical velocity component of the slide-to-scroll action, where the positive direction is downward.| 2556 2557**Error codes** 2558 2559For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2560 2561| ID| Error Message | 2562| -------- | ------------------------------------------------------------ | 2563| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2564 2565**Example** 2566 2567```ts 2568// xxx.ets 2569import web_webview from '@ohos.web.webview'; 2570 2571@Entry 2572@Component 2573struct WebComponent { 2574 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2575 2576 build() { 2577 Column() { 2578 Button('slideScroll') 2579 .onClick(() => { 2580 try { 2581 this.controller.slideScroll(500, 500); 2582 } catch (error) { 2583 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 2584 } 2585 }) 2586 Web({ src: 'www.example.com', controller: this.controller }) 2587 } 2588 } 2589} 2590``` 2591 2592```html 2593<!--xxx.html--> 2594<!DOCTYPE html> 2595<html> 2596<head> 2597 <title>Demo</title> 2598 <style> 2599 body { 2600 width:3000px; 2601 height:3000px; 2602 padding-right:170px; 2603 padding-left:170px; 2604 border:5px solid blueviolet 2605 } 2606 </style> 2607</head> 2608<body> 2609Scroll Test 2610</body> 2611</html> 2612``` 2613 2614### getOriginalUrl 2615 2616getOriginalUrl(): string 2617 2618Obtains the original URL of this page. 2619 2620**System capability**: SystemCapability.Web.Webview.Core 2621 2622**Return value** 2623 2624| Type | Description | 2625| ------ | ----------------------- | 2626| string | Original URL of the current page.| 2627 2628**Error codes** 2629 2630For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2631 2632| ID| Error Message | 2633| -------- | ------------------------------------------------------------ | 2634| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2635 2636**Example** 2637 2638```ts 2639// xxx.ets 2640import web_webview from '@ohos.web.webview'; 2641 2642@Entry 2643@Component 2644struct WebComponent { 2645 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2646 2647 build() { 2648 Column() { 2649 Button('getOrgUrl') 2650 .onClick(() => { 2651 try { 2652 let url = this.controller.getOriginalUrl(); 2653 console.log("original url: " + url); 2654 } catch (error) { 2655 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 2656 } 2657 }) 2658 Web({ src: 'www.example.com', controller: this.controller }) 2659 } 2660 } 2661} 2662``` 2663 2664### getFavicon 2665 2666getFavicon(): image.PixelMap 2667 2668Obtains the favicon of this page. 2669 2670**System capability**: SystemCapability.Web.Webview.Core 2671 2672**Return value** 2673 2674| Type | Description | 2675| -------------------------------------- | ------------------------------- | 2676| [PixelMap](js-apis-image.md#pixelmap7) | **PixelMap** object of the favicon of the page.| 2677 2678**Error codes** 2679 2680For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2681 2682| ID| Error Message | 2683| -------- | ------------------------------------------------------------ | 2684| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2685 2686**Example** 2687 2688```ts 2689// xxx.ets 2690import web_webview from '@ohos.web.webview'; 2691import image from "@ohos.multimedia.image" 2692@Entry 2693@Component 2694struct WebComponent { 2695 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2696 @State pixelmap: image.PixelMap = undefined; 2697 2698 build() { 2699 Column() { 2700 Button('getFavicon') 2701 .onClick(() => { 2702 try { 2703 this.pixelmap = this.controller.getFavicon(); 2704 } catch (error) { 2705 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 2706 } 2707 }) 2708 Web({ src: 'www.example.com', controller: this.controller }) 2709 } 2710 } 2711} 2712``` 2713 2714### setNetworkAvailable 2715 2716setNetworkAvailable(enable: boolean): void 2717 2718Sets the **window.navigator.onLine** attribute in JavaScript. 2719 2720**System capability**: SystemCapability.Web.Webview.Core 2721 2722**Parameters** 2723 2724| Name| Type | Mandatory| Description | 2725| ------ | ------- | ---- | --------------------------------- | 2726| enable | boolean | Yes | Whether to enable **window.navigator.onLine**.| 2727 2728**Error codes** 2729 2730For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2731 2732| ID| Error Message | 2733| -------- | ------------------------------------------------------------ | 2734| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2735 2736**Example** 2737 2738```ts 2739// xxx.ets 2740import web_webview from '@ohos.web.webview'; 2741 2742@Entry 2743@Component 2744struct WebComponent { 2745 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2746 2747 build() { 2748 Column() { 2749 Button('setNetworkAvailable') 2750 .onClick(() => { 2751 try { 2752 this.controller.setNetworkAvailable(true); 2753 } catch (error) { 2754 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 2755 } 2756 }) 2757 Web({ src: 'www.example.com', controller: this.controller }) 2758 } 2759 } 2760} 2761``` 2762 2763### hasImage 2764 2765hasImage(callback: AsyncCallback\<boolean>): void 2766 2767Checks whether this page contains images. This API uses an asynchronous callback to return the result. 2768 2769**System capability**: SystemCapability.Web.Webview.Core 2770 2771**Parameters** 2772 2773| Name | Type | Mandatory| Description | 2774| -------- | ----------------------- | ---- | -------------------------- | 2775| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result.| 2776 2777**Error codes** 2778 2779For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2780 2781| ID| Error Message | 2782| -------- | ------------------------------------------------------------ | 2783| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 2784 2785**Example** 2786 2787```ts 2788// xxx.ets 2789import web_webview from '@ohos.web.webview'; 2790 2791@Entry 2792@Component 2793struct WebComponent { 2794 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2795 2796 build() { 2797 Column() { 2798 Button('hasImageCb') 2799 .onClick(() => { 2800 try { 2801 this.controller.hasImage((error, data) => { 2802 if (error) { 2803 console.info(`hasImage error: ` + JSON.stringify(error)) 2804 return; 2805 } 2806 console.info("hasImage: " + data); 2807 }); 2808 } catch (error) { 2809 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 2810 } 2811 }) 2812 Web({ src: 'www.example.com', controller: this.controller }) 2813 } 2814 } 2815} 2816``` 2817 2818### hasImage 2819 2820hasImage(): Promise\<boolean> 2821 2822Checks whether this page contains images. This API uses a promise to return the result. 2823 2824**System capability**: SystemCapability.Web.Webview.Core 2825 2826**Return value** 2827 2828| Type | Description | 2829| ----------------- | --------------------------------------- | 2830| Promise\<boolean> | Promise used to return the result.| 2831 2832**Error codes** 2833 2834For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2835 2836| ID| Error Message | 2837| -------- | ------------------------------------------------------------ | 2838| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 2839 2840**Example** 2841 2842```ts 2843// xxx.ets 2844import web_webview from '@ohos.web.webview'; 2845 2846@Entry 2847@Component 2848struct WebComponent { 2849 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2850 2851 build() { 2852 Column() { 2853 Button('hasImagePm') 2854 .onClick(() => { 2855 try { 2856 this.controller.hasImage().then((data) => { 2857 console.info('hasImage: ' + data); 2858 }) 2859 .catch(function (error) { 2860 console.error("error: " + error); 2861 }) 2862 } catch (error) { 2863 console.error(`Errorcode: ${error.code}, Message: ${error.message}`); 2864 } 2865 }) 2866 Web({ src: 'www.example.com', controller: this.controller }) 2867 } 2868 } 2869} 2870``` 2871 2872### removeCache 2873 2874removeCache(clearRom: boolean): void 2875 2876Clears the cache in the application. This API will clear the cache for all webviews in the same application. 2877 2878**System capability**: SystemCapability.Web.Webview.Core 2879 2880**Parameters** 2881 2882| Name | Type | Mandatory| Description | 2883| -------- | ------- | ---- | -------------------------------------------------------- | 2884| clearRom | boolean | Yes | Whether to clear the cache in the ROM and RAM at the same time. The value **true** means to clear the cache in the ROM and RAM at the same time, and **false** means to only clear the cache in the RAM.| 2885 2886**Error codes** 2887 2888For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2889 2890| ID| Error Message | 2891| -------- | ------------------------------------------------------------ | 2892| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2893 2894**Example** 2895 2896```ts 2897// xxx.ets 2898import web_webview from '@ohos.web.webview'; 2899 2900@Entry 2901@Component 2902struct WebComponent { 2903 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2904 2905 build() { 2906 Column() { 2907 Button('removeCache') 2908 .onClick(() => { 2909 try { 2910 this.controller.removeCache(false); 2911 } catch (error) { 2912 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 2913 } 2914 }) 2915 Web({ src: 'www.example.com', controller: this.controller }) 2916 } 2917 } 2918} 2919``` 2920 2921### pageUp 2922 2923pageUp(top:boolean): void 2924 2925Scrolls the page up by half the view port or jumps to the top of the page. 2926 2927**System capability**: SystemCapability.Web.Webview.Core 2928 2929**Parameters** 2930 2931| Name| Type | Mandatory| Description | 2932| ------ | ------- | ---- | ------------------------------------------------------------ | 2933| top | boolean | Yes | Whether to jump to the top of the page. The value **true** means to jump to the top of the page; and **false** means to scroll the page up by half the view port.| 2934 2935**Error codes** 2936 2937For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2938 2939| ID| Error Message | 2940| -------- | ------------------------------------------------------------ | 2941| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2942 2943**Example** 2944 2945```ts 2946// xxx.ets 2947import web_webview from '@ohos.web.webview'; 2948 2949@Entry 2950@Component 2951struct WebComponent { 2952 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2953 2954 build() { 2955 Column() { 2956 Button('pageUp') 2957 .onClick(() => { 2958 try { 2959 this.controller.pageUp(false); 2960 } catch (error) { 2961 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 2962 } 2963 }) 2964 Web({ src: 'www.example.com', controller: this.controller }) 2965 } 2966 } 2967} 2968``` 2969 2970### pageDown 2971 2972pageDown(bottom:boolean): void 2973 2974Scrolls the page down by half the view port or jumps to the bottom of the page. 2975 2976**System capability**: SystemCapability.Web.Webview.Core 2977 2978**Parameters** 2979 2980| Name| Type | Mandatory| Description | 2981| ------ | ------- | ---- | ------------------------------------------------------------ | 2982| bottom | boolean | Yes | Whether to jump to the bottom of the page. The value **true** means to jump to the bottom of the page; and **false** means to scroll the page down by half the view port.| 2983 2984**Error codes** 2985 2986For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2987 2988| ID| Error Message | 2989| -------- | ------------------------------------------------------------ | 2990| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2991 2992**Example** 2993 2994```ts 2995// xxx.ets 2996import web_webview from '@ohos.web.webview'; 2997 2998@Entry 2999@Component 3000struct WebComponent { 3001 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3002 3003 build() { 3004 Column() { 3005 Button('pageDown') 3006 .onClick(() => { 3007 try { 3008 this.controller.pageDown(false); 3009 } catch (error) { 3010 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 3011 } 3012 }) 3013 Web({ src: 'www.example.com', controller: this.controller }) 3014 } 3015 } 3016} 3017``` 3018 3019### getBackForwardEntries 3020 3021getBackForwardEntries(): BackForwardList 3022 3023Obtains the historical information list of the current webview. 3024 3025**System capability**: SystemCapability.Web.Webview.Core 3026 3027**Return value** 3028 3029| Type | Description | 3030| ----------------------------------- | --------------------------- | 3031| [BackForwardList](#backforwardlist) | Historical information list of the current webview.| 3032 3033**Error codes** 3034 3035For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3036 3037| ID| Error Message | 3038| -------- | ------------------------------------------------------------ | 3039| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3040 3041**Example** 3042 3043```ts 3044// xxx.ets 3045import web_webview from '@ohos.web.webview'; 3046 3047@Entry 3048@Component 3049struct WebComponent { 3050 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3051 3052 build() { 3053 Column() { 3054 Button('getBackForwardEntries') 3055 .onClick(() => { 3056 try { 3057 let list = this.controller.getBackForwardEntries() 3058 } catch (error) { 3059 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 3060 } 3061 }) 3062 Web({ src: 'www.example.com', controller: this.controller }) 3063 } 3064 } 3065} 3066``` 3067 3068### serializeWebState 3069 3070serializeWebState(): Uint8Array 3071 3072Serializes the page status history of the current Webview. 3073 3074**System capability**: SystemCapability.Web.Webview.Core 3075 3076**Return value** 3077 3078| Type | Description | 3079| ---------- | --------------------------------------------- | 3080| Uint8Array | Serialized data of the page status history of the current WebView.| 3081 3082**Error codes** 3083 3084For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3085 3086| ID| Error Message | 3087| -------- | ------------------------------------------------------------ | 3088| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3089 3090**Example** 3091 30921. To perform operations on files, you must import the file management module. For details, see [File Management](./js-apis-file-fs.md). 3093```ts 3094// xxx.ets 3095import web_webview from '@ohos.web.webview'; 3096import fs from '@ohos.file.fs'; 3097 3098@Entry 3099@Component 3100struct WebComponent { 3101 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3102 3103 build() { 3104 Column() { 3105 Button('serializeWebState') 3106 .onClick(() => { 3107 try { 3108 let state = this.controller.serializeWebState(); 3109 // Obtain the value of globalThis.cacheDir from MainAbility.ts. 3110 let path = globalThis.cacheDir; 3111 path += '/WebState'; 3112 // Synchronously open a file. 3113 let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 3114 fs.writeSync(file.fd, state.buffer); 3115 fs.closeSync(file.fd); 3116 } catch (error) { 3117 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 3118 } 3119 }) 3120 Web({ src: 'www.example.com', controller: this.controller }) 3121 } 3122 } 3123} 3124``` 3125 31262. Modify **MainAbility.ts**. 3127Obtain the path of the application cache file. 3128```ts 3129// xxx.ts 3130import UIAbility from '@ohos.app.ability.UIAbility'; 3131import web_webview from '@ohos.web.webview'; 3132 3133export default class MainAbility extends UIAbility { 3134 onCreate(want, launchParam) { 3135 // Bind cacheDir to the globalThis object to implement data synchronization between the UIAbility component and the page. 3136 globalThis.cacheDir = this.context.cacheDir; 3137 } 3138} 3139``` 3140 3141### restoreWebState 3142 3143restoreWebState(state: Uint8Array): void 3144 3145Restores the page status history from the serialized data of the current WebView. 3146 3147**System capability**: SystemCapability.Web.Webview.Core 3148 3149**Parameters** 3150 3151| Name| Type | Mandatory| Description | 3152| ------ | ---------- | ---- | ---------------------------- | 3153| state | Uint8Array | Yes | Serialized data of the page status history.| 3154 3155**Error codes** 3156 3157For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3158 3159| ID| Error Message | 3160| -------- | ------------------------------------------------------------ | 3161| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3162 3163**Example** 3164 31651. To perform operations on files, you must import the file management module. For details, see [File Management](./js-apis-file-fs.md). 3166```ts 3167// xxx.ets 3168import web_webview from '@ohos.web.webview'; 3169import fs from '@ohos.file.fs'; 3170 3171@Entry 3172@Component 3173struct WebComponent { 3174 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3175 3176 build() { 3177 Column() { 3178 Button('RestoreWebState') 3179 .onClick(() => { 3180 try { 3181 // Obtain the value of globalThis.cacheDir from MainAbility.ts. 3182 let path = globalThis.cacheDir; 3183 path += '/WebState'; 3184 // Synchronously open a file. 3185 let file = fs.openSync(path, fs.OpenMode.READ_WRITE); 3186 let stat = fs.statSync(path); 3187 let size = stat.size; 3188 let buf = new ArrayBuffer(size); 3189 fs.read(file.fd, buf, (err, readLen) => { 3190 if (err) { 3191 console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); 3192 } else { 3193 console.info("read file data succeed"); 3194 this.controller.restoreWebState(new Uint8Array(buf.slice(0, readLen))); 3195 fs.closeSync(file); 3196 } 3197 }); 3198 } catch (error) { 3199 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 3200 } 3201 }) 3202 Web({ src: 'www.example.com', controller: this.controller }) 3203 } 3204 } 3205} 3206``` 3207 32082. Modify **MainAbility.ts**. 3209Obtain the path of the application cache file. 3210```ts 3211// xxx.ts 3212import UIAbility from '@ohos.app.ability.UIAbility'; 3213import web_webview from '@ohos.web.webview'; 3214 3215export default class MainAbility extends UIAbility { 3216 onCreate(want, launchParam) { 3217 // Bind cacheDir to the globalThis object to implement data synchronization between the UIAbility component and the page. 3218 globalThis.cacheDir = this.context.cacheDir; 3219 } 3220} 3221``` 3222 3223### customizeSchemes 3224 3225static customizeSchemes(schemes: Array\<WebCustomScheme\>): void 3226 3227Customizes the URL schemes (also known as protocols). It is recommended that this API be called before any **\<Web>** component is initialized. 3228 3229**System capability**: SystemCapability.Web.Webview.Core 3230 3231**Parameters** 3232 3233| Name | Type | Mandatory| Description | 3234| -------- | ------- | ---- | -------------------------------------- | 3235| schemes | Array\<[WebCustomScheme](#webcustomscheme)\> | Yes | Array of up to 10 custom schemes.| 3236 3237**Example** 3238 3239```ts 3240// xxx.ets 3241import web_webview from '@ohos.web.webview'; 3242 3243@Entry 3244@Component 3245struct WebComponent { 3246 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3247 responseweb: WebResourceResponse = new WebResourceResponse() 3248 scheme1: web_webview.WebCustomScheme = {schemeName: "name1", isSupportCORS: true, isSupportFetch: true} 3249 scheme2: web_webview.WebCustomScheme = {schemeName: "name2", isSupportCORS: true, isSupportFetch: true} 3250 scheme3: web_webview.WebCustomScheme = {schemeName: "name3", isSupportCORS: true, isSupportFetch: true} 3251 3252 aboutToAppear():void { 3253 try { 3254 web_webview.WebviewController.customizeSchemes([this.scheme1, this.scheme2, this.scheme3]) 3255 } catch(error) { 3256 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 3257 } 3258 } 3259 3260 build() { 3261 Column() { 3262 Web({ src: 'www.example.com', controller: this.controller }) 3263 .onInterceptRequest((event) => { 3264 console.log('url:' + event.request.getRequestUrl()) 3265 return this.responseweb 3266 }) 3267 } 3268 } 3269} 3270``` 3271 3272## WebCookieManager 3273 3274Implements a **WebCookieManager** instance to manage behavior of cookies in **\<Web>** components. All **\<Web>** components in an application share a **WebCookieManager** instance. 3275 3276### getCookie 3277 3278static getCookie(url: string): string 3279 3280Obtains the cookie corresponding to the specified URL. 3281 3282**System capability**: SystemCapability.Web.Webview.Core 3283 3284**Parameters** 3285 3286| Name| Type | Mandatory| Description | 3287| ------ | ------ | ---- | :------------------------ | 3288| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 3289 3290**Return value** 3291 3292| Type | Description | 3293| ------ | ------------------------- | 3294| string | Cookie value corresponding to the specified URL.| 3295 3296**Error codes** 3297 3298For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3299 3300| ID| Error Message | 3301| -------- | ------------------------------------------------------ | 3302| 17100002 | Invalid url. | 3303 3304**Example** 3305 3306```ts 3307// xxx.ets 3308import web_webview from '@ohos.web.webview' 3309 3310@Entry 3311@Component 3312struct WebComponent { 3313 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3314 3315 build() { 3316 Column() { 3317 Button('getCookie') 3318 .onClick(() => { 3319 try { 3320 let value = web_webview.WebCookieManager.getCookie('https://www.example.com'); 3321 console.log("value: " + value); 3322 } catch (error) { 3323 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 3324 } 3325 }) 3326 Web({ src: 'www.example.com', controller: this.controller }) 3327 } 3328 } 3329} 3330``` 3331 3332### setCookie 3333 3334static setCookie(url: string, value: string): void 3335 3336Sets a cookie for the specified URL. 3337 3338**System capability**: SystemCapability.Web.Webview.Core 3339 3340**Parameters** 3341 3342| Name| Type | Mandatory| Description | 3343| ------ | ------ | ---- | :------------------------ | 3344| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 3345| value | string | Yes | Cookie value to set. | 3346 3347**Error codes** 3348 3349For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3350 3351| ID| Error Message | 3352| -------- | ------------------------------------------------------ | 3353| 17100002 | Invalid url. | 3354| 17100005 | Invalid cookie value. | 3355 3356**Example** 3357 3358```ts 3359// xxx.ets 3360import web_webview from '@ohos.web.webview' 3361 3362@Entry 3363@Component 3364struct WebComponent { 3365 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3366 3367 build() { 3368 Column() { 3369 Button('setCookie') 3370 .onClick(() => { 3371 try { 3372 web_webview.WebCookieManager.setCookie('https://www.example.com', 'a=b'); 3373 } catch (error) { 3374 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 3375 } 3376 }) 3377 Web({ src: 'www.example.com', controller: this.controller }) 3378 } 3379 } 3380} 3381``` 3382 3383### saveCookieAsync 3384 3385static saveCookieAsync(callback: AsyncCallback\<void>): void 3386 3387Saves the cookies in the memory to the drive. This API uses an asynchronous callback to return the result. 3388 3389**System capability**: SystemCapability.Web.Webview.Core 3390 3391**Parameters** 3392 3393| Name | Type | Mandatory| Description | 3394| -------- | ---------------------- | ---- | :------------------------------------------------- | 3395| callback | AsyncCallback\<void> | Yes | Callback used to return whether the cookies are successfully saved.| 3396 3397 3398**Example** 3399 3400```ts 3401// xxx.ets 3402import web_webview from '@ohos.web.webview' 3403 3404@Entry 3405@Component 3406struct WebComponent { 3407 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3408 3409 build() { 3410 Column() { 3411 Button('saveCookieAsync') 3412 .onClick(() => { 3413 try { 3414 web_webview.WebCookieManager.saveCookieAsync((error) => { 3415 if (error) { 3416 console.log("error: " + error); 3417 } 3418 }) 3419 } catch (error) { 3420 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 3421 } 3422 }) 3423 Web({ src: 'www.example.com', controller: this.controller }) 3424 } 3425 } 3426} 3427``` 3428 3429### saveCookieAsync 3430 3431static saveCookieAsync(): Promise\<void> 3432 3433Saves the cookies in the memory to the drive. This API uses a promise to return the result. 3434 3435**System capability**: SystemCapability.Web.Webview.Core 3436 3437**Return value** 3438 3439| Type | Description | 3440| ---------------- | ----------------------------------------- | 3441| Promise\<void> | Promise used to return the operation result.| 3442 3443**Example** 3444 3445```ts 3446// xxx.ets 3447import web_webview from '@ohos.web.webview' 3448 3449@Entry 3450@Component 3451struct WebComponent { 3452 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3453 3454 build() { 3455 Column() { 3456 Button('saveCookieAsync') 3457 .onClick(() => { 3458 try { 3459 web_webview.WebCookieManager.saveCookieAsync() 3460 .then(() => { 3461 console.log("saveCookieAsyncCallback success!"); 3462 }) 3463 .catch((error) => { 3464 console.error("error: " + error); 3465 }); 3466 } catch (error) { 3467 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 3468 } 3469 }) 3470 Web({ src: 'www.example.com', controller: this.controller }) 3471 } 3472 } 3473} 3474``` 3475 3476### putAcceptCookieEnabled 3477 3478static putAcceptCookieEnabled(accept: boolean): void 3479 3480Sets whether the **WebCookieManager** instance has the permission to send and receive cookies. 3481 3482**System capability**: SystemCapability.Web.Webview.Core 3483 3484**Parameters** 3485 3486| Name| Type | Mandatory| Description | 3487| ------ | ------- | ---- | :----------------------------------- | 3488| accept | boolean | Yes | Whether the **WebCookieManager** instance has the permission to send and receive cookies.| 3489 3490**Example** 3491 3492```ts 3493// xxx.ets 3494import web_webview from '@ohos.web.webview' 3495 3496@Entry 3497@Component 3498struct WebComponent { 3499 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3500 3501 build() { 3502 Column() { 3503 Button('putAcceptCookieEnabled') 3504 .onClick(() => { 3505 try { 3506 web_webview.WebCookieManager.putAcceptCookieEnabled(false); 3507 } catch (error) { 3508 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 3509 } 3510 }) 3511 Web({ src: 'www.example.com', controller: this.controller }) 3512 } 3513 } 3514} 3515``` 3516 3517### isCookieAllowed 3518 3519static isCookieAllowed(): boolean 3520 3521Checks whether the **WebCookieManager** instance has the permission to send and receive cookies. 3522 3523**System capability**: SystemCapability.Web.Webview.Core 3524 3525**Return value** 3526 3527| Type | Description | 3528| ------- | -------------------------------- | 3529| boolean | Whether the **WebCookieManager** instance has the permission to send and receive cookies. The default value is **true**.| 3530 3531**Example** 3532 3533```ts 3534// xxx.ets 3535import web_webview from '@ohos.web.webview' 3536 3537@Entry 3538@Component 3539struct WebComponent { 3540 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3541 3542 build() { 3543 Column() { 3544 Button('isCookieAllowed') 3545 .onClick(() => { 3546 let result = web_webview.WebCookieManager.isCookieAllowed(); 3547 console.log("result: " + result); 3548 }) 3549 Web({ src: 'www.example.com', controller: this.controller }) 3550 } 3551 } 3552} 3553``` 3554 3555### putAcceptThirdPartyCookieEnabled 3556 3557static putAcceptThirdPartyCookieEnabled(accept: boolean): void 3558 3559Sets whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. 3560 3561**System capability**: SystemCapability.Web.Webview.Core 3562 3563**Parameters** 3564 3565| Name| Type | Mandatory| Description | 3566| ------ | ------- | ---- | :----------------------------------------- | 3567| accept | boolean | Yes | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies.| 3568 3569**Example** 3570 3571```ts 3572// xxx.ets 3573import web_webview from '@ohos.web.webview' 3574 3575@Entry 3576@Component 3577struct WebComponent { 3578 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3579 3580 build() { 3581 Column() { 3582 Button('putAcceptThirdPartyCookieEnabled') 3583 .onClick(() => { 3584 try { 3585 web_webview.WebCookieManager.putAcceptThirdPartyCookieEnabled(false); 3586 } catch (error) { 3587 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 3588 } 3589 }) 3590 Web({ src: 'www.example.com', controller: this.controller }) 3591 } 3592 } 3593} 3594``` 3595 3596### isThirdPartyCookieAllowed 3597 3598static isThirdPartyCookieAllowed(): boolean 3599 3600Checks whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. 3601 3602**System capability**: SystemCapability.Web.Webview.Core 3603 3604**Return value** 3605 3606| Type | Description | 3607| ------- | -------------------------------------- | 3608| boolean | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. The default value is **false**.| 3609 3610**Example** 3611 3612```ts 3613// xxx.ets 3614import web_webview from '@ohos.web.webview' 3615 3616@Entry 3617@Component 3618struct WebComponent { 3619 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3620 3621 build() { 3622 Column() { 3623 Button('isThirdPartyCookieAllowed') 3624 .onClick(() => { 3625 let result = web_webview.WebCookieManager.isThirdPartyCookieAllowed(); 3626 console.log("result: " + result); 3627 }) 3628 Web({ src: 'www.example.com', controller: this.controller }) 3629 } 3630 } 3631} 3632``` 3633 3634### existCookie 3635 3636static existCookie(): boolean 3637 3638Checks whether cookies exist. 3639 3640**System capability**: SystemCapability.Web.Webview.Core 3641 3642**Return value** 3643 3644| Type | Description | 3645| ------- | -------------------------------------- | 3646| boolean | Whether cookies exist.| 3647 3648**Example** 3649 3650```ts 3651// xxx.ets 3652import web_webview from '@ohos.web.webview' 3653 3654@Entry 3655@Component 3656struct WebComponent { 3657 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3658 3659 build() { 3660 Column() { 3661 Button('existCookie') 3662 .onClick(() => { 3663 let result = web_webview.WebCookieManager.existCookie(); 3664 console.log("result: " + result); 3665 }) 3666 Web({ src: 'www.example.com', controller: this.controller }) 3667 } 3668 } 3669} 3670``` 3671 3672### deleteEntireCookie 3673 3674static deleteEntireCookie(): void 3675 3676Deletes all cookies. 3677 3678**System capability**: SystemCapability.Web.Webview.Core 3679 3680**Example** 3681 3682```ts 3683// xxx.ets 3684import web_webview from '@ohos.web.webview' 3685 3686@Entry 3687@Component 3688struct WebComponent { 3689 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3690 3691 build() { 3692 Column() { 3693 Button('deleteEntireCookie') 3694 .onClick(() => { 3695 web_webview.WebCookieManager.deleteEntireCookie(); 3696 }) 3697 Web({ src: 'www.example.com', controller: this.controller }) 3698 } 3699 } 3700} 3701``` 3702 3703### deleteSessionCookie 3704 3705static deleteSessionCookie(): void 3706 3707Deletes all session cookies. 3708 3709**System capability**: SystemCapability.Web.Webview.Core 3710 3711**Example** 3712 3713```ts 3714// xxx.ets 3715import web_webview from '@ohos.web.webview' 3716 3717@Entry 3718@Component 3719struct WebComponent { 3720 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3721 3722 build() { 3723 Column() { 3724 Button('deleteSessionCookie') 3725 .onClick(() => { 3726 web_webview.WebCookieManager.deleteSessionCookie(); 3727 }) 3728 Web({ src: 'www.example.com', controller: this.controller }) 3729 } 3730 } 3731} 3732``` 3733 3734## WebStorage 3735 3736Implements a **WebStorage** object to manage the Web SQL database and HTML5 Web Storage APIs. All **\<Web>** components in an application share a **WebStorage** object. 3737 3738### deleteOrigin 3739 3740static deleteOrigin(origin : string): void 3741 3742Deletes all data in the specified origin. 3743 3744**System capability**: SystemCapability.Web.Webview.Core 3745 3746**Parameters** 3747 3748| Name| Type | Mandatory| Description | 3749| ------ | ------ | ---- | ------------------------ | 3750| origin | string | Yes | Index of the origin, which is obtained through [getOrigins](#getorigins).| 3751 3752**Error codes** 3753 3754For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3755 3756| ID| Error Message | 3757| -------- | ------------------------------------------------------ | 3758| 17100011 | Invalid origin. | 3759 3760**Example** 3761 3762```ts 3763// xxx.ets 3764import web_webview from '@ohos.web.webview'; 3765 3766@Entry 3767@Component 3768struct WebComponent { 3769 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3770 origin: string = "file:///"; 3771 3772 build() { 3773 Column() { 3774 Button('deleteOrigin') 3775 .onClick(() => { 3776 try { 3777 web_webview.WebStorage.deleteOrigin(this.origin); 3778 } catch (error) { 3779 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 3780 } 3781 3782 }) 3783 Web({ src: 'www.example.com', controller: this.controller }) 3784 .databaseAccess(true) 3785 } 3786 } 3787} 3788``` 3789 3790### getOrigins 3791 3792static getOrigins(callback: AsyncCallback\<Array\<WebStorageOrigin>>) : void 3793 3794Obtains information about all origins that are currently using the Web SQL Database. This API uses an asynchronous callback to return the result. 3795 3796**System capability**: SystemCapability.Web.Webview.Core 3797 3798**Parameters** 3799 3800| Name | Type | Mandatory| Description | 3801| -------- | -------------------------------------- | ---- | ------------------------------------------------------ | 3802| callback | AsyncCallback\<Array\<[WebStorageOrigin](#webstorageorigin)>> | Yes | Callback used to return the information about the origins. For details, see [WebStorageOrigin](#webstorageorigin).| 3803 3804**Error codes** 3805 3806For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3807 3808| ID| Error Message | 3809| -------- | ------------------------------------------------------ | 3810| 17100012 | Invalid web storage origin. | 3811 3812**Example** 3813 3814```ts 3815// xxx.ets 3816import web_webview from '@ohos.web.webview'; 3817 3818@Entry 3819@Component 3820struct WebComponent { 3821 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3822 3823 build() { 3824 Column() { 3825 Button('getOrigins') 3826 .onClick(() => { 3827 try { 3828 web_webview.WebStorage.getOrigins((error, origins) => { 3829 if (error) { 3830 console.log('error: ' + JSON.stringify(error)); 3831 return; 3832 } 3833 for (let i = 0; i < origins.length; i++) { 3834 console.log('origin: ' + origins[i].origin); 3835 console.log('usage: ' + origins[i].usage); 3836 console.log('quota: ' + origins[i].quota); 3837 } 3838 }) 3839 } catch (error) { 3840 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 3841 } 3842 3843 }) 3844 Web({ src: 'www.example.com', controller: this.controller }) 3845 .databaseAccess(true) 3846 } 3847 } 3848} 3849``` 3850 3851### getOrigins 3852 3853static getOrigins() : Promise\<Array\<WebStorageOrigin>> 3854 3855Obtains information about all origins that are currently using the Web SQL Database. This API uses a promise to return the result. 3856 3857**System capability**: SystemCapability.Web.Webview.Core 3858 3859**Return value** 3860 3861| Type | Description | 3862| -------------------------------- | ------------------------------------------------------------ | 3863| Promise\<Array\<[WebStorageOrigin](#webstorageorigin)>> | Promise used to return the information about the origins. For details, see [WebStorageOrigin](#webstorageorigin).| 3864 3865**Error codes** 3866 3867For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3868 3869| ID| Error Message | 3870| -------- | ------------------------------------------------------ | 3871| 17100012 | Invalid web storage origin. | 3872 3873**Example** 3874 3875```ts 3876// xxx.ets 3877import web_webview from '@ohos.web.webview'; 3878 3879@Entry 3880@Component 3881struct WebComponent { 3882 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3883 3884 build() { 3885 Column() { 3886 Button('getOrigins') 3887 .onClick(() => { 3888 try { 3889 web_webview.WebStorage.getOrigins() 3890 .then(origins => { 3891 for (let i = 0; i < origins.length; i++) { 3892 console.log('origin: ' + origins[i].origin); 3893 console.log('usage: ' + origins[i].usage); 3894 console.log('quota: ' + origins[i].quota); 3895 } 3896 }) 3897 .catch(e => { 3898 console.log('error: ' + JSON.stringify(e)); 3899 }) 3900 } catch (error) { 3901 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 3902 } 3903 3904 }) 3905 Web({ src: 'www.example.com', controller: this.controller }) 3906 .databaseAccess(true) 3907 } 3908 } 3909} 3910``` 3911 3912### getOriginQuota 3913 3914static getOriginQuota(origin : string, callback : AsyncCallback\<number>) : void 3915 3916Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. 3917 3918**System capability**: SystemCapability.Web.Webview.Core 3919 3920**Parameters** 3921 3922| Name | Type | Mandatory| Description | 3923| -------- | --------------------- | ---- | ------------------ | 3924| origin | string | Yes | Index of the origin.| 3925| callback | AsyncCallback\<number> | Yes | Storage quota of the origin. | 3926 3927**Error codes** 3928 3929For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3930 3931| ID| Error Message | 3932| -------- | ------------------------------------------------------ | 3933| 17100011 | Invalid origin. | 3934 3935**Example** 3936 3937```ts 3938// xxx.ets 3939import web_webview from '@ohos.web.webview'; 3940 3941@Entry 3942@Component 3943struct WebComponent { 3944 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3945 origin: string = "file:///"; 3946 3947 build() { 3948 Column() { 3949 Button('getOriginQuota') 3950 .onClick(() => { 3951 try { 3952 web_webview.WebStorage.getOriginQuota(this.origin, (error, quota) => { 3953 if (error) { 3954 console.log('error: ' + JSON.stringify(error)); 3955 return; 3956 } 3957 console.log('quota: ' + quota); 3958 }) 3959 } catch (error) { 3960 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 3961 } 3962 3963 }) 3964 Web({ src: 'www.example.com', controller: this.controller }) 3965 .databaseAccess(true) 3966 } 3967 } 3968} 3969``` 3970 3971### getOriginQuota 3972 3973static getOriginQuota(origin : string) : Promise\<number> 3974 3975Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. 3976 3977**System capability**: SystemCapability.Web.Webview.Core 3978 3979**Parameters** 3980 3981| Name| Type | Mandatory| Description | 3982| ------ | ------ | ---- | ------------------ | 3983| origin | string | Yes | Index of the origin.| 3984 3985**Return value** 3986 3987| Type | Description | 3988| --------------- | --------------------------------------- | 3989| Promise\<number> | Promise used to return the storage quota of the origin.| 3990 3991**Error codes** 3992 3993For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3994 3995| ID| Error Message | 3996| -------- | ------------------------------------------------------ | 3997| 17100011 | Invalid origin. | 3998 3999**Example** 4000 4001```ts 4002// xxx.ets 4003import web_webview from '@ohos.web.webview'; 4004 4005@Entry 4006@Component 4007struct WebComponent { 4008 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4009 origin: string = "file:///"; 4010 4011 build() { 4012 Column() { 4013 Button('getOriginQuota') 4014 .onClick(() => { 4015 try { 4016 web_webview.WebStorage.getOriginQuota(this.origin) 4017 .then(quota => { 4018 console.log('quota: ' + quota); 4019 }) 4020 .catch(e => { 4021 console.log('error: ' + JSON.stringify(e)); 4022 }) 4023 } catch (error) { 4024 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 4025 } 4026 4027 }) 4028 Web({ src: 'www.example.com', controller: this.controller }) 4029 .databaseAccess(true) 4030 } 4031 } 4032} 4033``` 4034 4035### getOriginUsage 4036 4037static getOriginUsage(origin : string, callback : AsyncCallback\<number>) : void 4038 4039Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. 4040 4041**System capability**: SystemCapability.Web.Webview.Core 4042 4043**Parameters** 4044 4045| Name | Type | Mandatory| Description | 4046| -------- | --------------------- | ---- | ------------------ | 4047| origin | string | Yes | Index of the origin.| 4048| callback | AsyncCallback\<number> | Yes | Storage usage of the origin. | 4049 4050**Error codes** 4051 4052For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4053 4054| ID| Error Message | 4055| -------- | ------------------------------------------------------ | 4056| 17100011 | Invalid origin. | 4057 4058**Example** 4059 4060```ts 4061// xxx.ets 4062import web_webview from '@ohos.web.webview'; 4063 4064@Entry 4065@Component 4066struct WebComponent { 4067 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4068 origin: string = "file:///"; 4069 4070 build() { 4071 Column() { 4072 Button('getOriginUsage') 4073 .onClick(() => { 4074 try { 4075 web_webview.WebStorage.getOriginUsage(this.origin, (error, usage) => { 4076 if (error) { 4077 console.log('error: ' + JSON.stringify(error)); 4078 return; 4079 } 4080 console.log('usage: ' + usage); 4081 }) 4082 } catch (error) { 4083 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 4084 } 4085 4086 }) 4087 Web({ src: 'www.example.com', controller: this.controller }) 4088 .databaseAccess(true) 4089 } 4090 } 4091} 4092``` 4093 4094### getOriginUsage 4095 4096static getOriginUsage(origin : string) : Promise\<number> 4097 4098Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. 4099 4100**System capability**: SystemCapability.Web.Webview.Core 4101 4102**Parameters** 4103 4104| Name| Type | Mandatory| Description | 4105| ------ | ------ | ---- | ------------------ | 4106| origin | string | Yes | Index of the origin.| 4107 4108**Return value** 4109 4110| Type | Description | 4111| --------------- | ------------------------------------- | 4112| Promise\<number> | Promise used to return the storage usage of the origin.| 4113 4114**Error codes** 4115 4116For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4117 4118| ID| Error Message | 4119| -------- | ----------------------------------------------------- | 4120| 17100011 | Invalid origin. | 4121 4122**Example** 4123 4124```ts 4125// xxx.ets 4126import web_webview from '@ohos.web.webview'; 4127 4128@Entry 4129@Component 4130struct WebComponent { 4131 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4132 origin: string = "file:///"; 4133 4134 build() { 4135 Column() { 4136 Button('getOriginUsage') 4137 .onClick(() => { 4138 try { 4139 web_webview.WebStorage.getOriginUsage(this.origin) 4140 .then(usage => { 4141 console.log('usage: ' + usage); 4142 }) 4143 .catch(e => { 4144 console.log('error: ' + JSON.stringify(e)); 4145 }) 4146 } catch (error) { 4147 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 4148 } 4149 4150 }) 4151 Web({ src: 'www.example.com', controller: this.controller }) 4152 .databaseAccess(true) 4153 } 4154 } 4155} 4156``` 4157 4158### deleteAllData 4159 4160static deleteAllData(): void 4161 4162Deletes all data in the Web SQL Database. 4163 4164**System capability**: SystemCapability.Web.Webview.Core 4165 4166**Example** 4167 4168```ts 4169// xxx.ets 4170import web_webview from '@ohos.web.webview'; 4171 4172@Entry 4173@Component 4174struct WebComponent { 4175 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4176 4177 build() { 4178 Column() { 4179 Button('deleteAllData') 4180 .onClick(() => { 4181 try { 4182 web_webview.WebStorage.deleteAllData(); 4183 } catch (error) { 4184 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 4185 } 4186 }) 4187 Web({ src: 'www.example.com', controller: this.controller }) 4188 .databaseAccess(true) 4189 } 4190 } 4191} 4192``` 4193 4194## WebDataBase 4195 4196Implements a **WebDataBase** object. 4197 4198### getHttpAuthCredentials 4199 4200static getHttpAuthCredentials(host: string, realm: string): Array\<string> 4201 4202Retrieves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. 4203 4204**System capability**: SystemCapability.Web.Webview.Core 4205 4206**Parameters** 4207 4208| Name| Type | Mandatory| Description | 4209| ------ | ------ | ---- | ---------------------------- | 4210| host | string | Yes | Host to which HTTP authentication credentials apply.| 4211| realm | string | Yes | Realm to which HTTP authentication credentials apply. | 4212 4213**Return value** 4214 4215| Type | Description | 4216| ----- | -------------------------------------------- | 4217| Array\<string> | Returns the array of the matching user names and passwords if the operation is successful; returns an empty array otherwise.| 4218 4219**Example** 4220 4221```ts 4222// xxx.ets 4223import web_webview from '@ohos.web.webview'; 4224 4225@Entry 4226@Component 4227struct WebComponent { 4228 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4229 host: string = "www.spincast.org"; 4230 realm: string = "protected example"; 4231 username_password: string[]; 4232 4233 build() { 4234 Column() { 4235 Button('getHttpAuthCredentials') 4236 .onClick(() => { 4237 try { 4238 this.username_password = web_webview.WebDataBase.getHttpAuthCredentials(this.host, this.realm); 4239 console.log('num: ' + this.username_password.length); 4240 } catch (error) { 4241 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 4242 } 4243 }) 4244 Web({ src: 'www.example.com', controller: this.controller }) 4245 } 4246 } 4247} 4248``` 4249 4250### saveHttpAuthCredentials 4251 4252static saveHttpAuthCredentials(host: string, realm: string, username: string, password: string): void 4253 4254Saves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. 4255 4256**System capability**: SystemCapability.Web.Webview.Core 4257 4258**Parameters** 4259 4260| Name | Type | Mandatory| Description | 4261| -------- | ------ | ---- | ---------------------------- | 4262| host | string | Yes | Host to which HTTP authentication credentials apply.| 4263| realm | string | Yes | Realm to which HTTP authentication credentials apply. | 4264| username | string | Yes | User name. | 4265| password | string | Yes | Password. | 4266 4267**Example** 4268 4269```ts 4270// xxx.ets 4271import web_webview from '@ohos.web.webview'; 4272 4273@Entry 4274@Component 4275struct WebComponent { 4276 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4277 host: string = "www.spincast.org"; 4278 realm: string = "protected example"; 4279 4280 build() { 4281 Column() { 4282 Button('saveHttpAuthCredentials') 4283 .onClick(() => { 4284 try { 4285 web_webview.WebDataBase.saveHttpAuthCredentials(this.host, this.realm, "Stromgol", "Laroche"); 4286 } catch (error) { 4287 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 4288 } 4289 }) 4290 Web({ src: 'www.example.com', controller: this.controller }) 4291 } 4292 } 4293} 4294``` 4295 4296### existHttpAuthCredentials 4297 4298static existHttpAuthCredentials(): boolean 4299 4300Checks whether any saved HTTP authentication credentials exist. This API returns the result synchronously. 4301 4302**System capability**: SystemCapability.Web.Webview.Core 4303 4304**Return value** 4305 4306| Type | Description | 4307| ------- | ------------------------------------------------------------ | 4308| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist; returns **false** otherwise.| 4309 4310**Example** 4311 4312```ts 4313// xxx.ets 4314import web_webview from '@ohos.web.webview'; 4315 4316@Entry 4317@Component 4318struct WebComponent { 4319 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4320 4321 build() { 4322 Column() { 4323 Button('existHttpAuthCredentials') 4324 .onClick(() => { 4325 try { 4326 let result = web_webview.WebDataBase.existHttpAuthCredentials(); 4327 } catch (error) { 4328 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 4329 } 4330 }) 4331 Web({ src: 'www.example.com', controller: this.controller }) 4332 } 4333 } 4334} 4335``` 4336 4337### deleteHttpAuthCredentials 4338 4339static deleteHttpAuthCredentials(): void 4340 4341Deletes all HTTP authentication credentials saved in the cache. This API returns the result synchronously. 4342 4343**System capability**: SystemCapability.Web.Webview.Core 4344 4345**Example** 4346 4347```ts 4348// xxx.ets 4349import web_webview from '@ohos.web.webview'; 4350 4351@Entry 4352@Component 4353struct WebComponent { 4354 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4355 4356 build() { 4357 Column() { 4358 Button('deleteHttpAuthCredentials') 4359 .onClick(() => { 4360 try { 4361 web_webview.WebDataBase.deleteHttpAuthCredentials(); 4362 } catch (error) { 4363 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 4364 } 4365 }) 4366 Web({ src: 'www.example.com', controller: this.controller }) 4367 } 4368 } 4369} 4370``` 4371 4372## GeolocationPermissions 4373 4374Implements a **GeolocationPermissions** object. 4375 4376### Required Permissions 4377 4378**ohos.permission.LOCATION**, **ohos.permission.APPROXIMATELY_LOCATION**, and **ohos.permission.LOCATION_IN_BACKGROUND**, which are required for accessing the location information. For details about the permissions, see [@ohos.geolocation (Geolocation)](./js-apis-geolocation.md). 4379 4380### allowGeolocation 4381 4382static allowGeolocation(origin: string): void 4383 4384Allows the specified origin to use the geolocation information. 4385 4386**System capability**: SystemCapability.Web.Webview.Core 4387 4388**Parameters** 4389 4390| Name| Type | Mandatory| Description | 4391| ------ | ------ | ---- | ------------------ | 4392| origin | string | Yes |Index of the origin.| 4393 4394**Error codes** 4395 4396For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4397 4398| ID| Error Message | 4399| -------- | ------------------------------------------------------ | 4400| 17100011 | Invalid origin. | 4401 4402**Example** 4403 4404```ts 4405// xxx.ets 4406import web_webview from '@ohos.web.webview'; 4407 4408@Entry 4409@Component 4410struct WebComponent { 4411 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4412 origin: string = "file:///"; 4413 4414 build() { 4415 Column() { 4416 Button('allowGeolocation') 4417 .onClick(() => { 4418 try { 4419 web_webview.GeolocationPermissions.allowGeolocation(this.origin); 4420 } catch (error) { 4421 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 4422 } 4423 }) 4424 Web({ src: 'www.example.com', controller: this.controller }) 4425 } 4426 } 4427} 4428``` 4429 4430### deleteGeolocation 4431 4432static deleteGeolocation(origin: string): void 4433 4434Clears the geolocation permission status of a specified origin. 4435 4436**System capability**: SystemCapability.Web.Webview.Core 4437 4438**Parameters** 4439 4440| Name| Type | Mandatory| Description | 4441| ------ | ------ | ---- | ------------------ | 4442| origin | string | Yes | Index of the origin.| 4443 4444**Error codes** 4445 4446For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4447 4448| ID| Error Message | 4449| -------- | ------------------------------------------------------ | 4450| 17100011 | Invalid origin. | 4451 4452**Example** 4453 4454```ts 4455// xxx.ets 4456import web_webview from '@ohos.web.webview'; 4457 4458@Entry 4459@Component 4460struct WebComponent { 4461 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4462 origin: string = "file:///"; 4463 4464 build() { 4465 Column() { 4466 Button('deleteGeolocation') 4467 .onClick(() => { 4468 try { 4469 web_webview.GeolocationPermissions.deleteGeolocation(this.origin); 4470 } catch (error) { 4471 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 4472 } 4473 }) 4474 Web({ src: 'www.example.com', controller: this.controller }) 4475 } 4476 } 4477} 4478``` 4479 4480### getAccessibleGeolocation 4481 4482static getAccessibleGeolocation(origin: string, callback: AsyncCallback\<boolean>): void 4483 4484Obtains the geolocation permission status of the specified origin. This API uses an asynchronous callback to return the result. 4485 4486**System capability**: SystemCapability.Web.Webview.Core 4487 4488**Parameters** 4489 4490| Name | Type | Mandatory| Description | 4491| -------- | ---------------------- | ---- | ------------------------------------------------------------ | 4492| origin | string | Yes | Index of the origin. | 4493| callback | AsyncCallback\<boolean> | Yes | Callback used to return the geolocation permission status of the specified origin. If the operation is successful, the value **true** means that the geolocation permission is granted, and **false** means the opposite. If the operation fails, the geolocation permission status of the specified origin is not found.| 4494 4495**Error codes** 4496 4497For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4498 4499| ID| Error Message | 4500| -------- | ------------------------------------------------------ | 4501| 17100011 | Invalid origin. | 4502 4503**Example** 4504 4505```ts 4506// xxx.ets 4507import web_webview from '@ohos.web.webview'; 4508 4509@Entry 4510@Component 4511struct WebComponent { 4512 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4513 origin: string = "file:///"; 4514 4515 build() { 4516 Column() { 4517 Button('getAccessibleGeolocation') 4518 .onClick(() => { 4519 try { 4520 web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin, (error, result) => { 4521 if (error) { 4522 console.log('getAccessibleGeolocationAsync error: ' + JSON.stringify(error)); 4523 return; 4524 } 4525 console.log('getAccessibleGeolocationAsync result: ' + result); 4526 }); 4527 } catch (error) { 4528 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 4529 } 4530 }) 4531 Web({ src: 'www.example.com', controller: this.controller }) 4532 } 4533 } 4534} 4535``` 4536 4537### getAccessibleGeolocation 4538 4539static getAccessibleGeolocation(origin: string): Promise\<boolean> 4540 4541Obtains the geolocation permission status of the specified origin. This API uses a promise to return the result. 4542 4543**System capability**: SystemCapability.Web.Webview.Core 4544 4545**Parameters** 4546 4547| Name| Type| Mandatory| Description | 4548| ------ | -------- | ---- | -------------------- | 4549| origin | string | Yes | Index of the origin.| 4550 4551**Return value** 4552 4553| Type | Description | 4554| ---------------- | ------------------------------------------------------------ | 4555| Promise\<boolean> | Promise used to return the geolocation permission status of the specified origin. If the operation is successful, the value **true** means that the geolocation permission is granted, and **false** means the opposite. If the operation fails, the geolocation permission status of the specified origin is not found.| 4556 4557**Error codes** 4558 4559For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4560 4561| ID| Error Message | 4562| -------- | ------------------------------------------------------ | 4563| 17100011 | Invalid origin. | 4564 4565**Example** 4566 4567```ts 4568// xxx.ets 4569import web_webview from '@ohos.web.webview'; 4570 4571@Entry 4572@Component 4573struct WebComponent { 4574 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4575 origin: string = "file:///"; 4576 4577 build() { 4578 Column() { 4579 Button('getAccessibleGeolocation') 4580 .onClick(() => { 4581 try { 4582 web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin) 4583 .then(result => { 4584 console.log('getAccessibleGeolocationPromise result: ' + result); 4585 }).catch(error => { 4586 console.log('getAccessibleGeolocationPromise error: ' + JSON.stringify(error)); 4587 }); 4588 } catch (error) { 4589 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 4590 } 4591 }) 4592 Web({ src: 'www.example.com', controller: this.controller }) 4593 } 4594 } 4595} 4596``` 4597 4598### getStoredGeolocation 4599 4600static getStoredGeolocation(callback: AsyncCallback\<Array\<string>>): void 4601 4602Obtains the geolocation permission status of all origins. This API uses an asynchronous callback to return the result. 4603 4604**System capability**: SystemCapability.Web.Webview.Core 4605 4606**Parameters** 4607 4608| Name | Type | Mandatory| Description | 4609| -------- | ---------------------------- | ---- | ---------------------------------------- | 4610| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return the geolocation permission status of all origins.| 4611 4612**Example** 4613 4614```ts 4615// xxx.ets 4616import web_webview from '@ohos.web.webview'; 4617 4618@Entry 4619@Component 4620struct WebComponent { 4621 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4622 4623 build() { 4624 Column() { 4625 Button('getStoredGeolocation') 4626 .onClick(() => { 4627 try { 4628 web_webview.GeolocationPermissions.getStoredGeolocation((error, origins) => { 4629 if (error) { 4630 console.log('getStoredGeolocationAsync error: ' + JSON.stringify(error)); 4631 return; 4632 } 4633 let origins_str: string = origins.join(); 4634 console.log('getStoredGeolocationAsync origins: ' + origins_str); 4635 }); 4636 } catch (error) { 4637 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 4638 } 4639 }) 4640 Web({ src: 'www.example.com', controller: this.controller }) 4641 } 4642 } 4643} 4644``` 4645 4646### getStoredGeolocation 4647 4648static getStoredGeolocation(): Promise\<Array\<string>> 4649 4650Obtains the geolocation permission status of all origins. This API uses a promise to return the result. 4651 4652**System capability**: SystemCapability.Web.Webview.Core 4653 4654**Return value** 4655 4656| Type | Description | 4657| ---------------------- | --------------------------------------------------------- | 4658| Promise\<Array\<string>> | Promise used to return the geolocation permission status of all origins.| 4659 4660**Example** 4661 4662```ts 4663// xxx.ets 4664import web_webview from '@ohos.web.webview'; 4665 4666@Entry 4667@Component 4668struct WebComponent { 4669 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4670 4671 build() { 4672 Column() { 4673 Button('getStoredGeolocation') 4674 .onClick(() => { 4675 try { 4676 web_webview.GeolocationPermissions.getStoredGeolocation() 4677 .then(origins => { 4678 let origins_str: string = origins.join(); 4679 console.log('getStoredGeolocationPromise origins: ' + origins_str); 4680 }).catch(error => { 4681 console.log('getStoredGeolocationPromise error: ' + JSON.stringify(error)); 4682 }); 4683 } catch (error) { 4684 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 4685 } 4686 }) 4687 Web({ src: 'www.example.com', controller: this.controller }) 4688 } 4689 } 4690} 4691``` 4692 4693### deleteAllGeolocation 4694 4695static deleteAllGeolocation(): void 4696 4697Clears the geolocation permission status of all sources. 4698 4699**System capability**: SystemCapability.Web.Webview.Core 4700 4701**Example** 4702 4703```ts 4704// xxx.ets 4705import web_webview from '@ohos.web.webview'; 4706 4707@Entry 4708@Component 4709struct WebComponent { 4710 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4711 4712 build() { 4713 Column() { 4714 Button('deleteAllGeolocation') 4715 .onClick(() => { 4716 try { 4717 web_webview.GeolocationPermissions.deleteAllGeolocation(); 4718 } catch (error) { 4719 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 4720 } 4721 }) 4722 Web({ src: 'www.example.com', controller: this.controller }) 4723 } 4724 } 4725} 4726``` 4727## WebHeader 4728Describes the request/response header returned by the **\<Web>** component. 4729 4730**System capability**: SystemCapability.Web.Webview.Core 4731 4732| Name | Type | Readable| Writable|Description | 4733| ----------- | ------ | -----|------|------------------- | 4734| headerKey | string | Yes| Yes| Key of the request/response header. | 4735| headerValue | string | Yes| Yes| Value of the request/response header.| 4736 4737## WebHitTestType 4738 4739**System capability**: SystemCapability.Web.Webview.Core 4740 4741| Name | Value| Description | 4742| ------------- | -- |----------------------------------------- | 4743| EditText | 0 |Editable area. | 4744| Email | 1 |Email address. | 4745| HttpAnchor | 2 |Hyperlink whose **src** is **http**. | 4746| HttpAnchorImg | 3 |Image with a hyperlink, where **src** is **http**.| 4747| Img | 4 |HTML::img tag. | 4748| Map | 5 |Geographical address. | 4749| Phone | 6 |Phone number. | 4750| Unknown | 7 |Unknown content. | 4751 4752## HitTestValue 4753 4754Provides the element information of the area being clicked. For details about the sample code, see **getHitTestValue**. 4755 4756**System capability**: SystemCapability.Web.Webview.Core 4757 4758| Name| Type| Readable| Writable| Description| 4759| ---- | ---- | ---- | ---- |---- | 4760| type | [WebHitTestType](#webhittesttype) | Yes| No| Element type of the area being clicked.| 4761| extra | string | Yes| No|Extra information of the area being clicked. If the area being clicked is an image or a link, the extra information is the URL of the image or link.| 4762 4763## WebMessage 4764 4765Describes the data types supported for [WebMessagePort](#webmessageport). 4766 4767**System capability**: SystemCapability.Web.Webview.Core 4768 4769| Type | Description | 4770| -------- | -------------------------------------- | 4771| string | String type.| 4772| ArrayBuffer | Binary type.| 4773 4774## WebStorageOrigin 4775 4776Provides usage information of the Web SQL Database. 4777 4778**System capability**: SystemCapability.Web.Webview.Core 4779 4780| Name | Type | Readable| Writable| Description| 4781| ------ | ------ | ---- | ---- | ---- | 4782| origin | string | Yes | No| Index of the origin.| 4783| usage | number | Yes | No| Storage usage of the origin. | 4784| quota | number | Yes | No| Storage quota of the origin. | 4785 4786## BackForwardList 4787 4788Provides the historical information list of the current webview. 4789 4790**System capability**: SystemCapability.Web.Webview.Core 4791 4792| Name | Type | Readable| Writable| Description | 4793| ------------ | ------ | ---- | ---- | ------------------------------------------------------------ | 4794| currentIndex | number | Yes | No | Index of the current page in the page history stack. | 4795| size | number | Yes | No | Number of indexes in the history stack. The maximum value is 50. If this value is exceeded, the earliest index will be overwritten.| 4796 4797### getItemAtIndex 4798 4799getItemAtIndex(index: number): HistoryItem 4800 4801Obtains the page record with the specified index in the history stack. 4802 4803**System capability**: SystemCapability.Web.Webview.Core 4804 4805**Parameters** 4806 4807| Name| Type | Mandatory| Description | 4808| ------ | ------ | ---- | ---------------------- | 4809| index | number | Yes | Index of the target page record in the history stack.| 4810 4811**Return value** 4812 4813| Type | Description | 4814| --------------------------- | ------------ | 4815| [HistoryItem](#historyitem) | Historical page record.| 4816 4817**Example** 4818 4819```ts 4820// xxx.ets 4821import web_webview from '@ohos.web.webview'; 4822import image from "@ohos.multimedia.image" 4823 4824@Entry 4825@Component 4826struct WebComponent { 4827 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4828 @State icon: image.PixelMap = undefined; 4829 4830 build() { 4831 Column() { 4832 Button('getBackForwardEntries') 4833 .onClick(() => { 4834 try { 4835 let list = this.controller.getBackForwardEntries(); 4836 let historyItem = list.getItemAtIndex(list.currentIndex); 4837 console.log("HistoryItem: " + JSON.stringify(historyItem)); 4838 this.icon = historyItem.icon; 4839 } catch (error) { 4840 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 4841 } 4842 }) 4843 Web({ src: 'www.example.com', controller: this.controller }) 4844 } 4845 } 4846} 4847``` 4848 4849## HistoryItem 4850 4851Describes a historical page record. 4852 4853**System capability**: SystemCapability.Web.Webview.Core 4854 4855| Name | Type | Readable| Writable| Description | 4856| ------------- | -------------------------------------- | ---- | ---- | ---------------------------- | 4857| icon | [PixelMap](js-apis-image.md#pixelmap7) | Yes | No | **PixelMap** object of the icon on the historical page.| 4858| historyUrl | string | Yes | No | URL of the historical page. | 4859| historyRawUrl | string | Yes | No | Original URL of the historical page. | 4860| title | string | Yes | No | Title of the historical page. | 4861 4862## WebCustomScheme 4863 4864Defines a custom URL scheme. 4865 4866**System capability**: SystemCapability.Web.Webview.Core 4867 4868| Name | Type | Readable| Writable| Description | 4869| -------------- | --------- | ---- | ---- | ---------------------------- | 4870| schemeName | string | Yes | Yes | Name of the custom URL scheme. The value can contain a maximum of 32 characters and include only lowercase letters, digits, periods (.), plus signs (+), and hyphens (-). | 4871| isSupportCORS | boolean | Yes | Yes | Whether to support cross-origin resource sharing (CORS). | 4872| isSupportFetch | boolean | Yes | Yes | Whether to support fetch requests. | 4873