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