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### postMessageEvent 67 68postMessageEvent(message: WebMessage): void 69 70Sends a message. For the complete sample code, see [postMessage](#postmessage). 71 72**System capability**: SystemCapability.Web.Webview.Core 73 74**Parameters** 75 76| Name | Type | Mandatory| Description | 77| ------- | ------ | ---- | :------------- | 78| message | [WebMessage](#webmessage) | Yes | Message to send.| 79 80**Error codes** 81 82For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 83 84| ID| Error Message | 85| -------- | ------------------------------------- | 86| 17100010 | Can not post message using this port. | 87 88**Example** 89 90```ts 91// xxx.ets 92import web_webview from '@ohos.web.webview'; 93import business_error from '@ohos.base'; 94 95@Entry 96@Component 97struct WebComponent { 98 controller: web_webview.WebviewController = new web_webview.WebviewController(); 99 ports: web_webview.WebMessagePort[] = []; 100 101 build() { 102 Column() { 103 Button('postMessageEvent') 104 .onClick(() => { 105 try { 106 this.ports = this.controller.createWebMessagePorts(); 107 this.controller.postMessage('__init_port__', [this.ports[0]], '*'); 108 this.ports[1].postMessageEvent("post message from ets to html5"); 109 } catch (error) { 110 let e: business_error.BusinessError = error as business_error.BusinessError; 111 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 112 } 113 }) 114 Web({ src: 'www.example.com', controller: this.controller }) 115 } 116 } 117} 118``` 119 120### onMessageEvent 121 122onMessageEvent(callback: (result: WebMessage) => void): void 123 124Registers a callback to receive messages from the HTML5 side. For the complete sample code, see [postMessage](#postmessage). 125 126**System capability**: SystemCapability.Web.Webview.Core 127 128**Parameters** 129 130| Name | Type | Mandatory| Description | 131| -------- | -------- | ---- | :------------------- | 132| result | [WebMessage](#webmessage) | Yes | Message received.| 133 134**Error codes** 135 136For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 137 138| ID| Error Message | 139| -------- | ----------------------------------------------- | 140| 17100006 | Can not register message event using this port. | 141 142**Example** 143 144```ts 145// xxx.ets 146import web_webview from '@ohos.web.webview'; 147import business_error from '@ohos.base'; 148 149@Entry 150@Component 151struct WebComponent { 152 controller: web_webview.WebviewController = new web_webview.WebviewController(); 153 ports: web_webview.WebMessagePort[] = []; 154 155 build() { 156 Column() { 157 Button('onMessageEvent') 158 .onClick(() => { 159 try { 160 this.ports = this.controller.createWebMessagePorts(); 161 this.ports[1].onMessageEvent((msg) => { 162 if (typeof(msg) == "string") { 163 console.log("received string message from html5, string is:" + msg); 164 } else if (typeof(msg) == "object") { 165 if (msg instanceof ArrayBuffer) { 166 console.log("received arraybuffer from html5, length is:" + msg.byteLength); 167 } else { 168 console.log("not support"); 169 } 170 } else { 171 console.log("not support"); 172 } 173 }) 174 } catch (error) { 175 let e: business_error.BusinessError = error as business_error.BusinessError; 176 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 177 } 178 }) 179 Web({ src: 'www.example.com', controller: this.controller }) 180 } 181 } 182} 183``` 184 185### isExtentionType<sup>10+</sup> 186 187**System capability**: SystemCapability.Web.Webview.Core 188 189| Name | Type | Readable| Writable| Description | 190| ------------ | ------ | ---- | ---- | ------------------------------------------------| 191| isExtentionType | boolean | Yes | No| Whether to use the extended interface when creating a **WebMessagePort** instance. | 192 193### postMessageEventExt<sup>10+</sup> 194 195postMessageEventExt(message: WebMessageExt): void 196 197Sends a message. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 198 199**System capability**: SystemCapability.Web.Webview.Core 200 201**Parameters** 202 203| Name | Type | Mandatory| Description | 204| ------- | ------ | ---- | :------------- | 205| message | [WebMessageExt](#webmessageext10) | Yes | Message to send.| 206 207**Error codes** 208 209For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 210 211| ID| Error Message | 212| -------- | ------------------------------------- | 213| 17100010 | Can not post message using this port. | 214 215### onMessageEventExt<sup>10+</sup> 216 217onMessageEventExt(callback: (result: WebMessageExt) => void): void 218 219Registers a callback to receive messages from the HTML5 side. 220 221**System capability**: SystemCapability.Web.Webview.Core 222 223**Parameters** 224 225| Name | Type | Mandatory| Description | 226| -------- | -------- | ---- | :------------------- | 227| result | [WebMessageExt](#webmessageext10) | Yes | Message received.| 228 229**Error codes** 230 231For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 232 233| ID| Error Message | 234| -------- | ----------------------------------------------- | 235| 17100006 | Can not register message event using this port. | 236 237**Example** 238 239```ts 240// xxx.ets 241import web_webview from '@ohos.web.webview'; 242import business_error from '@ohos.base'; 243 244// Example of sending messages between an application and a web page: Use the init_web_messageport channel to receive messages from the web page on the application side through port 0 and receive messages from the application on the web page side through port 1. 245@Entry 246@Component 247struct WebComponent { 248 controller: web_webview.WebviewController = new web_webview.WebviewController(); 249 ports: web_webview.WebMessagePort[] = []; 250 nativePort: web_webview.WebMessagePort | null = null; 251 @State msg1: string = ""; 252 @State msg2: string = ""; 253 message: web_webview.WebMessageExt = new web_webview.WebMessageExt(); 254 255 build() { 256 Column() { 257 Text(this.msg1).fontSize(16) 258 Text(this.msg2).fontSize(16) 259 Button('SendToH5') 260 .onClick(() => { 261 // Use the local port to send messages to HTML5. 262 try { 263 console.log("In ArkTS side send true start"); 264 if (this.nativePort) { 265 this.message.setString("helloFromEts"); 266 this.nativePort.postMessageEventExt(this.message); 267 } 268 } 269 catch (error) { 270 let e: business_error.BusinessError = resError as business_error.BusinessError; 271 console.log("In ArkTS side send message catch error:" + e.code + ", msg:" + e.message); 272 } 273 }) 274 275 Web({ src: $rawfile('index.html'), controller: this.controller }) 276 .onPageEnd((e) => { 277 console.log("In ArkTS side message onPageEnd init mesaage channel"); 278 // 1. Create a message port. 279 this.ports = this.controller.createWebMessagePorts(true); 280 // 2. Send port 1 to HTML5. 281 this.controller.postMessage("init_web_messageport", [this.ports[1]], "*"); 282 // 3. Save port 0 to the local host. 283 this.nativePort = this.ports[0]; 284 // 4. Set the callback. 285 this.nativePort.onMessageEventExt((result) => { 286 console.log("In ArkTS side got message"); 287 try { 288 let type = result.getType(); 289 console.log("In ArkTS side getType:" + type); 290 switch (type) { 291 case web_webview.WebMessageType.STRING: { 292 this.msg1 = "result type:" + typeof (result.getString()); 293 this.msg2 = "result getString:" + ((result.getString())); 294 break; 295 } 296 case web_webview.WebMessageType.NUMBER: { 297 this.msg1 = "result type:" + typeof (result.getNumber()); 298 this.msg2 = "result getNumber:" + ((result.getNumber())); 299 break; 300 } 301 case web_webview.WebMessageType.BOOLEAN: { 302 this.msg1 = "result type:" + typeof (result.getBoolean()); 303 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 304 break; 305 } 306 case web_webview.WebMessageType.ARRAY_BUFFER: { 307 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 308 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 309 break; 310 } 311 case web_webview.WebMessageType.ARRAY: { 312 this.msg1 = "result type:" + typeof (result.getArray()); 313 this.msg2 = "result getArray:" + result.getArray(); 314 break; 315 } 316 case web_webview.WebMessageType.ERROR: { 317 this.msg1 = "result type:" + typeof (result.getError()); 318 this.msg2 = "result getError:" + result.getError(); 319 break; 320 } 321 default: { 322 this.msg1 = "default break, type:" + type; 323 break; 324 } 325 } 326 } 327 catch (resError) { 328 let e: business_error.BusinessError = resError as business_error.BusinessError; 329 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 330 } 331 }); 332 }) 333 } 334 } 335} 336``` 337 338HTML file to be loaded: 339```html 340<!--index.html--> 341<!DOCTYPE html> 342<html lang="en-gb"> 343<head> 344 <title>WebView MessagePort Demo</title> 345</head> 346 347<body> 348<h1>Html5 Send and Receive Message</h1> 349<h3 id="msg">Receive string:</h3> 350<h3 id="msg2">Receive arraybuffer:</h3> 351<div style="font-size: 10pt; text-align: center;"> 352 <input type="button" value="Send String" onclick="postStringToApp();" /><br/> 353</div> 354</body> 355<script src="index.js"></script> 356</html> 357``` 358 359```js 360//index.js 361var h5Port; 362window.addEventListener('message', function(event) { 363 if (event.data == 'init_web_messageport') { 364 if(event.ports[0] != null) { 365 h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side. 366 h5Port.onmessage = function(event) { 367 console.log("hwd In html got message"); 368 // 2. Receive the message sent from the eTS side. 369 var result = event.data; 370 console.log("In html got message, typeof: ", typeof(result)); 371 console.log("In html got message, result: ", (result)); 372 if (typeof(result) == "string") { 373 console.log("In html got message, String: ", result); 374 document.getElementById("msg").innerHTML = "String:" + result; 375 } else if (typeof(result) == "number") { 376 console.log("In html side got message, number: ", result); 377 document.getElementById("msg").innerHTML = "Number:" + result; 378 } else if (typeof(result) == "boolean") { 379 console.log("In html side got message, boolean: ", result); 380 document.getElementById("msg").innerHTML = "Boolean:" + result; 381 } else if (typeof(result) == "object") { 382 if (result instanceof ArrayBuffer) { 383 document.getElementById("msg2").innerHTML = "ArrayBuffer:" + result.byteLength; 384 console.log("In html got message, byteLength: ", result.byteLength); 385 } else if (result instanceof Error) { 386 console.log("In html error message, err:" + (result)); 387 console.log("In html error message, typeof err:" + typeof(result)); 388 document.getElementById("msg2").innerHTML = "Error:" + result.name + ", msg:" + result.message; 389 } else if (result instanceof Array) { 390 console.log("In html got message, Array"); 391 console.log("In html got message, Array length:" + result.length); 392 console.log("In html got message, Array[0]:" + (result[0])); 393 console.log("In html got message, typeof Array[0]:" + typeof(result[0])); 394 document.getElementById("msg2").innerHTML = "Array len:" + result.length + ", value:" + result; 395 } else { 396 console.log("In html got message, not any instance of support type"); 397 document.getElementById("msg").innerHTML = "not any instance of support type"; 398 } 399 } else { 400 console.log("In html got message, not support type"); 401 document.getElementById("msg").innerHTML = "not support type"; 402 } 403 } 404 h5Port.onmessageerror = (event) => { 405 console.error(`hwd In html Error receiving message: ${event}`); 406 }; 407 } 408 } 409}) 410 411// Use h5Port to send a message of the string type to the ets side. 412function postStringToApp() { 413 if (h5Port) { 414 console.log("In html send string message"); 415 h5Port.postMessage("hello"); 416 console.log("In html send string message end"); 417 } else { 418 console.error("In html h5port is null, please init first"); 419 } 420} 421``` 422 423### close 424 425close(): void 426 427Closes this message port. To use this API, a message port must first be created using [createWebMessagePorts](#createwebmessageports). 428 429**System capability**: SystemCapability.Web.Webview.Core 430 431**Example** 432 433```ts 434// xxx.ets 435import web_webview from '@ohos.web.webview'; 436import business_error from '@ohos.base'; 437 438@Entry 439@Component 440struct WebComponent { 441 controller: web_webview.WebviewController = new web_webview.WebviewController(); 442 msgPort: web_webview.WebMessagePort[] = []; 443 444 build() { 445 Column() { 446 // Use createWebMessagePorts to create a message port. 447 Button('createWebMessagePorts') 448 .onClick(() => { 449 try { 450 this.msgPort = this.controller.createWebMessagePorts(); 451 console.log("createWebMessagePorts size:" + this.msgPort.length) 452 } catch (error) { 453 let e: business_error.BusinessError = error as business_error.BusinessError; 454 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 455 } 456 }) 457 Button('close') 458 .onClick(() => { 459 try { 460 if (this.msgPort && this.msgPort.length == 2) { 461 this.msgPort[1].close(); 462 } else { 463 console.error("msgPort is null, Please initialize first"); 464 } 465 } catch (error) { 466 let e: business_error.BusinessError = error as business_error.BusinessError; 467 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 468 } 469 }) 470 Web({ src: 'www.example.com', controller: this.controller }) 471 } 472 } 473} 474``` 475 476## WebviewController 477 478Implements 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. 479 480### initializeWebEngine 481 482static initializeWebEngine(): void 483 484Loads 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. 485 486**System capability**: SystemCapability.Web.Webview.Core 487 488**Example** 489 490The following code snippet exemplifies calling this API after the EntryAbility is created. 491 492```ts 493// xxx.ts 494import UIAbility from '@ohos.app.ability.UIAbility'; 495import web_webview from '@ohos.web.webview'; 496import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 497import Want from '@ohos.app.ability.Want'; 498 499export default class EntryAbility extends UIAbility { 500 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 501 console.log("EntryAbility onCreate") 502 web_webview.WebviewController.initializeWebEngine() 503 console.log("EntryAbility onCreate done") 504 } 505} 506``` 507 508### setHttpDns<sup>10+</sup> 509 510static setHttpDns(secureDnsMode:SecureDnsMode, secureDnsConfig:string): void 511 512Sets how the \<Web> component uses HTTPDNS for DNS resolution. 513 514**System capability**: SystemCapability.Web.Webview.Core 515 516**Parameters** 517 518| Name | Type | Mandatory | Description| 519| ------------------ | ------- | ---- | ------------- | 520| secureDnsMode | [SecureDnsMode](#securednsmode10) | Yes | Mode in which HTTPDNS is used.| 521| secureDnsConfig | string | Yes| Information about the HTTPDNS server to use, which must use HTTPS. Only one HTTPDNS server can be configured.| 522 523**Example** 524 525```ts 526// xxx.ts 527import UIAbility from '@ohos.app.ability.UIAbility'; 528import web_webview from '@ohos.web.webview'; 529import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 530import Want from '@ohos.app.ability.Want'; 531import business_error from '@ohos.base'; 532 533export default class EntryAbility extends UIAbility { 534 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 535 console.log("EntryAbility onCreate") 536 try { 537 web_webview.WebviewController.setHttpDns(web_webview.SecureDnsMode.AUTO, "https://example1.test") 538 } catch (error) { 539 let e: business_error.BusinessError = error as business_error.BusinessError; 540 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 541 } 542 543 AppStorage.setOrCreate("abilityWant", want); 544 console.log("EntryAbility onCreate done") 545 } 546} 547``` 548 549### setWebDebuggingAccess 550 551static setWebDebuggingAccess(webDebuggingAccess: boolean): void 552 553Sets whether to enable web debugging. For details, see [Debugging Frontend Pages by Using DevTools](../../web/web-debugging-with-devtools.md). 554 555**System capability**: SystemCapability.Web.Webview.Core 556 557**Parameters** 558 559| Name | Type | Mandatory | Description| 560| ------------------ | ------- | ---- | ------------- | 561| webDebuggingAccess | boolean | Yes | Whether to enable web debugging.| 562 563**Example** 564 565```ts 566// xxx.ets 567import web_webview from '@ohos.web.webview'; 568import business_error from '@ohos.base'; 569 570@Entry 571@Component 572struct WebComponent { 573 controller: web_webview.WebviewController = new web_webview.WebviewController(); 574 575 aboutToAppear(): void { 576 try { 577 web_webview.WebviewController.setWebDebuggingAccess(true); 578 } catch (error) { 579 let e: business_error.BusinessError = error as business_error.BusinessError; 580 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 581 } 582 } 583 584 build() { 585 Column() { 586 Web({ src: 'www.example.com', controller: this.controller }) 587 } 588 } 589} 590``` 591 592### loadUrl 593 594loadUrl(url: string | Resource, headers?: Array\<WebHeader>): void 595 596Loads a specified URL. 597 598**System capability**: SystemCapability.Web.Webview.Core 599 600**Parameters** 601 602| Name | Type | Mandatory| Description | 603| ------- | ---------------- | ---- | :-------------------- | 604| url | string \| Resource | Yes | URL to load. | 605| headers | Array\<[WebHeader](#webheader)> | No | Additional HTTP request header of the URL.| 606 607**Error codes** 608 609For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 610 611| ID| Error Message | 612| -------- | ------------------------------------------------------------ | 613| 17100001 | Init error. The WebviewController must be associated with a Web component. | 614| 17100002 | Invalid url. | 615| 17100003 | Invalid resource path or file type. | 616 617**Example** 618 619```ts 620// xxx.ets 621import web_webview from '@ohos.web.webview'; 622import business_error from '@ohos.base'; 623 624@Entry 625@Component 626struct WebComponent { 627 controller: web_webview.WebviewController = new web_webview.WebviewController(); 628 629 build() { 630 Column() { 631 Button('loadUrl') 632 .onClick(() => { 633 try { 634 // The URL to be loaded is of the string type. 635 this.controller.loadUrl('www.example.com'); 636 } catch (error) { 637 let e: business_error.BusinessError = error as business_error.BusinessError; 638 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 639 } 640 }) 641 Web({ src: 'www.example.com', controller: this.controller }) 642 } 643 } 644} 645``` 646 647```ts 648// xxx.ets 649import web_webview from '@ohos.web.webview'; 650import business_error from '@ohos.base'; 651 652@Entry 653@Component 654struct WebComponent { 655 controller: web_webview.WebviewController = new web_webview.WebviewController(); 656 657 build() { 658 Column() { 659 Button('loadUrl') 660 .onClick(() => { 661 try { 662 // The headers parameter is passed. 663 this.controller.loadUrl('www.example.com', [{ headerKey: "headerKey", headerValue: "headerValue" }]); 664 } catch (error) { 665 let e: business_error.BusinessError = error as business_error.BusinessError; 666 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 667 } 668 }) 669 Web({ src: 'www.example.com', controller: this.controller }) 670 } 671 } 672} 673``` 674 675There are three methods for loading local resource files: 676 6771. Using $rawfile 678```ts 679// xxx.ets 680import web_webview from '@ohos.web.webview'; 681import business_error from '@ohos.base'; 682 683@Entry 684@Component 685struct WebComponent { 686 controller: web_webview.WebviewController = new web_webview.WebviewController(); 687 688 build() { 689 Column() { 690 Button('loadUrl') 691 .onClick(() => { 692 try { 693 // Load a local resource file through $rawfile. 694 this.controller.loadUrl($rawfile('index.html')); 695 } catch (error) { 696 let e: business_error.BusinessError = error as business_error.BusinessError; 697 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 698 } 699 }) 700 Web({ src: 'www.example.com', controller: this.controller }) 701 } 702 } 703} 704``` 705 7062. Using the resources protocol 707```ts 708// xxx.ets 709import web_webview from '@ohos.web.webview'; 710import business_error from '@ohos.base'; 711 712@Entry 713@Component 714struct WebComponent { 715 controller: web_webview.WebviewController = new web_webview.WebviewController(); 716 717 build() { 718 Column() { 719 Button('loadUrl') 720 .onClick(() => { 721 try { 722 // Load local resource files through the resource protocol. 723 this.controller.loadUrl("resource://rawfile/index.html"); 724 } catch (error) { 725 let e: business_error.BusinessError = error as business_error.BusinessError; 726 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 727 } 728 }) 729 Web({ src: 'www.example.com', controller: this.controller }) 730 } 731 } 732} 733``` 734 7353. Using a sandbox path. For details, see the example of loading local resource files in the sandbox in [Web](../arkui-ts/ts-basic-components-web.md#web). 736 737HTML file to be loaded: 738```html 739<!-- index.html --> 740<!DOCTYPE html> 741<html> 742 <body> 743 <p>Hello World</p> 744 </body> 745</html> 746``` 747 748### loadData 749 750loadData(data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string): void 751 752Loads specified data. 753 754**System capability**: SystemCapability.Web.Webview.Core 755 756**Parameters** 757 758| Name | Type | Mandatory| Description | 759| ---------- | ------ | ---- | ------------------------------------------------------------ | 760| data | string | Yes | Character string obtained after being Base64 or URL encoded. | 761| mimeType | string | Yes | Media type (MIME). | 762| encoding | string | Yes | Encoding type, which can be Base64 or URL. | 763| baseUrl | string | No | URL (HTTP/HTTPS/data compliant), which is assigned by the **\<Web>** component to **window.origin**.| 764| 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.| 765 766> **NOTE** 767> 768> To load a local image, you can assign a space to either **baseUrl** or **historyUrl**. For details, see the sample code. 769> In the scenario of loading a local image, **baseUrl** and **historyUrl** cannot be both empty. Otherwise, the image cannot be loaded. 770 771**Error codes** 772 773For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 774 775| ID| Error Message | 776| -------- | ------------------------------------------------------------ | 777| 17100001 | Init error. The WebviewController must be associated with a Web component. | 778| 17100002 | Invalid url. | 779 780**Example** 781 782```ts 783// xxx.ets 784import web_webview from '@ohos.web.webview'; 785import business_error from '@ohos.base'; 786 787@Entry 788@Component 789struct WebComponent { 790 controller: web_webview.WebviewController = new web_webview.WebviewController(); 791 792 build() { 793 Column() { 794 Button('loadData') 795 .onClick(() => { 796 try { 797 this.controller.loadData( 798 "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>", 799 "text/html", 800 "UTF-8" 801 ); 802 } catch (error) { 803 let e: business_error.BusinessError = error as business_error.BusinessError; 804 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 805 } 806 }) 807 Web({ src: 'www.example.com', controller: this.controller }) 808 } 809 } 810} 811``` 812 813Example of loading local resource: 814```ts 815// xxx.ets 816import web_webview from '@ohos.web.webview'; 817import business_error from '@ohos.base'; 818 819@Entry 820@Component 821struct WebComponent { 822 controller: web_webview.WebviewController = new web_webview.WebviewController(); 823 updataContent: string = '<body><div><image src=resource://rawfile/xxx.png alt="image -- end" width="500" height="250"></image></div></body>' 824 825 build() { 826 Column() { 827 Button('loadData') 828 .onClick(() => { 829 try { 830 this.controller.loadData(this.updataContent, "text/html", "UTF-8", " ", " "); 831 } catch (error) { 832 let e: business_error.BusinessError = error as business_error.BusinessError; 833 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 834 } 835 }) 836 Web({ src: 'www.example.com', controller: this.controller }) 837 } 838 } 839} 840``` 841 842### accessForward 843 844accessForward(): boolean 845 846Checks whether moving to the next page can be performed on the current page. 847 848**System capability**: SystemCapability.Web.Webview.Core 849 850**Return value** 851 852| Type | Description | 853| ------- | --------------------------------- | 854| boolean | Returns **true** if moving to the next page can be performed on the current page; returns **false** otherwise.| 855 856**Error codes** 857 858For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 859 860| ID| Error Message | 861| -------- | ------------------------------------------------------------ | 862| 17100001 | Init error. The WebviewController must be associated with a Web component. | 863 864**Example** 865 866```ts 867// xxx.ets 868import web_webview from '@ohos.web.webview'; 869import business_error from '@ohos.base'; 870 871@Entry 872@Component 873struct WebComponent { 874 controller: web_webview.WebviewController = new web_webview.WebviewController(); 875 876 build() { 877 Column() { 878 Button('accessForward') 879 .onClick(() => { 880 try { 881 let result = this.controller.accessForward(); 882 console.log('result:' + result); 883 } catch (error) { 884 let e: business_error.BusinessError = error as business_error.BusinessError; 885 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 886 } 887 }) 888 Web({ src: 'www.example.com', controller: this.controller }) 889 } 890 } 891} 892``` 893 894### forward 895 896forward(): void 897 898Moves to the next page based on the history stack. This API is generally used together with **accessForward**. 899 900**System capability**: SystemCapability.Web.Webview.Core 901 902**Error codes** 903 904For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 905 906| ID| Error Message | 907| -------- | ------------------------------------------------------------ | 908| 17100001 | Init error. The WebviewController must be associated with a Web component. | 909 910**Example** 911 912```ts 913// xxx.ets 914import web_webview from '@ohos.web.webview'; 915import business_error from '@ohos.base'; 916 917@Entry 918@Component 919struct WebComponent { 920 controller: web_webview.WebviewController = new web_webview.WebviewController(); 921 922 build() { 923 Column() { 924 Button('forward') 925 .onClick(() => { 926 try { 927 this.controller.forward(); 928 } catch (error) { 929 let e: business_error.BusinessError = error as business_error.BusinessError; 930 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 931 } 932 }) 933 Web({ src: 'www.example.com', controller: this.controller }) 934 } 935 } 936} 937``` 938 939### accessBackward 940 941accessBackward(): boolean 942 943Checks whether moving to the previous page can be performed on the current page. 944 945**System capability**: SystemCapability.Web.Webview.Core 946 947**Return value** 948 949| Type | Description | 950| ------- | -------------------------------- | 951| boolean | Returns **true** if moving to the previous page can be performed on the current page; returns **false** otherwise.| 952 953**Error codes** 954 955For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 956 957| ID| Error Message | 958| -------- | ------------------------------------------------------------ | 959| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 960 961**Example** 962 963```ts 964// xxx.ets 965import web_webview from '@ohos.web.webview'; 966import business_error from '@ohos.base'; 967 968@Entry 969@Component 970struct WebComponent { 971 controller: web_webview.WebviewController = new web_webview.WebviewController(); 972 973 build() { 974 Column() { 975 Button('accessBackward') 976 .onClick(() => { 977 try { 978 let result = this.controller.accessBackward(); 979 console.log('result:' + result); 980 } catch (error) { 981 let e: business_error.BusinessError = error as business_error.BusinessError; 982 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 983 } 984 }) 985 Web({ src: 'www.example.com', controller: this.controller }) 986 } 987 } 988} 989``` 990 991### backward 992 993backward(): void 994 995Moves to the previous page based on the history stack. This API is generally used together with **accessBackward**. 996 997**System capability**: SystemCapability.Web.Webview.Core 998 999**Error codes** 1000 1001For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1002 1003| ID| Error Message | 1004| -------- | ------------------------------------------------------------ | 1005| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1006 1007**Example** 1008 1009```ts 1010// xxx.ets 1011import web_webview from '@ohos.web.webview'; 1012import business_error from '@ohos.base'; 1013 1014@Entry 1015@Component 1016struct WebComponent { 1017 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1018 1019 build() { 1020 Column() { 1021 Button('backward') 1022 .onClick(() => { 1023 try { 1024 this.controller.backward(); 1025 } catch (error) { 1026 let e: business_error.BusinessError = error as business_error.BusinessError; 1027 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1028 } 1029 }) 1030 Web({ src: 'www.example.com', controller: this.controller }) 1031 } 1032 } 1033} 1034``` 1035 1036### onActive 1037 1038onActive(): void 1039 1040Invoked to instruct the **\<Web>** component to enter the active foreground state. 1041 1042**System capability**: SystemCapability.Web.Webview.Core 1043 1044**Error codes** 1045 1046For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1047 1048| ID| Error Message | 1049| -------- | ------------------------------------------------------------ | 1050| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1051 1052**Example** 1053 1054```ts 1055// xxx.ets 1056import web_webview from '@ohos.web.webview'; 1057import business_error from '@ohos.base'; 1058 1059@Entry 1060@Component 1061struct WebComponent { 1062 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1063 1064 build() { 1065 Column() { 1066 Button('onActive') 1067 .onClick(() => { 1068 try { 1069 this.controller.onActive(); 1070 } catch (error) { 1071 let e: business_error.BusinessError = error as business_error.BusinessError; 1072 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1073 } 1074 }) 1075 Web({ src: 'www.example.com', controller: this.controller }) 1076 } 1077 } 1078} 1079``` 1080 1081### onInactive 1082 1083onInactive(): void 1084 1085Invoked to instruct the **\<Web>** component to enter the inactive state. 1086 1087**System capability**: SystemCapability.Web.Webview.Core 1088 1089**Error codes** 1090 1091For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1092 1093| ID| Error Message | 1094| -------- | ------------------------------------------------------------ | 1095| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1096 1097**Example** 1098 1099```ts 1100// xxx.ets 1101import web_webview from '@ohos.web.webview'; 1102import business_error from '@ohos.base'; 1103 1104@Entry 1105@Component 1106struct WebComponent { 1107 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1108 1109 build() { 1110 Column() { 1111 Button('onInactive') 1112 .onClick(() => { 1113 try { 1114 this.controller.onInactive(); 1115 } catch (error) { 1116 let e: business_error.BusinessError = error as business_error.BusinessError; 1117 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1118 } 1119 }) 1120 Web({ src: 'www.example.com', controller: this.controller }) 1121 } 1122 } 1123} 1124``` 1125 1126### refresh 1127refresh(): void 1128 1129Invoked to instruct the **\<Web>** component to refresh the web page. 1130 1131**System capability**: SystemCapability.Web.Webview.Core 1132 1133**Error codes** 1134 1135For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1136 1137| ID| Error Message | 1138| -------- | ------------------------------------------------------------ | 1139| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1140 1141**Example** 1142 1143```ts 1144// xxx.ets 1145import web_webview from '@ohos.web.webview'; 1146import business_error from '@ohos.base'; 1147 1148@Entry 1149@Component 1150struct WebComponent { 1151 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1152 1153 build() { 1154 Column() { 1155 Button('refresh') 1156 .onClick(() => { 1157 try { 1158 this.controller.refresh(); 1159 } catch (error) { 1160 let e: business_error.BusinessError = error as business_error.BusinessError; 1161 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1162 } 1163 }) 1164 Web({ src: 'www.example.com', controller: this.controller }) 1165 } 1166 } 1167} 1168``` 1169 1170### accessStep 1171 1172accessStep(step: number): boolean 1173 1174Checks whether a specific number of steps forward or backward can be performed on the current page. 1175 1176**System capability**: SystemCapability.Web.Webview.Core 1177 1178**Parameters** 1179 1180| Name| Type| Mandatory| Description | 1181| ------ | -------- | ---- | ------------------------------------------ | 1182| step | number | Yes | Number of the steps to take. A positive number means to move forward, and a negative number means to move backward.| 1183 1184**Return value** 1185 1186| Type | Description | 1187| ------- | ------------------ | 1188| boolean | Whether moving forward or backward is performed on the current page.| 1189 1190**Error codes** 1191 1192For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1193 1194| ID| Error Message | 1195| -------- | ------------------------------------------------------------ | 1196| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1197 1198**Example** 1199 1200```ts 1201// xxx.ets 1202import web_webview from '@ohos.web.webview'; 1203import business_error from '@ohos.base'; 1204 1205@Entry 1206@Component 1207struct WebComponent { 1208 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1209 @State steps: number = 2; 1210 1211 build() { 1212 Column() { 1213 Button('accessStep') 1214 .onClick(() => { 1215 try { 1216 let result = this.controller.accessStep(this.steps); 1217 console.log('result:' + result); 1218 } catch (error) { 1219 let e: business_error.BusinessError = error as business_error.BusinessError; 1220 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1221 } 1222 }) 1223 Web({ src: 'www.example.com', controller: this.controller }) 1224 } 1225 } 1226} 1227``` 1228 1229### clearHistory 1230 1231clearHistory(): void 1232 1233Clears the browsing history. 1234 1235**System capability**: SystemCapability.Web.Webview.Core 1236 1237**Error codes** 1238 1239For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1240 1241| ID| Error Message | 1242| -------- | ------------------------------------------------------------ | 1243| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1244 1245**Example** 1246 1247```ts 1248// xxx.ets 1249import web_webview from '@ohos.web.webview'; 1250import business_error from '@ohos.base'; 1251 1252@Entry 1253@Component 1254struct WebComponent { 1255 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1256 1257 build() { 1258 Column() { 1259 Button('clearHistory') 1260 .onClick(() => { 1261 try { 1262 this.controller.clearHistory(); 1263 } catch (error) { 1264 let e: business_error.BusinessError = error as business_error.BusinessError; 1265 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1266 } 1267 }) 1268 Web({ src: 'www.example.com', controller: this.controller }) 1269 } 1270 } 1271} 1272``` 1273 1274### getHitTest 1275 1276getHitTest(): WebHitTestType 1277 1278Obtains the element type of the area being clicked. 1279 1280**System capability**: SystemCapability.Web.Webview.Core 1281 1282**Return value** 1283 1284| Type | Description | 1285| ------------------------------------------------------------ | ---------------------- | 1286| [WebHitTestType](#webhittesttype)| Element type of the area being clicked.| 1287 1288**Error codes** 1289 1290For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1291 1292| ID| Error Message | 1293| -------- | ------------------------------------------------------------ | 1294| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1295 1296**Example** 1297 1298```ts 1299// xxx.ets 1300import web_webview from '@ohos.web.webview'; 1301import business_error from '@ohos.base'; 1302 1303@Entry 1304@Component 1305struct WebComponent { 1306 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1307 1308 build() { 1309 Column() { 1310 Button('getHitTest') 1311 .onClick(() => { 1312 try { 1313 let hitTestType = this.controller.getHitTest(); 1314 console.log("hitTestType: " + hitTestType); 1315 } catch (error) { 1316 let e: business_error.BusinessError = error as business_error.BusinessError; 1317 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1318 } 1319 }) 1320 Web({ src: 'www.example.com', controller: this.controller }) 1321 } 1322 } 1323} 1324``` 1325 1326### registerJavaScriptProxy 1327 1328registerJavaScriptProxy(object: object, name: string, methodList: Array\<string>): void 1329 1330Registers 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. 1331 1332**System capability**: SystemCapability.Web.Webview.Core 1333 1334**Parameters** 1335 1336| Name | Type | Mandatory| Description | 1337| ---------- | -------------- | ---- | ------------------------------------------------------------ | 1338| 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.| 1339| 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.| 1340| methodList | Array\<string> | Yes | Methods of the JavaScript object to be registered at the application side. | 1341 1342**Error codes** 1343 1344For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1345 1346| ID| Error Message | 1347| -------- | ------------------------------------------------------------ | 1348| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1349 1350**Example** 1351 1352```ts 1353// xxx.ets 1354import web_webview from '@ohos.web.webview'; 1355import business_error from '@ohos.base'; 1356 1357class testObj { 1358 constructor() { 1359 } 1360 1361 test(): string { 1362 return "ArkUI Web Component"; 1363 } 1364 1365 toString(): void { 1366 console.log('Web Component toString'); 1367 } 1368} 1369 1370@Entry 1371@Component 1372struct Index { 1373 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1374 @State testObjtest: testObj = new testObj(); 1375 1376 build() { 1377 Column() { 1378 Button('refresh') 1379 .onClick(() => { 1380 try { 1381 this.controller.refresh(); 1382 } catch (error) { 1383 let e: business_error.BusinessError = error as business_error.BusinessError; 1384 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1385 } 1386 }) 1387 Button('Register JavaScript To Window') 1388 .onClick(() => { 1389 try { 1390 this.controller.registerJavaScriptProxy(this.testObjtest, "objName", ["test", "toString"]); 1391 } catch (error) { 1392 let e: business_error.BusinessError = error as business_error.BusinessError; 1393 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1394 } 1395 }) 1396 Web({ src: $rawfile('index.html'), controller: this.controller }) 1397 .javaScriptAccess(true) 1398 } 1399 } 1400} 1401``` 1402 1403HTML file to be loaded: 1404```html 1405<!-- index.html --> 1406<!DOCTYPE html> 1407<html> 1408 <meta charset="utf-8"> 1409 <body> 1410 <button type="button" onclick="htmlTest()">Click Me!</button> 1411 <p id="demo"></p> 1412 </body> 1413 <script type="text/javascript"> 1414 function htmlTest() { 1415 let str=objName.test(); 1416 document.getElementById("demo").innerHTML=str; 1417 console.log('objName.test result:'+ str) 1418 } 1419</script> 1420</html> 1421``` 1422 1423### runJavaScript 1424 1425runJavaScript(script: string, callback : AsyncCallback\<string>): void 1426 1427Executes 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**. 1428 1429**System capability**: SystemCapability.Web.Webview.Core 1430 1431**Parameters** 1432 1433| Name | Type | Mandatory| Description | 1434| -------- | -------------------- | ---- | ---------------------------- | 1435| script | string | Yes | JavaScript script. | 1436| 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.| 1437 1438**Error codes** 1439 1440For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1441 1442| ID| Error Message | 1443| -------- | ------------------------------------------------------------ | 1444| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1445 1446**Example** 1447 1448```ts 1449import web_webview from '@ohos.web.webview'; 1450import business_error from '@ohos.base'; 1451 1452@Entry 1453@Component 1454struct WebComponent { 1455 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1456 @State webResult: string = '' 1457 1458 build() { 1459 Column() { 1460 Text(this.webResult).fontSize(20) 1461 Web({ src: $rawfile('index.html'), controller: this.controller }) 1462 .javaScriptAccess(true) 1463 .onPageEnd(e => { 1464 try { 1465 this.controller.runJavaScript( 1466 'test()', 1467 (error, result) => { 1468 if (error) { 1469 console.info(`run JavaScript error: ` + JSON.stringify(error)) 1470 return; 1471 } 1472 if (result) { 1473 this.webResult = result 1474 console.info(`The test() return value is: ${result}`) 1475 } 1476 }); 1477 if (e) { 1478 console.info('url: ', e.url); 1479 } 1480 } catch (error) { 1481 let e: business_error.BusinessError = error as business_error.BusinessError; 1482 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1483 } 1484 }) 1485 } 1486 } 1487} 1488``` 1489 1490HTML file to be loaded: 1491```html 1492<!-- index.html --> 1493<!DOCTYPE html> 1494<html> 1495 <meta charset="utf-8"> 1496 <body> 1497 Hello world! 1498 </body> 1499 <script type="text/javascript"> 1500 function test() { 1501 console.log('Ark WebComponent') 1502 return "This value is from index.html" 1503 } 1504 </script> 1505</html> 1506``` 1507 1508### runJavaScript 1509 1510runJavaScript(script: string): Promise\<string> 1511 1512Executes 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**. 1513 1514**System capability**: SystemCapability.Web.Webview.Core 1515 1516**Parameters** 1517 1518| Name| Type| Mandatory| Description | 1519| ------ | -------- | ---- | ---------------- | 1520| script | string | Yes | JavaScript script.| 1521 1522**Return value** 1523 1524| Type | Description | 1525| --------------- | --------------------------------------------------- | 1526| Promise\<string> | Promise used to return the result if the operation is successful and null otherwise.| 1527 1528**Error codes** 1529 1530For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1531 1532| ID| Error Message | 1533| -------- | ------------------------------------------------------------ | 1534| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1535 1536**Example** 1537 1538```ts 1539// xxx.ets 1540import web_webview from '@ohos.web.webview'; 1541import business_error from '@ohos.base'; 1542 1543@Entry 1544@Component 1545struct WebComponent { 1546 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1547 1548 build() { 1549 Column() { 1550 Web({ src: $rawfile('index.html'), controller: this.controller }) 1551 .javaScriptAccess(true) 1552 .onPageEnd(e => { 1553 try { 1554 this.controller.runJavaScript('test()') 1555 .then((result) => { 1556 console.log('result: ' + result); 1557 }) 1558 .catch((error: business_error.BusinessError) => { 1559 console.error("error: " + error); 1560 }) 1561 if (e) { 1562 console.info('url: ', e.url); 1563 } 1564 } catch (error) { 1565 let e: business_error.BusinessError = error as business_error.BusinessError; 1566 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1567 } 1568 }) 1569 } 1570 } 1571} 1572``` 1573 1574HTML file to be loaded: 1575```html 1576<!-- index.html --> 1577<!DOCTYPE html> 1578<html> 1579 <meta charset="utf-8"> 1580 <body> 1581 Hello world! 1582 </body> 1583 <script type="text/javascript"> 1584 function test() { 1585 console.log('Ark WebComponent') 1586 return "This value is from index.html" 1587 } 1588 </script> 1589</html> 1590``` 1591 1592### runJavaScriptExt<sup>10+</sup> 1593 1594runJavaScriptExt(script: string, callback : AsyncCallback\<JsMessageExt>): void 1595 1596Executes a JavaScript script. This API uses an asynchronous callback to return the script execution result. **runJavaScriptExt** can be invoked only after **loadUrl** is executed. For example, it can be invoked in **onPageEnd**. 1597 1598**System capability**: SystemCapability.Web.Webview.Core 1599 1600**Parameters** 1601 1602| Name | Type | Mandatory| Description | 1603| -------- | -------------------- | ---- | ---------------------------- | 1604| script | string | Yes | JavaScript script. | 1605| callback | AsyncCallback\<[JsMessageExt](#jsmessageext10)\> | Yes | Callback used to return the result.| 1606 1607**Error codes** 1608 1609For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1610 1611| ID| Error Message | 1612| -------- | ------------------------------------------------------------ | 1613| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1614 1615**Example** 1616 1617```ts 1618import web_webview from '@ohos.web.webview'; 1619import business_error from '@ohos.base'; 1620 1621@Entry 1622@Component 1623struct WebComponent { 1624 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1625 @State msg1: string = '' 1626 @State msg2: string = '' 1627 1628 build() { 1629 Column() { 1630 Text(this.msg1).fontSize(20) 1631 Text(this.msg2).fontSize(20) 1632 Web({ src: $rawfile('index.html'), controller: this.controller }) 1633 .javaScriptAccess(true) 1634 .onPageEnd(e => { 1635 try { 1636 this.controller.runJavaScriptExt( 1637 'test()', 1638 (error, result) => { 1639 if (error) { 1640 console.info(`run JavaScript error: ` + JSON.stringify(error)) 1641 return; 1642 } 1643 if (result) { 1644 try { 1645 let type = result.getType(); 1646 switch (type) { 1647 case web_webview.JsMessageType.STRING: { 1648 this.msg1 = "result type:" + typeof (result.getString()); 1649 this.msg2 = "result getString:" + ((result.getString())); 1650 break; 1651 } 1652 case web_webview.JsMessageType.NUMBER: { 1653 this.msg1 = "result type:" + typeof (result.getNumber()); 1654 this.msg2 = "result getNumber:" + ((result.getNumber())); 1655 break; 1656 } 1657 case web_webview.JsMessageType.BOOLEAN: { 1658 this.msg1 = "result type:" + typeof (result.getBoolean()); 1659 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 1660 break; 1661 } 1662 case web_webview.JsMessageType.ARRAY_BUFFER: { 1663 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 1664 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 1665 break; 1666 } 1667 case web_webview.JsMessageType.ARRAY: { 1668 this.msg1 = "result type:" + typeof (result.getArray()); 1669 this.msg2 = "result getArray:" + result.getArray(); 1670 break; 1671 } 1672 default: { 1673 this.msg1 = "default break, type:" + type; 1674 break; 1675 } 1676 } 1677 } 1678 catch (resError) { 1679 let e: business_error.BusinessError = resError as business_error.BusinessError; 1680 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1681 } 1682 } 1683 }); 1684 if (e) { 1685 console.info('url: ', e.url); 1686 } 1687 } catch (error) { 1688 let e: business_error.BusinessError = error as business_error.BusinessError; 1689 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1690 } 1691 }) 1692 } 1693 } 1694} 1695``` 1696 1697HTML file to be loaded: 1698```html 1699<!-- index.html --> 1700<!DOCTYPE html> 1701<html lang="en-gb"> 1702<body> 1703<h1>run JavaScript Ext demo</h1> 1704</body> 1705<script type="text/javascript"> 1706function test() { 1707 return "hello, world"; 1708} 1709</script> 1710</html> 1711``` 1712 1713### runJavaScriptExt<sup>10+</sup> 1714 1715runJavaScriptExt(script: string): Promise\<JsMessageExt> 1716 1717Executes a JavaScript script. This API uses a promise to return the script execution result. **runJavaScriptExt** can be invoked only after **loadUrl** is executed. For example, it can be invoked in **onPageEnd**. 1718 1719**System capability**: SystemCapability.Web.Webview.Core 1720 1721**Parameters** 1722 1723| Name| Type| Mandatory| Description | 1724| ------ | -------- | ---- | ---------------- | 1725| script | string | Yes | JavaScript script.| 1726 1727**Return value** 1728 1729| Type | Description | 1730| --------------- | --------------------------------------------------- | 1731| Promise\<[JsMessageExt](#jsmessageext10)> | Promise used to return the script execution result.| 1732 1733**Error codes** 1734 1735For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1736 1737| ID| Error Message | 1738| -------- | ------------------------------------------------------------ | 1739| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1740 1741**Example** 1742 1743```ts 1744// xxx.ets 1745import web_webview from '@ohos.web.webview'; 1746import business_error from '@ohos.base'; 1747 1748@Entry 1749@Component 1750struct WebComponent { 1751 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1752 @State webResult: string = ''; 1753 @State msg1: string = '' 1754 @State msg2: string = '' 1755 1756 build() { 1757 Column() { 1758 Text(this.webResult).fontSize(20) 1759 Text(this.msg1).fontSize(20) 1760 Text(this.msg2).fontSize(20) 1761 Web({ src: $rawfile('index.html'), controller: this.controller }) 1762 .javaScriptAccess(true) 1763 .onPageEnd(e => { 1764 this.controller.runJavaScriptExt('test()') 1765 .then((result) => { 1766 try { 1767 let type = result.getType(); 1768 switch (type) { 1769 case web_webview.JsMessageType.STRING: { 1770 this.msg1 = "result type:" + typeof (result.getString()); 1771 this.msg2 = "result getString:" + ((result.getString())); 1772 break; 1773 } 1774 case web_webview.JsMessageType.NUMBER: { 1775 this.msg1 = "result type:" + typeof (result.getNumber()); 1776 this.msg2 = "result getNumber:" + ((result.getNumber())); 1777 break; 1778 } 1779 case web_webview.JsMessageType.BOOLEAN: { 1780 this.msg1 = "result type:" + typeof (result.getBoolean()); 1781 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 1782 break; 1783 } 1784 case web_webview.JsMessageType.ARRAY_BUFFER: { 1785 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 1786 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 1787 break; 1788 } 1789 case web_webview.JsMessageType.ARRAY: { 1790 this.msg1 = "result type:" + typeof (result.getArray()); 1791 this.msg2 = "result getArray:" + result.getArray(); 1792 break; 1793 } 1794 default: { 1795 this.msg1 = "default break, type:" + type; 1796 break; 1797 } 1798 } 1799 } 1800 catch (resError) { 1801 let e: business_error.BusinessError = resError as business_error.BusinessError; 1802 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1803 } 1804 }) 1805 .catch((error: business_error.BusinessError) => { 1806 console.error("error: " + error); 1807 }) 1808 }) 1809 } 1810 } 1811} 1812``` 1813 1814HTML file to be loaded: 1815```html 1816<!-- index.html --> 1817<!DOCTYPE html> 1818<html lang="en-gb"> 1819<body> 1820<h1>run JavaScript Ext demo</h1> 1821</body> 1822<script type="text/javascript"> 1823function test() { 1824 return "hello, world"; 1825} 1826</script> 1827</html> 1828``` 1829 1830### deleteJavaScriptRegister 1831 1832deleteJavaScriptRegister(name: string): void 1833 1834Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. The deletion takes effect immediately without invoking the [refresh](#refresh) API. 1835 1836**System capability**: SystemCapability.Web.Webview.Core 1837 1838**Parameters** 1839 1840| Name| Type| Mandatory| Description | 1841| ------ | -------- | ---- | ---- | 1842| 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.| 1843 1844**Error codes** 1845 1846For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1847 1848| ID| Error Message | 1849| -------- | ------------------------------------------------------------ | 1850| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1851| 17100008 | Cannot delete JavaScriptProxy. | 1852 1853**Example** 1854 1855```ts 1856// xxx.ets 1857import web_webview from '@ohos.web.webview'; 1858import business_error from '@ohos.base'; 1859 1860@Entry 1861@Component 1862struct WebComponent { 1863 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1864 @State name: string = 'Object'; 1865 1866 build() { 1867 Column() { 1868 Button('deleteJavaScriptRegister') 1869 .onClick(() => { 1870 try { 1871 this.controller.deleteJavaScriptRegister(this.name); 1872 } catch (error) { 1873 let e: business_error.BusinessError = error as business_error.BusinessError; 1874 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1875 } 1876 }) 1877 Web({ src: 'www.example.com', controller: this.controller }) 1878 } 1879 } 1880} 1881``` 1882 1883### zoom 1884 1885zoom(factor: number): void 1886 1887Zooms in or out of this web page. 1888 1889**System capability**: SystemCapability.Web.Webview.Core 1890 1891**Parameters** 1892 1893| Name| Type| Mandatory| Description| 1894| ------ | -------- | ---- | ------------------------------------------------------------ | 1895| factor | number | Yes | Relative zoom ratio. The value must be greater than 0. The value **1** indicates that the page is not zoomed. A value smaller than **1** indicates zoom-out, and a value greater than **1** indicates zoom-in.| 1896 1897**Error codes** 1898 1899For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1900 1901| ID| Error Message | 1902| -------- | ------------------------------------------------------------ | 1903| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1904| 17100004 | Function not enable. | 1905 1906**Example** 1907 1908```ts 1909// xxx.ets 1910import web_webview from '@ohos.web.webview'; 1911import business_error from '@ohos.base'; 1912 1913@Entry 1914@Component 1915struct WebComponent { 1916 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1917 @State factor: number = 1; 1918 1919 build() { 1920 Column() { 1921 Button('zoom') 1922 .onClick(() => { 1923 try { 1924 this.controller.zoom(this.factor); 1925 } catch (error) { 1926 let e: business_error.BusinessError = error as business_error.BusinessError; 1927 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1928 } 1929 }) 1930 Web({ src: 'www.example.com', controller: this.controller }) 1931 } 1932 } 1933} 1934``` 1935 1936### searchAllAsync 1937 1938searchAllAsync(searchString: string): void 1939 1940Searches 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). 1941 1942**System capability**: SystemCapability.Web.Webview.Core 1943 1944**Parameters** 1945 1946| Name | Type| Mandatory| Description | 1947| ------------ | -------- | ---- | -------------- | 1948| searchString | string | Yes | Search keyword.| 1949 1950**Error codes** 1951 1952For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1953 1954| ID| Error Message | 1955| -------- | ------------------------------------------------------------ | 1956| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 1957 1958**Example** 1959 1960```ts 1961// xxx.ets 1962import web_webview from '@ohos.web.webview'; 1963import business_error from '@ohos.base'; 1964 1965@Entry 1966@Component 1967struct WebComponent { 1968 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1969 @State searchString: string = "xxx"; 1970 1971 build() { 1972 Column() { 1973 Button('searchString') 1974 .onClick(() => { 1975 try { 1976 this.controller.searchAllAsync(this.searchString); 1977 } catch (error) { 1978 let e: business_error.BusinessError = error as business_error.BusinessError; 1979 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1980 } 1981 }) 1982 Web({ src: 'www.example.com', controller: this.controller }) 1983 .onSearchResultReceive(ret => { 1984 if (ret) { 1985 console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal + 1986 "[total]" + ret.numberOfMatches + "[isDone]" + ret.isDoneCounting); 1987 } 1988 }) 1989 } 1990 } 1991} 1992``` 1993 1994### clearMatches 1995 1996clearMatches(): void 1997 1998Clears the matches found through [searchAllAsync](#searchallasync). 1999 2000**System capability**: SystemCapability.Web.Webview.Core 2001 2002**Error codes** 2003 2004For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2005 2006| ID| Error Message | 2007| -------- | ------------------------------------------------------------ | 2008| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 2009 2010**Example** 2011 2012```ts 2013// xxx.ets 2014import web_webview from '@ohos.web.webview'; 2015import business_error from '@ohos.base'; 2016 2017@Entry 2018@Component 2019struct WebComponent { 2020 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2021 2022 build() { 2023 Column() { 2024 Button('clearMatches') 2025 .onClick(() => { 2026 try { 2027 this.controller.clearMatches(); 2028 } catch (error) { 2029 let e: business_error.BusinessError = error as business_error.BusinessError; 2030 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2031 } 2032 }) 2033 Web({ src: 'www.example.com', controller: this.controller }) 2034 } 2035 } 2036} 2037``` 2038 2039### searchNext 2040 2041searchNext(forward: boolean): void 2042 2043Searches for and highlights the next match. 2044 2045**System capability**: SystemCapability.Web.Webview.Core 2046 2047**Parameters** 2048 2049| Name | Type| Mandatory| Description | 2050| ------- | -------- | ---- | ---------------------- | 2051| forward | boolean | Yes | Whether to search forward.| 2052 2053**Error codes** 2054 2055For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2056 2057| ID| Error Message | 2058| -------- | ------------------------------------------------------------ | 2059| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 2060 2061**Example** 2062 2063```ts 2064// xxx.ets 2065import web_webview from '@ohos.web.webview'; 2066import business_error from '@ohos.base'; 2067 2068@Entry 2069@Component 2070struct WebComponent { 2071 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2072 2073 build() { 2074 Column() { 2075 Button('searchNext') 2076 .onClick(() => { 2077 try { 2078 this.controller.searchNext(true); 2079 } catch (error) { 2080 let e: business_error.BusinessError = error as business_error.BusinessError; 2081 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2082 } 2083 }) 2084 Web({ src: 'www.example.com', controller: this.controller }) 2085 } 2086 } 2087} 2088``` 2089 2090### clearSslCache 2091 2092clearSslCache(): void 2093 2094Clears the user operation corresponding to the SSL certificate error event recorded by the **\<Web>** component. 2095 2096**System capability**: SystemCapability.Web.Webview.Core 2097 2098**Error codes** 2099 2100For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2101 2102| ID| Error Message | 2103| -------- | ------------------------------------------------------------ | 2104| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 2105 2106**Example** 2107 2108```ts 2109// xxx.ets 2110import web_webview from '@ohos.web.webview'; 2111import business_error from '@ohos.base'; 2112 2113@Entry 2114@Component 2115struct WebComponent { 2116 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2117 2118 build() { 2119 Column() { 2120 Button('clearSslCache') 2121 .onClick(() => { 2122 try { 2123 this.controller.clearSslCache(); 2124 } catch (error) { 2125 let e: business_error.BusinessError = error as business_error.BusinessError; 2126 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2127 } 2128 }) 2129 Web({ src: 'www.example.com', controller: this.controller }) 2130 } 2131 } 2132} 2133``` 2134 2135### clearClientAuthenticationCache 2136 2137clearClientAuthenticationCache(): void 2138 2139Clears the user operation corresponding to the client certificate request event recorded by the **\<Web>** component. 2140 2141**System capability**: SystemCapability.Web.Webview.Core 2142 2143**Error codes** 2144 2145For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2146 2147| ID| Error Message | 2148| -------- | ------------------------------------------------------------ | 2149| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 2150 2151**Example** 2152 2153```ts 2154// xxx.ets 2155import web_webview from '@ohos.web.webview'; 2156import business_error from '@ohos.base'; 2157 2158@Entry 2159@Component 2160struct WebComponent { 2161 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2162 2163 build() { 2164 Column() { 2165 Button('clearClientAuthenticationCache') 2166 .onClick(() => { 2167 try { 2168 this.controller.clearClientAuthenticationCache(); 2169 } catch (error) { 2170 let e: business_error.BusinessError = error as business_error.BusinessError; 2171 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2172 } 2173 }) 2174 Web({ src: 'www.example.com', controller: this.controller }) 2175 } 2176 } 2177} 2178``` 2179 2180### createWebMessagePorts 2181 2182createWebMessagePorts(isExtentionType?: boolean): Array\<WebMessagePort> 2183 2184Creates web message ports. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 2185 2186**System capability**: SystemCapability.Web.Webview.Core 2187 2188**Parameters** 2189 2190| Name| Type | Mandatory| Description | 2191| ------ | ---------------------- | ---- | :------------------------------| 2192| isExtentionType<sup>10+</sup> | boolean | No | Whether to use the extended interface. The default value is **false**, indicating that the extended interface is not used. This parameter is supported since API version 10.| 2193 2194**Return value** 2195 2196| Type | Description | 2197| ---------------------- | ----------------- | 2198| Array\<WebMessagePort> | List of web message ports.| 2199 2200**Error codes** 2201 2202For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2203 2204| ID| Error Message | 2205| -------- | ------------------------------------------------------------ | 2206| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2207 2208**Example** 2209 2210 ```ts 2211// xxx.ets 2212import web_webview from '@ohos.web.webview'; 2213import business_error from '@ohos.base'; 2214 2215@Entry 2216@Component 2217struct WebComponent { 2218 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2219 ports: web_webview.WebMessagePort[] = []; 2220 2221 build() { 2222 Column() { 2223 Button('createWebMessagePorts') 2224 .onClick(() => { 2225 try { 2226 this.ports = this.controller.createWebMessagePorts(); 2227 console.log("createWebMessagePorts size:" + this.ports.length) 2228 } catch (error) { 2229 let e: business_error.BusinessError = error as business_error.BusinessError; 2230 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2231 } 2232 }) 2233 Web({ src: 'www.example.com', controller: this.controller }) 2234 } 2235 } 2236} 2237 ``` 2238 2239### postMessage 2240 2241postMessage(name: string, ports: Array\<WebMessagePort>, uri: string): void 2242 2243Sends a web message to an HTML5 window. 2244 2245**System capability**: SystemCapability.Web.Webview.Core 2246 2247**Parameters** 2248 2249| Name| Type | Mandatory| Description | 2250| ------ | ---------------------- | ---- | :------------------------------- | 2251| name | string | Yes | Name of the message to send. | 2252| ports | Array\<WebMessagePort> | Yes | Message ports for sending the message. | 2253| uri | string | Yes | URI for receiving the message. | 2254 2255**Error codes** 2256 2257For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2258 2259| ID| Error Message | 2260| -------- | ------------------------------------------------------------ | 2261| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2262 2263**Example** 2264 2265```ts 2266// xxx.ets 2267import web_webview from '@ohos.web.webview'; 2268import business_error from '@ohos.base'; 2269 2270@Entry 2271@Component 2272struct WebComponent { 2273 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2274 ports: web_webview.WebMessagePort[] = []; 2275 @State sendFromEts: string = 'Send this message from ets to HTML'; 2276 @State receivedFromHtml: string = 'Display received message send from HTML'; 2277 2278 build() { 2279 Column() { 2280 // Display the received HTML content. 2281 Text(this.receivedFromHtml) 2282 // Send the content in the text box to an HTML window. 2283 TextInput({ placeholder: 'Send this message from ets to HTML' }) 2284 .onChange((value: string) => { 2285 this.sendFromEts = value; 2286 }) 2287 2288 Button('postMessage') 2289 .onClick(() => { 2290 try { 2291 // 1. Create two message ports. 2292 this.ports = this.controller.createWebMessagePorts(); 2293 // 2. Register a callback on a message port (for example, port 1) on the application side. 2294 this.ports[1].onMessageEvent((result: web_webview.WebMessage) => { 2295 let msg = 'Got msg from HTML:'; 2296 if (typeof(result) == "string") { 2297 console.log("received string message from html5, string is:" + result); 2298 msg = msg + result; 2299 } else if (typeof(result) == "object") { 2300 if (result instanceof ArrayBuffer) { 2301 console.log("received arraybuffer from html5, length is:" + result.byteLength); 2302 msg = msg + "lenght is " + result.byteLength; 2303 } else { 2304 console.log("not support"); 2305 } 2306 } else { 2307 console.log("not support"); 2308 } 2309 this.receivedFromHtml = msg; 2310 }) 2311 // 3. Send another message port (for example, port 0) to the HTML side, which can then save the port for future use. 2312 this.controller.postMessage('__init_port__', [this.ports[0]], '*'); 2313 } catch (error) { 2314 let e: business_error.BusinessError = error as business_error.BusinessError; 2315 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2316 } 2317 }) 2318 2319 // 4. Use the port on the application side to send messages to the port that has been sent to the HTML side. 2320 Button('SendDataToHTML') 2321 .onClick(() => { 2322 try { 2323 if (this.ports && this.ports[1]) { 2324 this.ports[1].postMessageEvent(this.sendFromEts); 2325 } else { 2326 console.error(`ports is null, Please initialize first`); 2327 } 2328 } catch (error) { 2329 let e: business_error.BusinessError = error as business_error.BusinessError; 2330 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2331 } 2332 }) 2333 Web({ src: $rawfile('index.html'), controller: this.controller }) 2334 } 2335 } 2336} 2337``` 2338 2339HTML file to be loaded: 2340```html 2341<!--index.html--> 2342<!DOCTYPE html> 2343<html> 2344<head> 2345 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 2346 <title>WebView Message Port Demo</title> 2347</head> 2348 2349 <body> 2350 <h1>WebView Message Port Demo</h1> 2351 <div> 2352 <input type="button" value="SendToEts" onclick="PostMsgToEts(msgFromJS.value);"/><br/> 2353 <input id="msgFromJS" type="text" value="send this message from HTML to ets"/><br/> 2354 </div> 2355 <p class="output">display received message send from ets</p> 2356 </body> 2357 <script src="xxx.js"></script> 2358</html> 2359``` 2360 2361```js 2362//xxx.js 2363var h5Port; 2364var output = document.querySelector('.output'); 2365window.addEventListener('message', function (event) { 2366 if (event.data == '__init_port__') { 2367 if (event.ports[0] != null) { 2368 h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side. 2369 h5Port.onmessage = function (event) { 2370 // 2. Receive the message sent from the eTS side. 2371 var msg = 'Got message from ets:'; 2372 var result = event.data; 2373 if (typeof(result) == "string") { 2374 console.log("received string message from html5, string is:" + result); 2375 msg = msg + result; 2376 } else if (typeof(result) == "object") { 2377 if (result instanceof ArrayBuffer) { 2378 console.log("received arraybuffer from html5, length is:" + result.byteLength); 2379 msg = msg + "lenght is " + result.byteLength; 2380 } else { 2381 console.log("not support"); 2382 } 2383 } else { 2384 console.log("not support"); 2385 } 2386 output.innerHTML = msg; 2387 } 2388 } 2389 } 2390}) 2391 2392// 3. Use h5Port to send messages to the eTS side. 2393function PostMsgToEts(data) { 2394 if (h5Port) { 2395 h5Port.postMessage(data); 2396 } else { 2397 console.error("h5Port is null, Please initialize first"); 2398 } 2399} 2400``` 2401 2402### requestFocus 2403 2404requestFocus(): void 2405 2406Requests focus for this web page. 2407 2408**System capability**: SystemCapability.Web.Webview.Core 2409 2410**Error codes** 2411 2412For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2413 2414| ID| Error Message | 2415| -------- | ------------------------------------------------------------ | 2416| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2417 2418**Example** 2419 2420```ts 2421// xxx.ets 2422import web_webview from '@ohos.web.webview'; 2423import business_error from '@ohos.base'; 2424 2425@Entry 2426@Component 2427struct WebComponent { 2428 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2429 2430 build() { 2431 Column() { 2432 Button('requestFocus') 2433 .onClick(() => { 2434 try { 2435 this.controller.requestFocus(); 2436 } catch (error) { 2437 let e: business_error.BusinessError = error as business_error.BusinessError; 2438 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2439 } 2440 }); 2441 Web({ src: 'www.example.com', controller: this.controller }) 2442 } 2443 } 2444} 2445``` 2446 2447### zoomIn 2448 2449zoomIn(): void 2450 2451Zooms in on this web page by 20%. 2452 2453**System capability**: SystemCapability.Web.Webview.Core 2454 2455**Error codes** 2456 2457For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2458 2459| ID| Error Message | 2460| -------- | ------------------------------------------------------------ | 2461| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2462| 17100004 | Function not enable. | 2463 2464**Example** 2465 2466```ts 2467// xxx.ets 2468import web_webview from '@ohos.web.webview'; 2469import business_error from '@ohos.base'; 2470 2471@Entry 2472@Component 2473struct WebComponent { 2474 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2475 2476 build() { 2477 Column() { 2478 Button('zoomIn') 2479 .onClick(() => { 2480 try { 2481 this.controller.zoomIn(); 2482 } catch (error) { 2483 let e: business_error.BusinessError = error as business_error.BusinessError; 2484 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2485 } 2486 }) 2487 Web({ src: 'www.example.com', controller: this.controller }) 2488 } 2489 } 2490} 2491``` 2492 2493### zoomOut 2494 2495zoomOut(): void 2496 2497Zooms out of this web page by 20%. 2498 2499**System capability**: SystemCapability.Web.Webview.Core 2500 2501**Error codes** 2502 2503For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2504 2505| ID| Error Message | 2506| -------- | ------------------------------------------------------------ | 2507| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2508| 17100004 | Function not enable. | 2509 2510**Example** 2511 2512```ts 2513// xxx.ets 2514import web_webview from '@ohos.web.webview'; 2515import business_error from '@ohos.base'; 2516 2517@Entry 2518@Component 2519struct WebComponent { 2520 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2521 2522 build() { 2523 Column() { 2524 Button('zoomOut') 2525 .onClick(() => { 2526 try { 2527 this.controller.zoomOut(); 2528 } catch (error) { 2529 let e: business_error.BusinessError = error as business_error.BusinessError; 2530 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2531 } 2532 }) 2533 Web({ src: 'www.example.com', controller: this.controller }) 2534 } 2535 } 2536} 2537``` 2538 2539### getHitTestValue 2540 2541getHitTestValue(): HitTestValue 2542 2543Obtains the element information of the area being clicked. 2544 2545**System capability**: SystemCapability.Web.Webview.Core 2546 2547**Return value** 2548 2549| Type | Description | 2550| ------------ | -------------------- | 2551| [HitTestValue](#hittestvalue) | Element information of the area being clicked.| 2552 2553**Error codes** 2554 2555For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2556 2557| ID| Error Message | 2558| -------- | ------------------------------------------------------------ | 2559| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2560 2561**Example** 2562 2563```ts 2564// xxx.ets 2565import web_webview from '@ohos.web.webview'; 2566import business_error from '@ohos.base'; 2567 2568@Entry 2569@Component 2570struct WebComponent { 2571 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2572 2573 build() { 2574 Column() { 2575 Button('getHitTestValue') 2576 .onClick(() => { 2577 try { 2578 let hitValue = this.controller.getHitTestValue(); 2579 console.log("hitType: " + hitValue.type); 2580 console.log("extra: " + hitValue.extra); 2581 } catch (error) { 2582 let e: business_error.BusinessError = error as business_error.BusinessError; 2583 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2584 } 2585 }) 2586 Web({ src: 'www.example.com', controller: this.controller }) 2587 } 2588 } 2589} 2590``` 2591 2592### getWebId 2593 2594getWebId(): number 2595 2596Obtains the index value of this **\<Web>** component, which can be used for **\<Web>** component management. 2597 2598**System capability**: SystemCapability.Web.Webview.Core 2599 2600**Return value** 2601 2602| Type | Description | 2603| ------ | --------------------- | 2604| number | Index value of the current **\<Web>** component.| 2605 2606**Error codes** 2607 2608For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2609 2610| ID| Error Message | 2611| -------- | ------------------------------------------------------------ | 2612| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2613 2614**Example** 2615 2616```ts 2617// xxx.ets 2618import web_webview from '@ohos.web.webview'; 2619import business_error from '@ohos.base'; 2620 2621@Entry 2622@Component 2623struct WebComponent { 2624 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2625 2626 build() { 2627 Column() { 2628 Button('getWebId') 2629 .onClick(() => { 2630 try { 2631 let id = this.controller.getWebId(); 2632 console.log("id: " + id); 2633 } catch (error) { 2634 let e: business_error.BusinessError = error as business_error.BusinessError; 2635 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2636 } 2637 }) 2638 Web({ src: 'www.example.com', controller: this.controller }) 2639 } 2640 } 2641} 2642``` 2643 2644### getUserAgent 2645 2646getUserAgent(): string 2647 2648Obtains the default user agent of this web page. 2649 2650**System capability**: SystemCapability.Web.Webview.Core 2651 2652**Return value** 2653 2654| Type | Description | 2655| ------ | -------------- | 2656| string | Default user agent.| 2657 2658**Error codes** 2659 2660For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2661 2662| ID| Error Message | 2663| -------- | ------------------------------------------------------------ | 2664| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2665 2666**Example** 2667 2668```ts 2669// xxx.ets 2670import web_webview from '@ohos.web.webview'; 2671import business_error from '@ohos.base'; 2672 2673@Entry 2674@Component 2675struct WebComponent { 2676 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2677 2678 build() { 2679 Column() { 2680 Button('getUserAgent') 2681 .onClick(() => { 2682 try { 2683 let userAgent = this.controller.getUserAgent(); 2684 console.log("userAgent: " + userAgent); 2685 } catch (error) { 2686 let e:business_error.BusinessError = error as business_error.BusinessError; 2687 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2688 } 2689 }) 2690 Web({ src: 'www.example.com', controller: this.controller }) 2691 } 2692 } 2693} 2694``` 2695 2696You can customize the user agent based on the default user agent. 2697```ts 2698// xxx.ets 2699import web_webview from '@ohos.web.webview'; 2700import business_error from '@ohos.base'; 2701 2702@Entry 2703@Component 2704struct WebComponent { 2705 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2706 @State ua: string = "" 2707 2708 aboutToAppear():void { 2709 web_webview.once('webInited', () => { 2710 try { 2711 // Customize the user agent on the application side. 2712 this.ua = this.controller.getUserAgent() + 'xxx'; 2713 } catch(error) { 2714 let e:business_error.BusinessError = error as business_error.BusinessError; 2715 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2716 } 2717 }) 2718 } 2719 2720 build() { 2721 Column() { 2722 Web({ src: 'www.example.com', controller: this.controller }) 2723 .userAgent(this.ua) 2724 } 2725 } 2726} 2727``` 2728 2729### getTitle 2730 2731getTitle(): string 2732 2733Obtains the title of the current web page. 2734 2735**System capability**: SystemCapability.Web.Webview.Core 2736 2737**Return value** 2738 2739| Type | Description | 2740| ------ | -------------------- | 2741| string | Title of the current web page.| 2742 2743**Error codes** 2744 2745For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2746 2747| ID| Error Message | 2748| -------- | ------------------------------------------------------------ | 2749| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2750 2751**Example** 2752 2753```ts 2754// xxx.ets 2755import web_webview from '@ohos.web.webview'; 2756import business_error from '@ohos.base'; 2757 2758@Entry 2759@Component 2760struct WebComponent { 2761 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2762 2763 build() { 2764 Column() { 2765 Button('getTitle') 2766 .onClick(() => { 2767 try { 2768 let title = this.controller.getTitle(); 2769 console.log("title: " + title); 2770 } catch (error) { 2771 let e:business_error.BusinessError = error as business_error.BusinessError; 2772 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2773 } 2774 }) 2775 Web({ src: 'www.example.com', controller: this.controller }) 2776 } 2777 } 2778} 2779``` 2780 2781### getPageHeight 2782 2783getPageHeight(): number 2784 2785Obtains the height of this web page. 2786 2787**System capability**: SystemCapability.Web.Webview.Core 2788 2789**Return value** 2790 2791| Type | Description | 2792| ------ | -------------------- | 2793| number | Height of the current web page.| 2794 2795**Error codes** 2796 2797For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2798 2799| ID| Error Message | 2800| -------- | ------------------------------------------------------------ | 2801| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2802 2803**Example** 2804 2805```ts 2806// xxx.ets 2807import web_webview from '@ohos.web.webview'; 2808import business_error from '@ohos.base'; 2809 2810@Entry 2811@Component 2812struct WebComponent { 2813 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2814 2815 build() { 2816 Column() { 2817 Button('getPageHeight') 2818 .onClick(() => { 2819 try { 2820 let pageHeight = this.controller.getPageHeight(); 2821 console.log("pageHeight : " + pageHeight); 2822 } catch (error) { 2823 let e:business_error.BusinessError = error as business_error.BusinessError; 2824 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2825 } 2826 }) 2827 Web({ src: 'www.example.com', controller: this.controller }) 2828 } 2829 } 2830} 2831``` 2832 2833### storeWebArchive 2834 2835storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback\<string>): void 2836 2837Stores this web page. This API uses an asynchronous callback to return the result. 2838 2839**System capability**: SystemCapability.Web.Webview.Core 2840 2841**Parameters** 2842 2843| Name | Type | Mandatory| Description | 2844| -------- | --------------------- | ---- | ------------------------------------------------------------ | 2845| baseName | string | Yes | Save path. The value cannot be null. | 2846| autoName | boolean | Yes | Whether to automatically generate a file name. The value **false** means not to automatically generate a file name. The value **true** means to automatically generate a file name based on the URL of the current page and the **baseName** value. In this case, **baseName** is regarded as a directory.| 2847| callback | AsyncCallback\<string> | Yes | Callback used to return the save path if the operation is successful and null otherwise. | 2848 2849**Error codes** 2850 2851For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2852 2853| ID| Error Message | 2854| -------- | ------------------------------------------------------------ | 2855| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2856| 17100003 | Invalid resource path or file type. | 2857 2858**Example** 2859 2860```ts 2861// xxx.ets 2862import web_webview from '@ohos.web.webview' 2863import business_error from '@ohos.base' 2864 2865@Entry 2866@Component 2867struct WebComponent { 2868 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2869 2870 build() { 2871 Column() { 2872 Button('storeWebArchive') 2873 .onClick(() => { 2874 try { 2875 this.controller.storeWebArchive("/data/storage/el2/base/", true, (error, filename) => { 2876 if (error) { 2877 console.info(`save web archive error: ` + JSON.stringify(error)) 2878 return; 2879 } 2880 if (filename != null) { 2881 console.info(`save web archive success: ${filename}`) 2882 } 2883 }); 2884 } catch (error) { 2885 let e:business_error.BusinessError = error as business_error.BusinessError; 2886 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2887 } 2888 }) 2889 Web({ src: 'www.example.com', controller: this.controller }) 2890 } 2891 } 2892} 2893``` 2894 2895### storeWebArchive 2896 2897storeWebArchive(baseName: string, autoName: boolean): Promise\<string> 2898 2899Stores this web page. This API uses a promise to return the result. 2900 2901**System capability**: SystemCapability.Web.Webview.Core 2902 2903**Parameters** 2904 2905| Name | Type| Mandatory| Description | 2906| -------- | -------- | ---- | ------------------------------------------------------------ | 2907| baseName | string | Yes | Save path. The value cannot be null. | 2908| autoName | boolean | Yes | Whether to automatically generate a file name. The value **false** means not to automatically generate a file name. The value **true** means to automatically generate a file name based on the URL of the current page and the **baseName** value. In this case, **baseName** is regarded as a directory.| 2909 2910**Return value** 2911 2912| Type | Description | 2913| --------------- | ----------------------------------------------------- | 2914| Promise\<string> | Promise used to return the save path if the operation is successful and null otherwise.| 2915 2916**Error codes** 2917 2918For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2919 2920| ID| Error Message | 2921| -------- | ------------------------------------------------------------ | 2922| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2923| 17100003 | Invalid resource path or file type. | 2924 2925**Example** 2926 2927```ts 2928// xxx.ets 2929import web_webview from '@ohos.web.webview' 2930import business_error from '@ohos.base' 2931 2932@Entry 2933@Component 2934struct WebComponent { 2935 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2936 2937 build() { 2938 Column() { 2939 Button('storeWebArchive') 2940 .onClick(() => { 2941 try { 2942 this.controller.storeWebArchive("/data/storage/el2/base/", true) 2943 .then(filename => { 2944 if (filename != null) { 2945 console.info(`save web archive success: ${filename}`) 2946 } 2947 }) 2948 .catch((error:business_error.BusinessError) => { 2949 console.log('error: ' + JSON.stringify(error)); 2950 }) 2951 } catch (error) { 2952 let e:business_error.BusinessError = error as business_error.BusinessError; 2953 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2954 } 2955 }) 2956 Web({ src: 'www.example.com', controller: this.controller }) 2957 } 2958 } 2959} 2960``` 2961 2962### getUrl 2963 2964getUrl(): string 2965 2966Obtains the URL of this page. 2967 2968**System capability**: SystemCapability.Web.Webview.Core 2969 2970**Return value** 2971 2972| Type | Description | 2973| ------ | ------------------- | 2974| string | URL of the current page.| 2975 2976**Error codes** 2977 2978For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2979 2980| ID| Error Message | 2981| -------- | ------------------------------------------------------------ | 2982| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2983 2984**Example** 2985 2986```ts 2987// xxx.ets 2988import web_webview from '@ohos.web.webview'; 2989import business_error from '@ohos.base'; 2990 2991@Entry 2992@Component 2993struct WebComponent { 2994 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2995 2996 build() { 2997 Column() { 2998 Button('getUrl') 2999 .onClick(() => { 3000 try { 3001 let url = this.controller.getUrl(); 3002 console.log("url: " + url); 3003 } catch (error) { 3004 let e:business_error.BusinessError = error as business_error.BusinessError; 3005 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3006 } 3007 }) 3008 Web({ src: 'www.example.com', controller: this.controller }) 3009 } 3010 } 3011} 3012``` 3013 3014### stop 3015 3016stop(): void 3017 3018Stops page loading. 3019 3020**System capability**: SystemCapability.Web.Webview.Core 3021 3022**Error codes** 3023 3024For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3025 3026| ID| Error Message | 3027| -------- | ------------------------------------------------------------ | 3028| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3029 3030**Example** 3031 3032```ts 3033// xxx.ets 3034import web_webview from '@ohos.web.webview'; 3035import business_error from '@ohos.base'; 3036 3037@Entry 3038@Component 3039struct WebComponent { 3040 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3041 3042 build() { 3043 Column() { 3044 Button('stop') 3045 .onClick(() => { 3046 try { 3047 this.controller.stop(); 3048 } catch (error) { 3049 let e:business_error.BusinessError = error as business_error.BusinessError; 3050 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3051 } 3052 }); 3053 Web({ src: 'www.example.com', controller: this.controller }) 3054 } 3055 } 3056} 3057``` 3058 3059### backOrForward 3060 3061backOrForward(step: number): void 3062 3063Performs 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. 3064 3065Because the previously loaded web pages are used for the operation, no page reloading is involved. 3066 3067**System capability**: SystemCapability.Web.Webview.Core 3068 3069**Parameters** 3070 3071| Name| Type| Mandatory| Description | 3072| ------ | -------- | ---- | ---------------------- | 3073| step | number | Yes | Number of the steps to take.| 3074 3075**Error codes** 3076 3077For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3078 3079| ID| Error Message | 3080| -------- | ------------------------------------------------------------ | 3081| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3082 3083**Example** 3084 3085```ts 3086// xxx.ets 3087import web_webview from '@ohos.web.webview'; 3088import business_error from '@ohos.base'; 3089 3090@Entry 3091@Component 3092struct WebComponent { 3093 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3094 @State step: number = -2; 3095 3096 build() { 3097 Column() { 3098 Button('backOrForward') 3099 .onClick(() => { 3100 try { 3101 this.controller.backOrForward(this.step); 3102 } catch (error) { 3103 let e:business_error.BusinessError = error as business_error.BusinessError; 3104 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3105 } 3106 }) 3107 Web({ src: 'www.example.com', controller: this.controller }) 3108 } 3109 } 3110} 3111``` 3112 3113### scrollTo 3114 3115scrollTo(x:number, y:number): void 3116 3117Scrolls the page to the specified absolute position. 3118 3119**System capability**: SystemCapability.Web.Webview.Core 3120 3121**Parameters** 3122 3123| Name| Type| Mandatory| Description | 3124| ------ | -------- | ---- | ---------------------- | 3125| x | number | Yes | X coordinate of the absolute position. If the value is a negative number, the value 0 is used.| 3126| y | number | Yes | Y coordinate of the absolute position. If the value is a negative number, the value 0 is used.| 3127 3128**Error codes** 3129 3130For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3131 3132| ID| Error Message | 3133| -------- | ------------------------------------------------------------ | 3134| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3135 3136**Example** 3137 3138```ts 3139// xxx.ets 3140import web_webview from '@ohos.web.webview'; 3141import business_error from '@ohos.base'; 3142 3143@Entry 3144@Component 3145struct WebComponent { 3146 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3147 3148 build() { 3149 Column() { 3150 Button('scrollTo') 3151 .onClick(() => { 3152 try { 3153 this.controller.scrollTo(50, 50); 3154 } catch (error) { 3155 let e:business_error.BusinessError = error as business_error.BusinessError; 3156 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3157 } 3158 }) 3159 Web({ src: $rawfile('index.html'), controller: this.controller }) 3160 } 3161 } 3162} 3163``` 3164 3165HTML file to be loaded: 3166```html 3167<!--index.html--> 3168<!DOCTYPE html> 3169<html> 3170<head> 3171 <title>Demo</title> 3172 <style> 3173 body { 3174 width:3000px; 3175 height:3000px; 3176 padding-right:170px; 3177 padding-left:170px; 3178 border:5px solid blueviolet 3179 } 3180 </style> 3181</head> 3182<body> 3183Scroll Test 3184</body> 3185</html> 3186``` 3187 3188### scrollBy 3189 3190scrollBy(deltaX:number, deltaY:number): void 3191 3192Scrolls the page by the specified amount. 3193 3194**System capability**: SystemCapability.Web.Webview.Core 3195 3196**Parameters** 3197 3198| Name| Type| Mandatory| Description | 3199| ------ | -------- | ---- | ---------------------- | 3200| deltaX | number | Yes | Amount to scroll by along the x-axis. The positive direction is rightward.| 3201| deltaY | number | Yes | Amount to scroll by along the y-axis. The positive direction is downward.| 3202 3203**Error codes** 3204 3205For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3206 3207| ID| Error Message | 3208| -------- | ------------------------------------------------------------ | 3209| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3210 3211**Example** 3212 3213```ts 3214// xxx.ets 3215import web_webview from '@ohos.web.webview'; 3216import business_error from '@ohos.base'; 3217 3218@Entry 3219@Component 3220struct WebComponent { 3221 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3222 3223 build() { 3224 Column() { 3225 Button('scrollBy') 3226 .onClick(() => { 3227 try { 3228 this.controller.scrollBy(50, 50); 3229 } catch (error) { 3230 let e:business_error.BusinessError = error as business_error.BusinessError; 3231 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3232 } 3233 }) 3234 Web({ src: $rawfile('index.html'), controller: this.controller }) 3235 } 3236 } 3237} 3238``` 3239 3240HTML file to be loaded: 3241```html 3242<!--index.html--> 3243<!DOCTYPE html> 3244<html> 3245<head> 3246 <title>Demo</title> 3247 <style> 3248 body { 3249 width:3000px; 3250 height:3000px; 3251 padding-right:170px; 3252 padding-left:170px; 3253 border:5px solid blueviolet 3254 } 3255 </style> 3256</head> 3257<body> 3258Scroll Test 3259</body> 3260</html> 3261``` 3262 3263### slideScroll 3264 3265slideScroll(vx:number, vy:number): void 3266 3267Simulates a slide-to-scroll action on the page at the specified velocity. 3268 3269**System capability**: SystemCapability.Web.Webview.Core 3270 3271**Parameters** 3272 3273| Name| Type| Mandatory| Description | 3274| ------ | -------- | ---- | ---------------------- | 3275| vx | number | Yes | Horizontal velocity component of the slide-to-scroll action, where the positive direction is rightward.| 3276| vy | number | Yes | Vertical velocity component of the slide-to-scroll action, where the positive direction is downward.| 3277 3278**Error codes** 3279 3280For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3281 3282| ID| Error Message | 3283| -------- | ------------------------------------------------------------ | 3284| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3285 3286**Example** 3287 3288```ts 3289// xxx.ets 3290import web_webview from '@ohos.web.webview'; 3291import business_error from '@ohos.base'; 3292 3293@Entry 3294@Component 3295struct WebComponent { 3296 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3297 3298 build() { 3299 Column() { 3300 Button('slideScroll') 3301 .onClick(() => { 3302 try { 3303 this.controller.slideScroll(500, 500); 3304 } catch (error) { 3305 let e:business_error.BusinessError = error as business_error.BusinessError; 3306 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3307 } 3308 }) 3309 Web({ src: $rawfile('index.html'), controller: this.controller }) 3310 } 3311 } 3312} 3313``` 3314 3315HTML file to be loaded: 3316```html 3317<!--index.html--> 3318<!DOCTYPE html> 3319<html> 3320<head> 3321 <title>Demo</title> 3322 <style> 3323 body { 3324 width:3000px; 3325 height:3000px; 3326 padding-right:170px; 3327 padding-left:170px; 3328 border:5px solid blueviolet 3329 } 3330 </style> 3331</head> 3332<body> 3333Scroll Test 3334</body> 3335</html> 3336``` 3337 3338### getOriginalUrl 3339 3340getOriginalUrl(): string 3341 3342Obtains the original URL of this page. 3343 3344**System capability**: SystemCapability.Web.Webview.Core 3345 3346**Return value** 3347 3348| Type | Description | 3349| ------ | ----------------------- | 3350| string | Original URL of the current page.| 3351 3352**Error codes** 3353 3354For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3355 3356| ID| Error Message | 3357| -------- | ------------------------------------------------------------ | 3358| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3359 3360**Example** 3361 3362```ts 3363// xxx.ets 3364import web_webview from '@ohos.web.webview'; 3365import business_error from '@ohos.base'; 3366 3367@Entry 3368@Component 3369struct WebComponent { 3370 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3371 3372 build() { 3373 Column() { 3374 Button('getOrgUrl') 3375 .onClick(() => { 3376 try { 3377 let url = this.controller.getOriginalUrl(); 3378 console.log("original url: " + url); 3379 } catch (error) { 3380 let e:business_error.BusinessError = error as business_error.BusinessError; 3381 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3382 } 3383 }) 3384 Web({ src: 'www.example.com', controller: this.controller }) 3385 } 3386 } 3387} 3388``` 3389 3390### getFavicon 3391 3392getFavicon(): image.PixelMap 3393 3394Obtains the favicon of this page. 3395 3396**System capability**: SystemCapability.Web.Webview.Core 3397 3398**Return value** 3399 3400| Type | Description | 3401| -------------------------------------- | ------------------------------- | 3402| [PixelMap](js-apis-image.md#pixelmap7) | **PixelMap** object of the favicon of the page.| 3403 3404**Error codes** 3405 3406For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3407 3408| ID| Error Message | 3409| -------- | ------------------------------------------------------------ | 3410| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3411 3412**Example** 3413 3414```ts 3415// xxx.ets 3416import web_webview from '@ohos.web.webview'; 3417import image from "@ohos.multimedia.image"; 3418import business_error from '@ohos.base'; 3419 3420@Entry 3421@Component 3422struct WebComponent { 3423 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3424 @State pixelmap: image.PixelMap | undefined = undefined; 3425 3426 build() { 3427 Column() { 3428 Button('getFavicon') 3429 .onClick(() => { 3430 try { 3431 this.pixelmap = this.controller.getFavicon(); 3432 } catch (error) { 3433 let e:business_error.BusinessError = error as business_error.BusinessError; 3434 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3435 } 3436 }) 3437 Web({ src: 'www.example.com', controller: this.controller }) 3438 } 3439 } 3440} 3441``` 3442 3443### setNetworkAvailable 3444 3445setNetworkAvailable(enable: boolean): void 3446 3447Sets the **window.navigator.onLine** attribute in JavaScript. 3448 3449**System capability**: SystemCapability.Web.Webview.Core 3450 3451**Parameters** 3452 3453| Name| Type | Mandatory| Description | 3454| ------ | ------- | ---- | --------------------------------- | 3455| enable | boolean | Yes | Whether to enable **window.navigator.onLine**.| 3456 3457**Error codes** 3458 3459For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3460 3461| ID| Error Message | 3462| -------- | ------------------------------------------------------------ | 3463| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3464 3465**Example** 3466 3467```ts 3468// xxx.ets 3469import web_webview from '@ohos.web.webview'; 3470import business_error from '@ohos.base'; 3471 3472@Entry 3473@Component 3474struct WebComponent { 3475 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3476 3477 build() { 3478 Column() { 3479 Button('setNetworkAvailable') 3480 .onClick(() => { 3481 try { 3482 this.controller.setNetworkAvailable(true); 3483 } catch (error) { 3484 let e:business_error.BusinessError = error as business_error.BusinessError; 3485 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3486 } 3487 }) 3488 Web({ src: 'www.example.com', controller: this.controller }) 3489 } 3490 } 3491} 3492``` 3493 3494### hasImage 3495 3496hasImage(callback: AsyncCallback\<boolean>): void 3497 3498Checks whether this page contains images. This API uses an asynchronous callback to return the result. 3499 3500**System capability**: SystemCapability.Web.Webview.Core 3501 3502**Parameters** 3503 3504| Name | Type | Mandatory| Description | 3505| -------- | ----------------------- | ---- | -------------------------- | 3506| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result.| 3507 3508**Error codes** 3509 3510For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3511 3512| ID| Error Message | 3513| -------- | ------------------------------------------------------------ | 3514| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 3515 3516**Example** 3517 3518```ts 3519// xxx.ets 3520import web_webview from '@ohos.web.webview'; 3521import business_error from '@ohos.base'; 3522 3523@Entry 3524@Component 3525struct WebComponent { 3526 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3527 3528 build() { 3529 Column() { 3530 Button('hasImageCb') 3531 .onClick(() => { 3532 try { 3533 this.controller.hasImage((error, data) => { 3534 if (error) { 3535 console.info(`hasImage error: ` + JSON.stringify(error)) 3536 return; 3537 } 3538 console.info("hasImage: " + data); 3539 }); 3540 } catch (error) { 3541 let e:business_error.BusinessError = error as business_error.BusinessError; 3542 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3543 } 3544 }) 3545 Web({ src: 'www.example.com', controller: this.controller }) 3546 } 3547 } 3548} 3549``` 3550 3551### hasImage 3552 3553hasImage(): Promise\<boolean> 3554 3555Checks whether this page contains images. This API uses a promise to return the result. 3556 3557**System capability**: SystemCapability.Web.Webview.Core 3558 3559**Return value** 3560 3561| Type | Description | 3562| ----------------- | --------------------------------------- | 3563| Promise\<boolean> | Promise used to return the result.| 3564 3565**Error codes** 3566 3567For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3568 3569| ID| Error Message | 3570| -------- | ------------------------------------------------------------ | 3571| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 3572 3573**Example** 3574 3575```ts 3576// xxx.ets 3577import web_webview from '@ohos.web.webview'; 3578import business_error from '@ohos.base'; 3579 3580@Entry 3581@Component 3582struct WebComponent { 3583 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3584 3585 build() { 3586 Column() { 3587 Button('hasImagePm') 3588 .onClick(() => { 3589 try { 3590 this.controller.hasImage().then((data) => { 3591 console.info('hasImage: ' + data); 3592 }) 3593 .catch((error:business_error.BusinessError) => { 3594 console.error("error: " + error); 3595 }) 3596 } catch (error) { 3597 let e:business_error.BusinessError = error as business_error.BusinessError; 3598 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3599 } 3600 }) 3601 Web({ src: 'www.example.com', controller: this.controller }) 3602 } 3603 } 3604} 3605``` 3606 3607### removeCache 3608 3609removeCache(clearRom: boolean): void 3610 3611Clears the cache in the application. This API will clear the cache for all webviews in the same application. 3612 3613**System capability**: SystemCapability.Web.Webview.Core 3614 3615**Parameters** 3616 3617| Name | Type | Mandatory| Description | 3618| -------- | ------- | ---- | -------------------------------------------------------- | 3619| 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.| 3620 3621**Error codes** 3622 3623For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3624 3625| ID| Error Message | 3626| -------- | ------------------------------------------------------------ | 3627| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3628 3629**Example** 3630 3631```ts 3632// xxx.ets 3633import web_webview from '@ohos.web.webview'; 3634import business_error from '@ohos.base'; 3635 3636@Entry 3637@Component 3638struct WebComponent { 3639 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3640 3641 build() { 3642 Column() { 3643 Button('removeCache') 3644 .onClick(() => { 3645 try { 3646 this.controller.removeCache(false); 3647 } catch (error) { 3648 let e:business_error.BusinessError = error as business_error.BusinessError; 3649 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3650 } 3651 }) 3652 Web({ src: 'www.example.com', controller: this.controller }) 3653 } 3654 } 3655} 3656``` 3657 3658### pageUp 3659 3660pageUp(top:boolean): void 3661 3662Scrolls the page up by half the viewport or jumps to the top of the page. 3663 3664**System capability**: SystemCapability.Web.Webview.Core 3665 3666**Parameters** 3667 3668| Name| Type | Mandatory| Description | 3669| ------ | ------- | ---- | ------------------------------------------------------------ | 3670| 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 viewport.| 3671 3672**Error codes** 3673 3674For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3675 3676| ID| Error Message | 3677| -------- | ------------------------------------------------------------ | 3678| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3679 3680**Example** 3681 3682```ts 3683// xxx.ets 3684import web_webview from '@ohos.web.webview'; 3685import business_error from '@ohos.base'; 3686 3687@Entry 3688@Component 3689struct WebComponent { 3690 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3691 3692 build() { 3693 Column() { 3694 Button('pageUp') 3695 .onClick(() => { 3696 try { 3697 this.controller.pageUp(false); 3698 } catch (error) { 3699 let e:business_error.BusinessError = error as business_error.BusinessError; 3700 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3701 } 3702 }) 3703 Web({ src: 'www.example.com', controller: this.controller }) 3704 } 3705 } 3706} 3707``` 3708 3709### pageDown 3710 3711pageDown(bottom:boolean): void 3712 3713Scrolls the page down by half the viewport or jumps to the bottom of the page. 3714 3715**System capability**: SystemCapability.Web.Webview.Core 3716 3717**Parameters** 3718 3719| Name| Type | Mandatory| Description | 3720| ------ | ------- | ---- | ------------------------------------------------------------ | 3721| 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 viewport.| 3722 3723**Error codes** 3724 3725For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3726 3727| ID| Error Message | 3728| -------- | ------------------------------------------------------------ | 3729| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3730 3731**Example** 3732 3733```ts 3734// xxx.ets 3735import web_webview from '@ohos.web.webview'; 3736import business_error from '@ohos.base'; 3737 3738@Entry 3739@Component 3740struct WebComponent { 3741 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3742 3743 build() { 3744 Column() { 3745 Button('pageDown') 3746 .onClick(() => { 3747 try { 3748 this.controller.pageDown(false); 3749 } catch (error) { 3750 let e:business_error.BusinessError = error as business_error.BusinessError; 3751 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3752 } 3753 }) 3754 Web({ src: 'www.example.com', controller: this.controller }) 3755 } 3756 } 3757} 3758``` 3759 3760### getBackForwardEntries 3761 3762getBackForwardEntries(): BackForwardList 3763 3764Obtains the historical information list of the current webview. 3765 3766**System capability**: SystemCapability.Web.Webview.Core 3767 3768**Return value** 3769 3770| Type | Description | 3771| ----------------------------------- | --------------------------- | 3772| [BackForwardList](#backforwardlist) | Historical information list of the current webview.| 3773 3774**Error codes** 3775 3776For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3777 3778| ID| Error Message | 3779| -------- | ------------------------------------------------------------ | 3780| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3781 3782**Example** 3783 3784```ts 3785// xxx.ets 3786import web_webview from '@ohos.web.webview'; 3787import business_error from '@ohos.base'; 3788 3789@Entry 3790@Component 3791struct WebComponent { 3792 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3793 3794 build() { 3795 Column() { 3796 Button('getBackForwardEntries') 3797 .onClick(() => { 3798 try { 3799 let list = this.controller.getBackForwardEntries() 3800 } catch (error) { 3801 let e:business_error.BusinessError = error as business_error.BusinessError; 3802 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3803 } 3804 }) 3805 Web({ src: 'www.example.com', controller: this.controller }) 3806 } 3807 } 3808} 3809``` 3810 3811### serializeWebState 3812 3813serializeWebState(): Uint8Array 3814 3815Serializes the page status history of the current Webview. 3816 3817**System capability**: SystemCapability.Web.Webview.Core 3818 3819**Return value** 3820 3821| Type | Description | 3822| ---------- | --------------------------------------------- | 3823| Uint8Array | Serialized data of the page status history of the current WebView.| 3824 3825**Error codes** 3826 3827For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3828 3829| ID| Error Message | 3830| -------- | ------------------------------------------------------------ | 3831| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3832 3833**Example** 3834 38351. To perform operations on files, you must import the file management module. For details, see [File Management](./js-apis-file-fs.md). 3836```ts 3837// xxx.ets 3838import web_webview from '@ohos.web.webview'; 3839import fs from '@ohos.file.fs'; 3840import business_error from '@ohos.base'; 3841 3842@Entry 3843@Component 3844struct WebComponent { 3845 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3846 3847 build() { 3848 Column() { 3849 Button('serializeWebState') 3850 .onClick(() => { 3851 try { 3852 let state = this.controller.serializeWebState(); 3853 let path:string | undefined = AppStorage.get("cacheDir"); 3854 if (path) { 3855 path += '/WebState'; 3856 // Synchronously open a file. 3857 let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 3858 fs.writeSync(file.fd, state.buffer); 3859 fs.closeSync(file.fd); 3860 } 3861 } catch (error) { 3862 let e:business_error.BusinessError = error as business_error.BusinessError; 3863 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3864 } 3865 }) 3866 Web({ src: 'www.example.com', controller: this.controller }) 3867 } 3868 } 3869} 3870``` 3871 38722. Modify the **EntryAbility.ts** file. 3873Obtain the path of the application cache file. 3874```ts 3875// xxx.ts 3876import UIAbility from '@ohos.app.ability.UIAbility'; 3877import web_webview from '@ohos.web.webview'; 3878import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 3879import Want from '@ohos.app.ability.Want'; 3880 3881export default class EntryAbility extends UIAbility { 3882 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 3883 // Data synchronization between the UIAbility component and the page can be implemented by binding cacheDir to the AppStorage object. 3884 AppStorage.setOrCreate("cacheDir", this.context.cacheDir); 3885 } 3886} 3887``` 3888 3889### restoreWebState 3890 3891restoreWebState(state: Uint8Array): void 3892 3893Restores the page status history from the serialized data of the current WebView. 3894 3895**System capability**: SystemCapability.Web.Webview.Core 3896 3897**Parameters** 3898 3899| Name| Type | Mandatory| Description | 3900| ------ | ---------- | ---- | ---------------------------- | 3901| state | Uint8Array | Yes | Serialized data of the page status history.| 3902 3903**Error codes** 3904 3905For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3906 3907| ID| Error Message | 3908| -------- | ------------------------------------------------------------ | 3909| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3910 3911**Example** 3912 39131. To perform operations on files, you must import the file management module. For details, see [File Management](./js-apis-file-fs.md). 3914```ts 3915// xxx.ets 3916import web_webview from '@ohos.web.webview'; 3917import fs from '@ohos.file.fs'; 3918import business_error from '@ohos.base'; 3919 3920@Entry 3921@Component 3922struct WebComponent { 3923 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3924 3925 build() { 3926 Column() { 3927 Button('RestoreWebState') 3928 .onClick(() => { 3929 try { 3930 let path:string | undefined = AppStorage.get("cacheDir"); 3931 if (path) { 3932 path += '/WebState'; 3933 // Synchronously open a file. 3934 let file = fs.openSync(path, fs.OpenMode.READ_WRITE); 3935 let stat = fs.statSync(path); 3936 let size = stat.size; 3937 let buf = new ArrayBuffer(size); 3938 fs.read(file.fd, buf, (err, readLen) => { 3939 if (err) { 3940 console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); 3941 } else { 3942 console.info("read file data succeed"); 3943 this.controller.restoreWebState(new Uint8Array(buf.slice(0, readLen))); 3944 fs.closeSync(file); 3945 } 3946 }); 3947 } 3948 } catch (error) { 3949 let e:business_error.BusinessError = error as business_error.BusinessError; 3950 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3951 } 3952 }) 3953 Web({ src: 'www.example.com', controller: this.controller }) 3954 } 3955 } 3956} 3957``` 3958 39592. Modify the **EntryAbility.ts** file. 3960Obtain the path of the application cache file. 3961```ts 3962// xxx.ts 3963import UIAbility from '@ohos.app.ability.UIAbility'; 3964import web_webview from '@ohos.web.webview'; 3965import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 3966import Want from '@ohos.app.ability.Want'; 3967 3968export default class EntryAbility extends UIAbility { 3969 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 3970 // Data synchronization between the UIAbility component and the page can be implemented by binding cacheDir to the AppStorage object. 3971 AppStorage.setOrCreate("cacheDir", this.context.cacheDir); 3972 } 3973} 3974``` 3975 3976### customizeSchemes 3977 3978static customizeSchemes(schemes: Array\<WebCustomScheme\>): void 3979 3980Customizes the URL schemes (also known as protocols). It is recommended that this API be called before any **\<Web>** component is initialized. 3981 3982**System capability**: SystemCapability.Web.Webview.Core 3983 3984**Parameters** 3985 3986| Name | Type | Mandatory| Description | 3987| -------- | ------- | ---- | -------------------------------------- | 3988| schemes | Array\<[WebCustomScheme](#webcustomscheme)\> | Yes | Array of up to 10 custom schemes.| 3989 3990**Example** 3991 3992```ts 3993// xxx.ets 3994import web_webview from '@ohos.web.webview'; 3995import business_error from '@ohos.base'; 3996 3997@Entry 3998@Component 3999struct WebComponent { 4000 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4001 responseweb: WebResourceResponse = new WebResourceResponse() 4002 scheme1: web_webview.WebCustomScheme = {schemeName: "name1", isSupportCORS: true, isSupportFetch: true} 4003 scheme2: web_webview.WebCustomScheme = {schemeName: "name2", isSupportCORS: true, isSupportFetch: true} 4004 scheme3: web_webview.WebCustomScheme = {schemeName: "name3", isSupportCORS: true, isSupportFetch: true} 4005 4006 aboutToAppear():void { 4007 try { 4008 web_webview.WebviewController.customizeSchemes([this.scheme1, this.scheme2, this.scheme3]) 4009 } catch(error) { 4010 let e:business_error.BusinessError = error as business_error.BusinessError; 4011 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4012 } 4013 } 4014 4015 build() { 4016 Column() { 4017 Web({ src: 'www.example.com', controller: this.controller }) 4018 .onInterceptRequest((event) => { 4019 if (event) { 4020 console.log('url:' + event.request.getRequestUrl()) 4021 } 4022 return this.responseweb 4023 }) 4024 } 4025 } 4026} 4027``` 4028 4029### getCertificate<sup>10+</sup> 4030 4031getCertificate(): Promise<Array<cert.X509Cert>> 4032 4033Obtains the certificate information of this website. When the **\<Web>** component is used to load an HTTPS website, SSL certificate verification is performed. This API uses a promise to return the [X.509 certificate](./js-apis-cert.md) of the current website. 4034 4035**System capability**: SystemCapability.Web.Webview.Core 4036 4037**Return value** 4038 4039| Type | Description | 4040| ---------- | --------------------------------------------- | 4041| Promise<Array<cert.X509Cert>> | Promise used to obtain the X.509 certificate array of the current HTTPS website.| 4042 4043**Error codes** 4044 4045For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4046 4047| ID| Error Message | 4048| -------- | ------------------------------------------------------------ | 4049| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4050 4051**Example** 4052 4053```ts 4054// xxx.ets 4055import web_webview from '@ohos.web.webview'; 4056import business_error from '@ohos.base'; 4057import cert from '@ohos.security.cert'; 4058 4059function Uint8ArrayToString(dataArray:Uint8Array) { 4060 let dataString = '' 4061 for (let i = 0; i < dataArray.length; i++) { 4062 dataString += String.fromCharCode(dataArray[i]) 4063 } 4064 return dataString 4065} 4066 4067function ParseX509CertInfo(x509CertArray:Array<cert.X509Cert>) { 4068 let res: string = 'getCertificate success: len = ' + x509CertArray.length; 4069 for (let i = 0; i < x509CertArray.length; i++) { 4070 res += ', index = ' + i + ', issuer name = ' 4071 + Uint8ArrayToString(x509CertArray[i].getIssuerName().data) + ', subject name = ' 4072 + Uint8ArrayToString(x509CertArray[i].getSubjectName().data) + ', valid start = ' 4073 + x509CertArray[i].getNotBeforeTime() 4074 + ', valid end = ' + x509CertArray[i].getNotAfterTime() 4075 } 4076 return res 4077} 4078 4079@Entry 4080@Component 4081struct Index { 4082 // outputStr displays debug information on the UI. 4083 @State outputStr: string = '' 4084 webviewCtl: web_webview.WebviewController = new web_webview.WebviewController(); 4085 4086 build() { 4087 Row() { 4088 Column() { 4089 List({space: 20, initialIndex: 0}) { 4090 ListItem() { 4091 Button() { 4092 Text('load bad ssl') 4093 .fontSize(10) 4094 .fontWeight(FontWeight.Bold) 4095 } 4096 .type(ButtonType.Capsule) 4097 .onClick(() => { 4098 // Load an expired certificate website and view the obtained certificate information. 4099 this.webviewCtl.loadUrl('https://expired.badssl.com') 4100 }) 4101 .height(50) 4102 } 4103 4104 ListItem() { 4105 Button() { 4106 Text('load example') 4107 .fontSize(10) 4108 .fontWeight(FontWeight.Bold) 4109 } 4110 .type(ButtonType.Capsule) 4111 .onClick(() => { 4112 // Load an HTTPS website and view the certificate information of the website. 4113 this.webviewCtl.loadUrl('https://www.example.com') 4114 }) 4115 .height(50) 4116 } 4117 4118 ListItem() { 4119 Button() { 4120 Text('getCertificate Promise') 4121 .fontSize(10) 4122 .fontWeight(FontWeight.Bold) 4123 } 4124 .type(ButtonType.Capsule) 4125 .onClick(() => { 4126 try { 4127 this.webviewCtl.getCertificate().then((x509CertArray:Array<cert.X509Cert>) => { 4128 this.outputStr = ParseX509CertInfo(x509CertArray); 4129 }) 4130 } catch (error) { 4131 let e:business_error.BusinessError = error as business_error.BusinessError; 4132 this.outputStr = 'getCertificate failed: ' + e.code + ", errMsg: " + e.message; 4133 } 4134 }) 4135 .height(50) 4136 } 4137 4138 ListItem() { 4139 Button() { 4140 Text('getCertificate AsyncCallback') 4141 .fontSize(10) 4142 .fontWeight(FontWeight.Bold) 4143 } 4144 .type(ButtonType.Capsule) 4145 .onClick(() => { 4146 try { 4147 this.webviewCtl.getCertificate((error:business_error.BusinessError, x509CertArray:Array<cert.X509Cert>) => { 4148 if (error) { 4149 this.outputStr = 'getCertificate failed: ' + error.code + ", errMsg: " + error.message; 4150 } else { 4151 this.outputStr = ParseX509CertInfo(x509CertArray); 4152 } 4153 }) 4154 } catch (error) { 4155 let e:business_error.BusinessError = error as business_error.BusinessError; 4156 this.outputStr = 'getCertificate failed: ' + e.code + ", errMsg: " + e.message; 4157 } 4158 }) 4159 .height(50) 4160 } 4161 } 4162 .listDirection(Axis.Horizontal) 4163 .height('10%') 4164 4165 Text(this.outputStr) 4166 .width('100%') 4167 .fontSize(10) 4168 4169 Web({ src: 'https://www.example.com', controller: this.webviewCtl }) 4170 .fileAccess(true) 4171 .javaScriptAccess(true) 4172 .domStorageAccess(true) 4173 .onlineImageAccess(true) 4174 .onPageEnd((e) => { 4175 if(e) { 4176 this.outputStr = 'onPageEnd : url = ' + e.url 4177 } 4178 }) 4179 .onSslErrorEventReceive((e) => { 4180 // Ignore SSL certificate errors to test websites whose certificates have expired, for example, https://expired.badssl.com. 4181 e.handler.handleConfirm() 4182 }) 4183 .width('100%') 4184 .height('70%') 4185 } 4186 .height('100%') 4187 } 4188 } 4189} 4190``` 4191 4192### getCertificate<sup>10+</sup> 4193 4194getCertificate(callback: AsyncCallback<Array<cert.X509Cert>>): void 4195 4196Obtains the certificate information of this website. When the **\<Web>** component is used to load an HTTPS website, SSL certificate verification is performed. This API uses an asynchronous callback to return the [X.509 certificate](./js-apis-cert.md) of the website. 4197 4198**System capability**: SystemCapability.Web.Webview.Core 4199 4200**Parameters** 4201 4202| Name | Type | Mandatory| Description | 4203| -------- | ---------------------------- | ---- | ---------------------------------------- | 4204| callback | AsyncCallback<Array<cert.X509Cert>> | Yes | Callback used to obtain the X.509 certificate array of the current website.| 4205 4206**Error codes** 4207 4208For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4209 4210| ID| Error Message | 4211| -------- | ------------------------------------------------------------ | 4212| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | 4213 4214**Example** 4215 4216```ts 4217// xxx.ets 4218import web_webview from '@ohos.web.webview'; 4219import business_error from '@ohos.base'; 4220import cert from '@ohos.security.cert'; 4221 4222function Uint8ArrayToString(dataArray:Uint8Array) { 4223 let dataString = '' 4224 for (let i = 0; i < dataArray.length; i++) { 4225 dataString += String.fromCharCode(dataArray[i]) 4226 } 4227 return dataString 4228} 4229 4230function ParseX509CertInfo(x509CertArray:Array<cert.X509Cert>) { 4231 let res: string = 'getCertificate success: len = ' + x509CertArray.length; 4232 for (let i = 0; i < x509CertArray.length; i++) { 4233 res += ', index = ' + i + ', issuer name = ' 4234 + Uint8ArrayToString(x509CertArray[i].getIssuerName().data) + ', subject name = ' 4235 + Uint8ArrayToString(x509CertArray[i].getSubjectName().data) + ', valid start = ' 4236 + x509CertArray[i].getNotBeforeTime() 4237 + ', valid end = ' + x509CertArray[i].getNotAfterTime() 4238 } 4239 return res 4240} 4241 4242@Entry 4243@Component 4244struct Index { 4245 // outputStr displays debug information on the UI. 4246 @State outputStr: string = '' 4247 webviewCtl: web_webview.WebviewController = new web_webview.WebviewController(); 4248 4249 build() { 4250 Row() { 4251 Column() { 4252 List({space: 20, initialIndex: 0}) { 4253 ListItem() { 4254 Button() { 4255 Text('load bad ssl') 4256 .fontSize(10) 4257 .fontWeight(FontWeight.Bold) 4258 } 4259 .type(ButtonType.Capsule) 4260 .onClick(() => { 4261 // Load an expired certificate website and view the obtained certificate information. 4262 this.webviewCtl.loadUrl('https://expired.badssl.com') 4263 }) 4264 .height(50) 4265 } 4266 4267 ListItem() { 4268 Button() { 4269 Text('load example') 4270 .fontSize(10) 4271 .fontWeight(FontWeight.Bold) 4272 } 4273 .type(ButtonType.Capsule) 4274 .onClick(() => { 4275 // Load an HTTPS website and view the certificate information of the website. 4276 this.webviewCtl.loadUrl('https://www.example.com') 4277 }) 4278 .height(50) 4279 } 4280 4281 ListItem() { 4282 Button() { 4283 Text('getCertificate Promise') 4284 .fontSize(10) 4285 .fontWeight(FontWeight.Bold) 4286 } 4287 .type(ButtonType.Capsule) 4288 .onClick(() => { 4289 try { 4290 this.webviewCtl.getCertificate().then((x509CertArray:Array<cert.X509Cert>) => { 4291 this.outputStr = ParseX509CertInfo(x509CertArray); 4292 }) 4293 } catch (error) { 4294 let e:business_error.BusinessError = error as business_error.BusinessError; 4295 this.outputStr = 'getCertificate failed: ' + e.code + ", errMsg: " + e.message; 4296 } 4297 }) 4298 .height(50) 4299 } 4300 4301 ListItem() { 4302 Button() { 4303 Text('getCertificate AsyncCallback') 4304 .fontSize(10) 4305 .fontWeight(FontWeight.Bold) 4306 } 4307 .type(ButtonType.Capsule) 4308 .onClick(() => { 4309 try { 4310 this.webviewCtl.getCertificate((error:business_error.BusinessError, x509CertArray:Array<cert.X509Cert>) => { 4311 if (error) { 4312 this.outputStr = 'getCertificate failed: ' + error.code + ", errMsg: " + error.message; 4313 } else { 4314 this.outputStr = ParseX509CertInfo(x509CertArray); 4315 } 4316 }) 4317 } catch (error) { 4318 let e:business_error.BusinessError = error as business_error.BusinessError; 4319 this.outputStr = 'getCertificate failed: ' + e.code + ", errMsg: " + e.message; 4320 } 4321 }) 4322 .height(50) 4323 } 4324 } 4325 .listDirection(Axis.Horizontal) 4326 .height('10%') 4327 4328 Text(this.outputStr) 4329 .width('100%') 4330 .fontSize(10) 4331 4332 Web({ src: 'https://www.example.com', controller: this.webviewCtl }) 4333 .fileAccess(true) 4334 .javaScriptAccess(true) 4335 .domStorageAccess(true) 4336 .onlineImageAccess(true) 4337 .onPageEnd((e) => { 4338 if (e) { 4339 this.outputStr = 'onPageEnd : url = ' + e.url 4340 } 4341 }) 4342 .onSslErrorEventReceive((e) => { 4343 // Ignore SSL certificate errors to test websites whose certificates have expired, for example, https://expired.badssl.com. 4344 e.handler.handleConfirm() 4345 }) 4346 .width('100%') 4347 .height('70%') 4348 } 4349 .height('100%') 4350 } 4351 } 4352} 4353``` 4354 4355### setAudioMuted<sup>10+</sup> 4356 4357setAudioMuted(mute: boolean): void 4358 4359Mutes this web page. 4360 4361**System capability**: SystemCapability.Web.Webview.Core 4362 4363**Parameters** 4364 4365| Name | Type | Mandatory| Description | 4366| -------- | ------- | ---- | -------------------------------------- | 4367| mute | boolean | Yes | Whether to mute the web page. The value **true** means to mute the web page, and **false** means the opposite.| 4368 4369**Error codes** 4370 4371For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4372 4373| ID| Error Message | 4374| -------- | ------------------------------------------------------------ | 4375| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4376 4377**Example** 4378 4379```ts 4380// xxx.ets 4381import web_webview from '@ohos.web.webview' 4382 4383@Entry 4384@Component 4385struct WebComponent { 4386 controller: web_webview.WebviewController = new web_webview.WebviewController() 4387 @State muted: boolean = false 4388 build() { 4389 Column() { 4390 Button("Toggle Mute") 4391 .onClick(event => { 4392 this.muted = !this.muted 4393 this.controller.setAudioMuted(this.muted) 4394 }) 4395 Web({ src: 'www.example.com', controller: this.controller }) 4396 } 4397 } 4398} 4399``` 4400 4401### prefetchPage<sup>10+</sup> 4402 4403prefetchPage(url: string, additionalHeaders?: Array\<WebHeader>): void 4404 4405Prefetches resources in the background for a page that is likely to be accessed in the near future, without executing the page JavaScript code or presenting the page. This can significantly reduce the load time for the prefetched page. 4406 4407**System capability**: SystemCapability.Web.Webview.Core 4408 4409**Parameters** 4410 4411| Name | Type | Mandatory | Description | 4412| ------------------| --------------------------------| ---- | ------------- | 4413| url | string | Yes | URL to be preloaded.| 4414| additionalHeaders | Array\<[WebHeader](#webheader)> | No | Additional HTTP headers of the URL.| 4415 4416**Error codes** 4417 4418For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4419 4420| ID | Error Message | 4421| -------- | ------------------------------------------------------------ | 4422| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4423| 17100002 | Invalid url. | 4424 4425**Example** 4426 4427```ts 4428// xxx.ets 4429import web_webview from '@ohos.web.webview' 4430import business_error from '@ohos.base' 4431 4432@Entry 4433@Component 4434struct WebComponent { 4435 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4436 4437 build() { 4438 Column() { 4439 Button('prefetchPopularPage') 4440 .onClick(() => { 4441 try { 4442 // Replace 'https://www.example.com' with a real URL for the API to work. 4443 this.controller.prefetchPage('https://www.example.com'); 4444 } catch (error) { 4445 let e:business_error.BusinessError = error as business_error.BusinessError; 4446 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4447 } 4448 }) 4449 // Replace ''www.example1.com' with a real URL for the API to work. 4450 Web({ src: 'www.example1.com', controller: this.controller }) 4451 } 4452 } 4453} 4454``` 4455 4456### prepareForPageLoad<sup>10+</sup> 4457 4458static prepareForPageLoad(url: string, preconnectable: boolean, numSockets: number): void 4459 4460Preconnects to a URL. This API can be called before the URL is loaded, to resolve the DNS and establish a socket connection, without obtaining the resources. 4461 4462**System capability**: SystemCapability.Web.Webview.Core 4463 4464**Parameters** 4465 4466| Name | Type | Mandatory | Description | 4467| ---------------| ------- | ---- | ------------- | 4468| url | string | Yes | URL to be preconnected.| 4469| preconnectable | boolean | Yes | Whether to perform preconnection, which involves DNS resolution and socket connection establishment. The value **true** means to perform preconnection, and **false** means the opposite.| 4470| numSockets | number | Yes | Number of sockets to be preconnected. The value must be greater than 0. A maximum of six socket connections are allowed.| 4471 4472**Error codes** 4473 4474For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4475 4476| ID | Error Message | 4477| -------- | ------------------------------------------------------------ | 4478| 17100002 | Invalid url. | 4479| 171000013| The number of preconnect sockets is invalid. | 4480 4481**Example** 4482 4483```ts 4484// xxx.ts 4485import UIAbility from '@ohos.app.ability.UIAbility'; 4486import web_webview from '@ohos.web.webview'; 4487import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 4488import Want from '@ohos.app.ability.Want'; 4489 4490export default class EntryAbility extends UIAbility { 4491 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 4492 console.log("EntryAbility onCreate") 4493 web_webview.WebviewController.initializeWebEngine() 4494 // Replace 'https://www.example.com' with a real URL for the API to work. 4495 web_webview.WebviewController.prepareForPageLoad("https://www.example.com", true, 2); 4496 AppStorage.setOrCreate("abilityWant", want) 4497 console.log("EntryAbility onCreate done") 4498 } 4499} 4500``` 4501 4502### setCustomUserAgent<sup>10+</sup> 4503 4504setCustomUserAgent(userAgent: string): void 4505 4506Set a custom user agent. 4507 4508**System capability**: SystemCapability.Web.Webview.Core 4509 4510**Parameters** 4511 4512| Name | Type | Mandatory | Description | 4513| ---------------| ------- | ---- | ------------- | 4514| userAgent | string | Yes | Information about the custom user agent.| 4515 4516**Error codes** 4517 4518For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4519 4520| ID | Error Message | 4521| -------- | ------------------------------------------------------------ | 4522| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4523 4524**Example** 4525 4526```ts 4527// xxx.ets 4528import web_webview from '@ohos.web.webview' 4529import business_error from '@ohos.base' 4530 4531@Entry 4532@Component 4533struct WebComponent { 4534 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4535 @State userAgent: string = 'test' 4536 4537 build() { 4538 Column() { 4539 Button('setCustomUserAgent') 4540 .onClick(() => { 4541 try { 4542 this.controller.setCustomUserAgent(this.userAgent); 4543 } catch (error) { 4544 let e:business_error.BusinessError = error as business_error.BusinessError; 4545 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4546 } 4547 }) 4548 Web({ src: 'www.example.com', controller: this.controller }) 4549 } 4550 } 4551} 4552``` 4553 4554### getCustomUserAgent<sup>10+</sup> 4555 4556getCustomUserAgent(): string 4557 4558Obtains a custom user agent. 4559 4560**System capability**: SystemCapability.Web.Webview.Core 4561 4562**Return value** 4563 4564| Type | Description | 4565| ------ | ------------------------- | 4566| string | Information about the custom user agent.| 4567 4568**Error codes** 4569 4570For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4571 4572| ID | Error Message | 4573| -------- | ------------------------------------------------------------ | 4574| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4575 4576**Example** 4577 4578```ts 4579// xxx.ets 4580import web_webview from '@ohos.web.webview' 4581import business_error from '@ohos.base' 4582 4583@Entry 4584@Component 4585struct WebComponent { 4586 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4587 @State userAgent: string = '' 4588 4589 build() { 4590 Column() { 4591 Button('getCustomUserAgent') 4592 .onClick(() => { 4593 try { 4594 this.userAgent = this.controller.getCustomUserAgent(); 4595 console.log("userAgent: " + this.userAgent); 4596 } catch (error) { 4597 let e:business_error.BusinessError = error as business_error.BusinessError; 4598 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4599 } 4600 }) 4601 Web({ src: 'www.example.com', controller: this.controller }) 4602 } 4603 } 4604} 4605``` 4606 4607## WebCookieManager 4608 4609Implements a **WebCookieManager** instance to manage behavior of cookies in **\<Web>** components. All **\<Web>** components in an application share a **WebCookieManager** instance. 4610 4611> **NOTE** 4612> 4613> You must load the **\<Web>** component before calling APIs in **WebCookieManager**. 4614 4615### getCookie 4616 4617static getCookie(url: string): string 4618 4619Obtains the cookie corresponding to the specified URL. 4620 4621**System capability**: SystemCapability.Web.Webview.Core 4622 4623**Parameters** 4624 4625| Name| Type | Mandatory| Description | 4626| ------ | ------ | ---- | :------------------------ | 4627| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 4628 4629**Return value** 4630 4631| Type | Description | 4632| ------ | ------------------------- | 4633| string | Cookie value corresponding to the specified URL.| 4634 4635**Error codes** 4636 4637For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4638 4639| ID| Error Message | 4640| -------- | ------------------------------------------------------ | 4641| 17100002 | Invalid url. | 4642 4643**Example** 4644 4645```ts 4646// xxx.ets 4647import web_webview from '@ohos.web.webview' 4648import business_error from '@ohos.base' 4649 4650@Entry 4651@Component 4652struct WebComponent { 4653 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4654 4655 build() { 4656 Column() { 4657 Button('getCookie') 4658 .onClick(() => { 4659 try { 4660 let value = web_webview.WebCookieManager.getCookie('https://www.example.com'); 4661 console.log("value: " + value); 4662 } catch (error) { 4663 let e:business_error.BusinessError = error as business_error.BusinessError; 4664 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4665 } 4666 }) 4667 Web({ src: 'www.example.com', controller: this.controller }) 4668 } 4669 } 4670} 4671``` 4672 4673### setCookie 4674 4675static setCookie(url: string, value: string): void 4676 4677Sets a cookie for the specified URL. 4678 4679**System capability**: SystemCapability.Web.Webview.Core 4680 4681**Parameters** 4682 4683| Name| Type | Mandatory| Description | 4684| ------ | ------ | ---- | :------------------------ | 4685| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 4686| value | string | Yes | Cookie value to set. | 4687 4688**Error codes** 4689 4690For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4691 4692| ID| Error Message | 4693| -------- | ------------------------------------------------------ | 4694| 17100002 | Invalid url. | 4695| 17100005 | Invalid cookie value. | 4696 4697**Example** 4698 4699```ts 4700// xxx.ets 4701import web_webview from '@ohos.web.webview' 4702import business_error from '@ohos.base' 4703 4704@Entry 4705@Component 4706struct WebComponent { 4707 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4708 4709 build() { 4710 Column() { 4711 Button('setCookie') 4712 .onClick(() => { 4713 try { 4714 web_webview.WebCookieManager.setCookie('https://www.example.com', 'a=b'); 4715 } catch (error) { 4716 let e:business_error.BusinessError = error as business_error.BusinessError; 4717 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4718 } 4719 }) 4720 Web({ src: 'www.example.com', controller: this.controller }) 4721 } 4722 } 4723} 4724``` 4725 4726### saveCookieAsync 4727 4728static saveCookieAsync(callback: AsyncCallback\<void>): void 4729 4730Saves the cookies in the memory to the drive. This API uses an asynchronous callback to return the result. 4731 4732**System capability**: SystemCapability.Web.Webview.Core 4733 4734**Parameters** 4735 4736| Name | Type | Mandatory| Description | 4737| -------- | ---------------------- | ---- | :------------------------------------------------- | 4738| callback | AsyncCallback\<void> | Yes | Callback used to return whether the cookies are successfully saved.| 4739 4740**Example** 4741 4742```ts 4743// xxx.ets 4744import web_webview from '@ohos.web.webview' 4745import business_error from '@ohos.base' 4746 4747@Entry 4748@Component 4749struct WebComponent { 4750 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4751 4752 build() { 4753 Column() { 4754 Button('saveCookieAsync') 4755 .onClick(() => { 4756 try { 4757 web_webview.WebCookieManager.saveCookieAsync((error) => { 4758 if (error) { 4759 console.log("error: " + error); 4760 } 4761 }) 4762 } catch (error) { 4763 let e:business_error.BusinessError = error as business_error.BusinessError; 4764 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4765 } 4766 }) 4767 Web({ src: 'www.example.com', controller: this.controller }) 4768 } 4769 } 4770} 4771``` 4772 4773### saveCookieAsync 4774 4775static saveCookieAsync(): Promise\<void> 4776 4777Saves the cookies in the memory to the drive. This API uses a promise to return the result. 4778 4779**System capability**: SystemCapability.Web.Webview.Core 4780 4781**Return value** 4782 4783| Type | Description | 4784| ---------------- | ----------------------------------------- | 4785| Promise\<void> | Promise used to return the operation result.| 4786 4787**Example** 4788 4789```ts 4790// xxx.ets 4791import web_webview from '@ohos.web.webview' 4792import business_error from '@ohos.base' 4793 4794@Entry 4795@Component 4796struct WebComponent { 4797 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4798 4799 build() { 4800 Column() { 4801 Button('saveCookieAsync') 4802 .onClick(() => { 4803 try { 4804 web_webview.WebCookieManager.saveCookieAsync() 4805 .then(() => { 4806 console.log("saveCookieAsyncCallback success!"); 4807 }) 4808 .catch((error:business_error.BusinessError) => { 4809 console.error("error: " + error); 4810 }); 4811 } catch (error) { 4812 let e:business_error.BusinessError = error as business_error.BusinessError; 4813 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4814 } 4815 }) 4816 Web({ src: 'www.example.com', controller: this.controller }) 4817 } 4818 } 4819} 4820``` 4821 4822### putAcceptCookieEnabled 4823 4824static putAcceptCookieEnabled(accept: boolean): void 4825 4826Sets whether the **WebCookieManager** instance has the permission to send and receive cookies. 4827 4828**System capability**: SystemCapability.Web.Webview.Core 4829 4830**Parameters** 4831 4832| Name| Type | Mandatory| Description | 4833| ------ | ------- | ---- | :----------------------------------- | 4834| accept | boolean | Yes | Whether the **WebCookieManager** instance has the permission to send and receive cookies.| 4835 4836**Example** 4837 4838```ts 4839// xxx.ets 4840import web_webview from '@ohos.web.webview' 4841import business_error from '@ohos.base' 4842 4843@Entry 4844@Component 4845struct WebComponent { 4846 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4847 4848 build() { 4849 Column() { 4850 Button('putAcceptCookieEnabled') 4851 .onClick(() => { 4852 try { 4853 web_webview.WebCookieManager.putAcceptCookieEnabled(false); 4854 } catch (error) { 4855 let e:business_error.BusinessError = error as business_error.BusinessError; 4856 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4857 } 4858 }) 4859 Web({ src: 'www.example.com', controller: this.controller }) 4860 } 4861 } 4862} 4863``` 4864 4865### isCookieAllowed 4866 4867static isCookieAllowed(): boolean 4868 4869Checks whether the **WebCookieManager** instance has the permission to send and receive cookies. 4870 4871**System capability**: SystemCapability.Web.Webview.Core 4872 4873**Return value** 4874 4875| Type | Description | 4876| ------- | -------------------------------- | 4877| boolean | Whether the **WebCookieManager** instance has the permission to send and receive cookies. The default value is **true**.| 4878 4879**Example** 4880 4881```ts 4882// xxx.ets 4883import web_webview from '@ohos.web.webview' 4884 4885@Entry 4886@Component 4887struct WebComponent { 4888 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4889 4890 build() { 4891 Column() { 4892 Button('isCookieAllowed') 4893 .onClick(() => { 4894 let result = web_webview.WebCookieManager.isCookieAllowed(); 4895 console.log("result: " + result); 4896 }) 4897 Web({ src: 'www.example.com', controller: this.controller }) 4898 } 4899 } 4900} 4901``` 4902 4903### putAcceptThirdPartyCookieEnabled 4904 4905static putAcceptThirdPartyCookieEnabled(accept: boolean): void 4906 4907Sets whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. 4908 4909**System capability**: SystemCapability.Web.Webview.Core 4910 4911**Parameters** 4912 4913| Name| Type | Mandatory| Description | 4914| ------ | ------- | ---- | :----------------------------------------- | 4915| accept | boolean | Yes | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies.| 4916 4917**Example** 4918 4919```ts 4920// xxx.ets 4921import web_webview from '@ohos.web.webview' 4922import business_error from '@ohos.base' 4923 4924@Entry 4925@Component 4926struct WebComponent { 4927 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4928 4929 build() { 4930 Column() { 4931 Button('putAcceptThirdPartyCookieEnabled') 4932 .onClick(() => { 4933 try { 4934 web_webview.WebCookieManager.putAcceptThirdPartyCookieEnabled(false); 4935 } catch (error) { 4936 let e:business_error.BusinessError = error as business_error.BusinessError; 4937 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4938 } 4939 }) 4940 Web({ src: 'www.example.com', controller: this.controller }) 4941 } 4942 } 4943} 4944``` 4945 4946### isThirdPartyCookieAllowed 4947 4948static isThirdPartyCookieAllowed(): boolean 4949 4950Checks whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. 4951 4952**System capability**: SystemCapability.Web.Webview.Core 4953 4954**Return value** 4955 4956| Type | Description | 4957| ------- | -------------------------------------- | 4958| boolean | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. The default value is **false**.| 4959 4960**Example** 4961 4962```ts 4963// xxx.ets 4964import web_webview from '@ohos.web.webview' 4965 4966@Entry 4967@Component 4968struct WebComponent { 4969 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4970 4971 build() { 4972 Column() { 4973 Button('isThirdPartyCookieAllowed') 4974 .onClick(() => { 4975 let result = web_webview.WebCookieManager.isThirdPartyCookieAllowed(); 4976 console.log("result: " + result); 4977 }) 4978 Web({ src: 'www.example.com', controller: this.controller }) 4979 } 4980 } 4981} 4982``` 4983 4984### existCookie 4985 4986static existCookie(): boolean 4987 4988Checks whether cookies exist. 4989 4990**System capability**: SystemCapability.Web.Webview.Core 4991 4992**Return value** 4993 4994| Type | Description | 4995| ------- | -------------------------------------- | 4996| boolean | Whether cookies exist.| 4997 4998**Example** 4999 5000```ts 5001// xxx.ets 5002import web_webview from '@ohos.web.webview' 5003 5004@Entry 5005@Component 5006struct WebComponent { 5007 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5008 5009 build() { 5010 Column() { 5011 Button('existCookie') 5012 .onClick(() => { 5013 let result = web_webview.WebCookieManager.existCookie(); 5014 console.log("result: " + result); 5015 }) 5016 Web({ src: 'www.example.com', controller: this.controller }) 5017 } 5018 } 5019} 5020``` 5021 5022### deleteEntireCookie 5023 5024static deleteEntireCookie(): void 5025 5026Deletes all cookies. 5027 5028**System capability**: SystemCapability.Web.Webview.Core 5029 5030**Example** 5031 5032```ts 5033// xxx.ets 5034import web_webview from '@ohos.web.webview' 5035 5036@Entry 5037@Component 5038struct WebComponent { 5039 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5040 5041 build() { 5042 Column() { 5043 Button('deleteEntireCookie') 5044 .onClick(() => { 5045 web_webview.WebCookieManager.deleteEntireCookie(); 5046 }) 5047 Web({ src: 'www.example.com', controller: this.controller }) 5048 } 5049 } 5050} 5051``` 5052 5053### deleteSessionCookie 5054 5055static deleteSessionCookie(): void 5056 5057Deletes all session cookies. 5058 5059**System capability**: SystemCapability.Web.Webview.Core 5060 5061**Example** 5062 5063```ts 5064// xxx.ets 5065import web_webview from '@ohos.web.webview' 5066 5067@Entry 5068@Component 5069struct WebComponent { 5070 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5071 5072 build() { 5073 Column() { 5074 Button('deleteSessionCookie') 5075 .onClick(() => { 5076 web_webview.WebCookieManager.deleteSessionCookie(); 5077 }) 5078 Web({ src: 'www.example.com', controller: this.controller }) 5079 } 5080 } 5081} 5082``` 5083 5084## WebStorage 5085 5086Implements a **WebStorage** object to manage the Web SQL database and HTML5 Web Storage APIs. All **\<Web>** components in an application share a **WebStorage** object. 5087 5088> **NOTE** 5089> 5090> You must load the **\<Web>** component before calling the APIs in **WebStorage**. 5091 5092### deleteOrigin 5093 5094static deleteOrigin(origin : string): void 5095 5096Deletes all data in the specified origin. 5097 5098**System capability**: SystemCapability.Web.Webview.Core 5099 5100**Parameters** 5101 5102| Name| Type | Mandatory| Description | 5103| ------ | ------ | ---- | ------------------------ | 5104| origin | string | Yes | Index of the origin, which is obtained through [getOrigins](#getorigins).| 5105 5106**Error codes** 5107 5108For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5109 5110| ID| Error Message | 5111| -------- | ------------------------------------------------------ | 5112| 17100011 | Invalid origin. | 5113 5114**Example** 5115 5116```ts 5117// xxx.ets 5118import web_webview from '@ohos.web.webview'; 5119import business_error from '@ohos.base'; 5120 5121@Entry 5122@Component 5123struct WebComponent { 5124 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5125 origin: string = "file:///"; 5126 5127 build() { 5128 Column() { 5129 Button('deleteOrigin') 5130 .onClick(() => { 5131 try { 5132 web_webview.WebStorage.deleteOrigin(this.origin); 5133 } catch (error) { 5134 let e: business_error.BusinessError = error as business_error.BusinessError; 5135 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5136 } 5137 5138 }) 5139 Web({ src: 'www.example.com', controller: this.controller }) 5140 .databaseAccess(true) 5141 } 5142 } 5143} 5144``` 5145 5146### getOrigins 5147 5148static getOrigins(callback: AsyncCallback\<Array\<WebStorageOrigin>>) : void 5149 5150Obtains information about all origins that are currently using the Web SQL Database. This API uses an asynchronous callback to return the result. 5151 5152**System capability**: SystemCapability.Web.Webview.Core 5153 5154**Parameters** 5155 5156| Name | Type | Mandatory| Description | 5157| -------- | -------------------------------------- | ---- | ------------------------------------------------------ | 5158| callback | AsyncCallback\<Array\<[WebStorageOrigin](#webstorageorigin)>> | Yes | Callback used to return the information about the origins. For details, see [WebStorageOrigin](#webstorageorigin).| 5159 5160**Error codes** 5161 5162For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5163 5164| ID| Error Message | 5165| -------- | ------------------------------------------------------ | 5166| 17100012 | Invalid web storage origin. | 5167 5168**Example** 5169 5170```ts 5171// xxx.ets 5172import web_webview from '@ohos.web.webview'; 5173import business_error from '@ohos.base'; 5174 5175@Entry 5176@Component 5177struct WebComponent { 5178 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5179 5180 build() { 5181 Column() { 5182 Button('getOrigins') 5183 .onClick(() => { 5184 try { 5185 web_webview.WebStorage.getOrigins((error, origins) => { 5186 if (error) { 5187 console.log('error: ' + JSON.stringify(error)); 5188 return; 5189 } 5190 for (let i = 0; i < origins.length; i++) { 5191 console.log('origin: ' + origins[i].origin); 5192 console.log('usage: ' + origins[i].usage); 5193 console.log('quota: ' + origins[i].quota); 5194 } 5195 }) 5196 } catch (error) { 5197 let e: business_error.BusinessError = error as business_error.BusinessError; 5198 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5199 } 5200 5201 }) 5202 Web({ src: 'www.example.com', controller: this.controller }) 5203 .databaseAccess(true) 5204 } 5205 } 5206} 5207``` 5208 5209### getOrigins 5210 5211static getOrigins() : Promise\<Array\<WebStorageOrigin>> 5212 5213Obtains information about all origins that are currently using the Web SQL Database. This API uses a promise to return the result. 5214 5215**System capability**: SystemCapability.Web.Webview.Core 5216 5217**Return value** 5218 5219| Type | Description | 5220| -------------------------------- | ------------------------------------------------------------ | 5221| Promise\<Array\<[WebStorageOrigin](#webstorageorigin)>> | Promise used to return the information about the origins. For details, see [WebStorageOrigin](#webstorageorigin).| 5222 5223**Error codes** 5224 5225For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5226 5227| ID| Error Message | 5228| -------- | ------------------------------------------------------ | 5229| 17100012 | Invalid web storage origin. | 5230 5231**Example** 5232 5233```ts 5234// xxx.ets 5235import web_webview from '@ohos.web.webview'; 5236import business_error from '@ohos.base'; 5237 5238@Entry 5239@Component 5240struct WebComponent { 5241 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5242 5243 build() { 5244 Column() { 5245 Button('getOrigins') 5246 .onClick(() => { 5247 try { 5248 web_webview.WebStorage.getOrigins() 5249 .then(origins => { 5250 for (let i = 0; i < origins.length; i++) { 5251 console.log('origin: ' + origins[i].origin); 5252 console.log('usage: ' + origins[i].usage); 5253 console.log('quota: ' + origins[i].quota); 5254 } 5255 }) 5256 .catch((e : business_error.BusinessError) => { 5257 console.log('error: ' + JSON.stringify(e)); 5258 }) 5259 } catch (error) { 5260 let e: business_error.BusinessError = error as business_error.BusinessError; 5261 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5262 } 5263 5264 }) 5265 Web({ src: 'www.example.com', controller: this.controller }) 5266 .databaseAccess(true) 5267 } 5268 } 5269} 5270``` 5271 5272### getOriginQuota 5273 5274static getOriginQuota(origin : string, callback : AsyncCallback\<number>) : void 5275 5276Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. 5277 5278**System capability**: SystemCapability.Web.Webview.Core 5279 5280**Parameters** 5281 5282| Name | Type | Mandatory| Description | 5283| -------- | --------------------- | ---- | ------------------ | 5284| origin | string | Yes | Index of the origin.| 5285| callback | AsyncCallback\<number> | Yes | Storage quota of the origin. | 5286 5287**Error codes** 5288 5289For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5290 5291| ID| Error Message | 5292| -------- | ------------------------------------------------------ | 5293| 17100011 | Invalid origin. | 5294 5295**Example** 5296 5297```ts 5298// xxx.ets 5299import web_webview from '@ohos.web.webview'; 5300import business_error from '@ohos.base'; 5301 5302@Entry 5303@Component 5304struct WebComponent { 5305 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5306 origin: string = "file:///"; 5307 5308 build() { 5309 Column() { 5310 Button('getOriginQuota') 5311 .onClick(() => { 5312 try { 5313 web_webview.WebStorage.getOriginQuota(this.origin, (error, quota) => { 5314 if (error) { 5315 console.log('error: ' + JSON.stringify(error)); 5316 return; 5317 } 5318 console.log('quota: ' + quota); 5319 }) 5320 } catch (error) { 5321 let e: business_error.BusinessError = error as business_error.BusinessError; 5322 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5323 } 5324 5325 }) 5326 Web({ src: 'www.example.com', controller: this.controller }) 5327 .databaseAccess(true) 5328 } 5329 } 5330} 5331``` 5332 5333### getOriginQuota 5334 5335static getOriginQuota(origin : string) : Promise\<number> 5336 5337Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. 5338 5339**System capability**: SystemCapability.Web.Webview.Core 5340 5341**Parameters** 5342 5343| Name| Type | Mandatory| Description | 5344| ------ | ------ | ---- | ------------------ | 5345| origin | string | Yes | Index of the origin.| 5346 5347**Return value** 5348 5349| Type | Description | 5350| --------------- | --------------------------------------- | 5351| Promise\<number> | Promise used to return the storage quota of the origin.| 5352 5353**Error codes** 5354 5355For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5356 5357| ID| Error Message | 5358| -------- | ------------------------------------------------------ | 5359| 17100011 | Invalid origin. | 5360 5361**Example** 5362 5363```ts 5364// xxx.ets 5365import web_webview from '@ohos.web.webview'; 5366import business_error from '@ohos.base'; 5367 5368@Entry 5369@Component 5370struct WebComponent { 5371 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5372 origin: string = "file:///"; 5373 5374 build() { 5375 Column() { 5376 Button('getOriginQuota') 5377 .onClick(() => { 5378 try { 5379 web_webview.WebStorage.getOriginQuota(this.origin) 5380 .then(quota => { 5381 console.log('quota: ' + quota); 5382 }) 5383 .catch((e : business_error.BusinessError) => { 5384 console.log('error: ' + JSON.stringify(e)); 5385 }) 5386 } catch (error) { 5387 let e: business_error.BusinessError = error as business_error.BusinessError; 5388 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5389 } 5390 5391 }) 5392 Web({ src: 'www.example.com', controller: this.controller }) 5393 .databaseAccess(true) 5394 } 5395 } 5396} 5397``` 5398 5399### getOriginUsage 5400 5401static getOriginUsage(origin : string, callback : AsyncCallback\<number>) : void 5402 5403Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. 5404 5405**System capability**: SystemCapability.Web.Webview.Core 5406 5407**Parameters** 5408 5409| Name | Type | Mandatory| Description | 5410| -------- | --------------------- | ---- | ------------------ | 5411| origin | string | Yes | Index of the origin.| 5412| callback | AsyncCallback\<number> | Yes | Storage usage of the origin. | 5413 5414**Error codes** 5415 5416For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5417 5418| ID| Error Message | 5419| -------- | ------------------------------------------------------ | 5420| 17100011 | Invalid origin. | 5421 5422**Example** 5423 5424```ts 5425// xxx.ets 5426import web_webview from '@ohos.web.webview'; 5427import business_error from '@ohos.base'; 5428 5429@Entry 5430@Component 5431struct WebComponent { 5432 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5433 origin: string = "file:///"; 5434 5435 build() { 5436 Column() { 5437 Button('getOriginUsage') 5438 .onClick(() => { 5439 try { 5440 web_webview.WebStorage.getOriginUsage(this.origin, (error, usage) => { 5441 if (error) { 5442 console.log('error: ' + JSON.stringify(error)); 5443 return; 5444 } 5445 console.log('usage: ' + usage); 5446 }) 5447 } catch (error) { 5448 let e: business_error.BusinessError = error as business_error.BusinessError; 5449 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5450 } 5451 5452 }) 5453 Web({ src: 'www.example.com', controller: this.controller }) 5454 .databaseAccess(true) 5455 } 5456 } 5457} 5458``` 5459 5460### getOriginUsage 5461 5462static getOriginUsage(origin : string) : Promise\<number> 5463 5464Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. 5465 5466**System capability**: SystemCapability.Web.Webview.Core 5467 5468**Parameters** 5469 5470| Name| Type | Mandatory| Description | 5471| ------ | ------ | ---- | ------------------ | 5472| origin | string | Yes | Index of the origin.| 5473 5474**Return value** 5475 5476| Type | Description | 5477| --------------- | ------------------------------------- | 5478| Promise\<number> | Promise used to return the storage usage of the origin.| 5479 5480**Error codes** 5481 5482For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5483 5484| ID| Error Message | 5485| -------- | ----------------------------------------------------- | 5486| 17100011 | Invalid origin. | 5487 5488**Example** 5489 5490```ts 5491// xxx.ets 5492import web_webview from '@ohos.web.webview'; 5493import business_error from '@ohos.base'; 5494 5495@Entry 5496@Component 5497struct WebComponent { 5498 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5499 origin: string = "file:///"; 5500 5501 build() { 5502 Column() { 5503 Button('getOriginUsage') 5504 .onClick(() => { 5505 try { 5506 web_webview.WebStorage.getOriginUsage(this.origin) 5507 .then(usage => { 5508 console.log('usage: ' + usage); 5509 }) 5510 .catch((e : business_error.BusinessError) => { 5511 console.log('error: ' + JSON.stringify(e)); 5512 }) 5513 } catch (error) { 5514 let e: business_error.BusinessError = error as business_error.BusinessError; 5515 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5516 } 5517 5518 }) 5519 Web({ src: 'www.example.com', controller: this.controller }) 5520 .databaseAccess(true) 5521 } 5522 } 5523} 5524``` 5525 5526### deleteAllData 5527 5528static deleteAllData(): void 5529 5530Deletes all data in the Web SQL Database. 5531 5532**System capability**: SystemCapability.Web.Webview.Core 5533 5534**Example** 5535 5536```ts 5537// xxx.ets 5538import web_webview from '@ohos.web.webview'; 5539import business_error from '@ohos.base'; 5540 5541@Entry 5542@Component 5543struct WebComponent { 5544 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5545 5546 build() { 5547 Column() { 5548 Button('deleteAllData') 5549 .onClick(() => { 5550 try { 5551 web_webview.WebStorage.deleteAllData(); 5552 } catch (error) { 5553 let e: business_error.BusinessError = error as business_error.BusinessError; 5554 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5555 } 5556 }) 5557 Web({ src: 'www.example.com', controller: this.controller }) 5558 .databaseAccess(true) 5559 } 5560 } 5561} 5562``` 5563 5564## WebDataBase 5565 5566Implements a **WebDataBase** object. 5567 5568> **NOTE** 5569> 5570> You must load the **\<Web>** component before calling the APIs in **WebDataBase**. 5571 5572### getHttpAuthCredentials 5573 5574static getHttpAuthCredentials(host: string, realm: string): Array\<string> 5575 5576Retrieves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. 5577 5578**System capability**: SystemCapability.Web.Webview.Core 5579 5580**Parameters** 5581 5582| Name| Type | Mandatory| Description | 5583| ------ | ------ | ---- | ---------------------------- | 5584| host | string | Yes | Host to which HTTP authentication credentials apply.| 5585| realm | string | Yes | Realm to which HTTP authentication credentials apply. | 5586 5587**Return value** 5588 5589| Type | Description | 5590| ----- | -------------------------------------------- | 5591| Array\<string> | Returns the array of the matching user names and passwords if the operation is successful; returns an empty array otherwise.| 5592 5593**Example** 5594 5595```ts 5596// xxx.ets 5597import web_webview from '@ohos.web.webview'; 5598import business_error from '@ohos.base'; 5599 5600@Entry 5601@Component 5602struct WebComponent { 5603 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5604 host: string = "www.spincast.org"; 5605 realm: string = "protected example"; 5606 username_password: string[] = []; 5607 5608 build() { 5609 Column() { 5610 Button('getHttpAuthCredentials') 5611 .onClick(() => { 5612 try { 5613 this.username_password = web_webview.WebDataBase.getHttpAuthCredentials(this.host, this.realm); 5614 console.log('num: ' + this.username_password.length); 5615 } catch (error) { 5616 let e: business_error.BusinessError = error as business_error.BusinessError; 5617 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5618 } 5619 }) 5620 Web({ src: 'www.example.com', controller: this.controller }) 5621 } 5622 } 5623} 5624``` 5625 5626### saveHttpAuthCredentials 5627 5628static saveHttpAuthCredentials(host: string, realm: string, username: string, password: string): void 5629 5630Saves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. 5631 5632**System capability**: SystemCapability.Web.Webview.Core 5633 5634**Parameters** 5635 5636| Name | Type | Mandatory| Description | 5637| -------- | ------ | ---- | ---------------------------- | 5638| host | string | Yes | Host to which HTTP authentication credentials apply.| 5639| realm | string | Yes | Realm to which HTTP authentication credentials apply. | 5640| username | string | Yes | User name. | 5641| password | string | Yes | Password. | 5642 5643**Example** 5644 5645```ts 5646// xxx.ets 5647import web_webview from '@ohos.web.webview'; 5648import business_error from '@ohos.base'; 5649 5650@Entry 5651@Component 5652struct WebComponent { 5653 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5654 host: string = "www.spincast.org"; 5655 realm: string = "protected example"; 5656 5657 build() { 5658 Column() { 5659 Button('saveHttpAuthCredentials') 5660 .onClick(() => { 5661 try { 5662 web_webview.WebDataBase.saveHttpAuthCredentials(this.host, this.realm, "Stromgol", "Laroche"); 5663 } catch (error) { 5664 let e: business_error.BusinessError = error as business_error.BusinessError; 5665 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5666 } 5667 }) 5668 Web({ src: 'www.example.com', controller: this.controller }) 5669 } 5670 } 5671} 5672``` 5673 5674### existHttpAuthCredentials 5675 5676static existHttpAuthCredentials(): boolean 5677 5678Checks whether any saved HTTP authentication credentials exist. This API returns the result synchronously. 5679 5680**System capability**: SystemCapability.Web.Webview.Core 5681 5682**Return value** 5683 5684| Type | Description | 5685| ------- | ------------------------------------------------------------ | 5686| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist; returns **false** otherwise.| 5687 5688**Example** 5689 5690```ts 5691// xxx.ets 5692import web_webview from '@ohos.web.webview'; 5693import business_error from '@ohos.base'; 5694 5695@Entry 5696@Component 5697struct WebComponent { 5698 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5699 5700 build() { 5701 Column() { 5702 Button('existHttpAuthCredentials') 5703 .onClick(() => { 5704 try { 5705 let result = web_webview.WebDataBase.existHttpAuthCredentials(); 5706 } catch (error) { 5707 let e: business_error.BusinessError = error as business_error.BusinessError; 5708 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5709 } 5710 }) 5711 Web({ src: 'www.example.com', controller: this.controller }) 5712 } 5713 } 5714} 5715``` 5716 5717### deleteHttpAuthCredentials 5718 5719static deleteHttpAuthCredentials(): void 5720 5721Deletes all HTTP authentication credentials saved in the cache. This API returns the result synchronously. 5722 5723**System capability**: SystemCapability.Web.Webview.Core 5724 5725**Example** 5726 5727```ts 5728// xxx.ets 5729import web_webview from '@ohos.web.webview'; 5730import business_error from '@ohos.base'; 5731 5732@Entry 5733@Component 5734struct WebComponent { 5735 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5736 5737 build() { 5738 Column() { 5739 Button('deleteHttpAuthCredentials') 5740 .onClick(() => { 5741 try { 5742 web_webview.WebDataBase.deleteHttpAuthCredentials(); 5743 } catch (error) { 5744 let e: business_error.BusinessError = error as business_error.BusinessError; 5745 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5746 } 5747 }) 5748 Web({ src: 'www.example.com', controller: this.controller }) 5749 } 5750 } 5751} 5752``` 5753 5754## GeolocationPermissions 5755 5756Implements a **GeolocationPermissions** object. 5757 5758> **NOTE** 5759> 5760> You must load the **\<Web>** component before calling the APIs in **GeolocationPermissions**. 5761 5762### Required Permissions 5763 5764**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). 5765 5766### allowGeolocation 5767 5768static allowGeolocation(origin: string): void 5769 5770Allows the specified origin to use the geolocation information. 5771 5772**System capability**: SystemCapability.Web.Webview.Core 5773 5774**Parameters** 5775 5776| Name| Type | Mandatory| Description | 5777| ------ | ------ | ---- | ------------------ | 5778| origin | string | Yes |Index of the origin.| 5779 5780**Error codes** 5781 5782For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5783 5784| ID| Error Message | 5785| -------- | ------------------------------------------------------ | 5786| 17100011 | Invalid origin. | 5787 5788**Example** 5789 5790```ts 5791// xxx.ets 5792import web_webview from '@ohos.web.webview'; 5793import business_error from '@ohos.base'; 5794 5795@Entry 5796@Component 5797struct WebComponent { 5798 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5799 origin: string = "file:///"; 5800 5801 build() { 5802 Column() { 5803 Button('allowGeolocation') 5804 .onClick(() => { 5805 try { 5806 web_webview.GeolocationPermissions.allowGeolocation(this.origin); 5807 } catch (error) { 5808 let e: business_error.BusinessError = error as business_error.BusinessError; 5809 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5810 } 5811 }) 5812 Web({ src: 'www.example.com', controller: this.controller }) 5813 } 5814 } 5815} 5816``` 5817 5818### deleteGeolocation 5819 5820static deleteGeolocation(origin: string): void 5821 5822Clears the geolocation permission status of a specified origin. 5823 5824**System capability**: SystemCapability.Web.Webview.Core 5825 5826**Parameters** 5827 5828| Name| Type | Mandatory| Description | 5829| ------ | ------ | ---- | ------------------ | 5830| origin | string | Yes | Index of the origin.| 5831 5832**Error codes** 5833 5834For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5835 5836| ID| Error Message | 5837| -------- | ------------------------------------------------------ | 5838| 17100011 | Invalid origin. | 5839 5840**Example** 5841 5842```ts 5843// xxx.ets 5844import web_webview from '@ohos.web.webview'; 5845import business_error from '@ohos.base'; 5846 5847@Entry 5848@Component 5849struct WebComponent { 5850 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5851 origin: string = "file:///"; 5852 5853 build() { 5854 Column() { 5855 Button('deleteGeolocation') 5856 .onClick(() => { 5857 try { 5858 web_webview.GeolocationPermissions.deleteGeolocation(this.origin); 5859 } catch (error) { 5860 let e: business_error.BusinessError = error as business_error.BusinessError; 5861 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5862 } 5863 }) 5864 Web({ src: 'www.example.com', controller: this.controller }) 5865 } 5866 } 5867} 5868``` 5869 5870### getAccessibleGeolocation 5871 5872static getAccessibleGeolocation(origin: string, callback: AsyncCallback\<boolean>): void 5873 5874Obtains the geolocation permission status of the specified origin. This API uses an asynchronous callback to return the result. 5875 5876**System capability**: SystemCapability.Web.Webview.Core 5877 5878**Parameters** 5879 5880| Name | Type | Mandatory| Description | 5881| -------- | ---------------------- | ---- | ------------------------------------------------------------ | 5882| origin | string | Yes | Index of the origin. | 5883| 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.| 5884 5885**Error codes** 5886 5887For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5888 5889| ID| Error Message | 5890| -------- | ------------------------------------------------------ | 5891| 17100011 | Invalid origin. | 5892 5893**Example** 5894 5895```ts 5896// xxx.ets 5897import web_webview from '@ohos.web.webview'; 5898import business_error from '@ohos.base'; 5899 5900@Entry 5901@Component 5902struct WebComponent { 5903 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5904 origin: string = "file:///"; 5905 5906 build() { 5907 Column() { 5908 Button('getAccessibleGeolocation') 5909 .onClick(() => { 5910 try { 5911 web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin, (error, result) => { 5912 if (error) { 5913 console.log('getAccessibleGeolocationAsync error: ' + JSON.stringify(error)); 5914 return; 5915 } 5916 console.log('getAccessibleGeolocationAsync result: ' + result); 5917 }); 5918 } catch (error) { 5919 let e: business_error.BusinessError = error as business_error.BusinessError; 5920 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5921 } 5922 }) 5923 Web({ src: 'www.example.com', controller: this.controller }) 5924 } 5925 } 5926} 5927``` 5928 5929### getAccessibleGeolocation 5930 5931static getAccessibleGeolocation(origin: string): Promise\<boolean> 5932 5933Obtains the geolocation permission status of the specified origin. This API uses a promise to return the result. 5934 5935**System capability**: SystemCapability.Web.Webview.Core 5936 5937**Parameters** 5938 5939| Name| Type| Mandatory| Description | 5940| ------ | -------- | ---- | -------------------- | 5941| origin | string | Yes | Index of the origin.| 5942 5943**Return value** 5944 5945| Type | Description | 5946| ---------------- | ------------------------------------------------------------ | 5947| 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.| 5948 5949**Error codes** 5950 5951For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5952 5953| ID| Error Message | 5954| -------- | ------------------------------------------------------ | 5955| 17100011 | Invalid origin. | 5956 5957**Example** 5958 5959```ts 5960// xxx.ets 5961import web_webview from '@ohos.web.webview'; 5962import business_error from '@ohos.base'; 5963 5964@Entry 5965@Component 5966struct WebComponent { 5967 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5968 origin: string = "file:///"; 5969 5970 build() { 5971 Column() { 5972 Button('getAccessibleGeolocation') 5973 .onClick(() => { 5974 try { 5975 web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin) 5976 .then(result => { 5977 console.log('getAccessibleGeolocationPromise result: ' + result); 5978 }).catch((error : business_error.BusinessError) => { 5979 console.log('getAccessibleGeolocationPromise error: ' + JSON.stringify(error)); 5980 }); 5981 } catch (error) { 5982 let e: business_error.BusinessError = error as business_error.BusinessError; 5983 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5984 } 5985 }) 5986 Web({ src: 'www.example.com', controller: this.controller }) 5987 } 5988 } 5989} 5990``` 5991 5992### getStoredGeolocation 5993 5994static getStoredGeolocation(callback: AsyncCallback\<Array\<string>>): void 5995 5996Obtains the geolocation permission status of all origins. This API uses an asynchronous callback to return the result. 5997 5998**System capability**: SystemCapability.Web.Webview.Core 5999 6000**Parameters** 6001 6002| Name | Type | Mandatory| Description | 6003| -------- | ---------------------------- | ---- | ---------------------------------------- | 6004| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return the geolocation permission status of all origins.| 6005 6006**Example** 6007 6008```ts 6009// xxx.ets 6010import web_webview from '@ohos.web.webview'; 6011import business_error from '@ohos.base'; 6012 6013@Entry 6014@Component 6015struct WebComponent { 6016 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6017 6018 build() { 6019 Column() { 6020 Button('getStoredGeolocation') 6021 .onClick(() => { 6022 try { 6023 web_webview.GeolocationPermissions.getStoredGeolocation((error, origins) => { 6024 if (error) { 6025 console.log('getStoredGeolocationAsync error: ' + JSON.stringify(error)); 6026 return; 6027 } 6028 let origins_str: string = origins.join(); 6029 console.log('getStoredGeolocationAsync origins: ' + origins_str); 6030 }); 6031 } catch (error) { 6032 let e: business_error.BusinessError = error as business_error.BusinessError; 6033 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 6034 } 6035 }) 6036 Web({ src: 'www.example.com', controller: this.controller }) 6037 } 6038 } 6039} 6040``` 6041 6042### getStoredGeolocation 6043 6044static getStoredGeolocation(): Promise\<Array\<string>> 6045 6046Obtains the geolocation permission status of all origins. This API uses a promise to return the result. 6047 6048**System capability**: SystemCapability.Web.Webview.Core 6049 6050**Return value** 6051 6052| Type | Description | 6053| ---------------------- | --------------------------------------------------------- | 6054| Promise\<Array\<string>> | Promise used to return the geolocation permission status of all origins.| 6055 6056**Example** 6057 6058```ts 6059// xxx.ets 6060import web_webview from '@ohos.web.webview'; 6061import business_error from '@ohos.base'; 6062 6063@Entry 6064@Component 6065struct WebComponent { 6066 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6067 6068 build() { 6069 Column() { 6070 Button('getStoredGeolocation') 6071 .onClick(() => { 6072 try { 6073 web_webview.GeolocationPermissions.getStoredGeolocation() 6074 .then(origins => { 6075 let origins_str: string = origins.join(); 6076 console.log('getStoredGeolocationPromise origins: ' + origins_str); 6077 }).catch((error : business_error.BusinessError) => { 6078 console.log('getStoredGeolocationPromise error: ' + JSON.stringify(error)); 6079 }); 6080 } catch (error) { 6081 let e: business_error.BusinessError = error as business_error.BusinessError; 6082 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 6083 } 6084 }) 6085 Web({ src: 'www.example.com', controller: this.controller }) 6086 } 6087 } 6088} 6089``` 6090 6091### deleteAllGeolocation 6092 6093static deleteAllGeolocation(): void 6094 6095Clears the geolocation permission status of all sources. 6096 6097**System capability**: SystemCapability.Web.Webview.Core 6098 6099**Example** 6100 6101```ts 6102// xxx.ets 6103import web_webview from '@ohos.web.webview'; 6104import business_error from '@ohos.base'; 6105 6106@Entry 6107@Component 6108struct WebComponent { 6109 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6110 6111 build() { 6112 Column() { 6113 Button('deleteAllGeolocation') 6114 .onClick(() => { 6115 try { 6116 web_webview.GeolocationPermissions.deleteAllGeolocation(); 6117 } catch (error) { 6118 let e: business_error.BusinessError = error as business_error.BusinessError; 6119 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 6120 } 6121 }) 6122 Web({ src: 'www.example.com', controller: this.controller }) 6123 } 6124 } 6125} 6126``` 6127## WebHeader 6128Describes the request/response header returned by the **\<Web>** component. 6129 6130**System capability**: SystemCapability.Web.Webview.Core 6131 6132| Name | Type | Readable| Writable|Description | 6133| ----------- | ------ | -----|------|------------------- | 6134| headerKey | string | Yes| Yes| Key of the request/response header. | 6135| headerValue | string | Yes| Yes| Value of the request/response header.| 6136 6137## WebHitTestType 6138 6139**System capability**: SystemCapability.Web.Webview.Core 6140 6141| Name | Value| Description | 6142| ------------- | -- |----------------------------------------- | 6143| EditText | 0 |Editable area. | 6144| Email | 1 |Email address. | 6145| HttpAnchor | 2 |Hyperlink whose **src** is **http**. | 6146| HttpAnchorImg | 3 |Image with a hyperlink, where **src** is **http**.| 6147| Img | 4 |HTML::img tag. | 6148| Map | 5 |Geographical address. | 6149| Phone | 6 |Phone number. | 6150| Unknown | 7 |Unknown content. | 6151 6152## HitTestValue 6153 6154Provides the element information of the area being clicked. For details about the sample code, see **getHitTestValue**. 6155 6156**System capability**: SystemCapability.Web.Webview.Core 6157 6158| Name| Type| Readable| Writable| Description| 6159| ---- | ---- | ---- | ---- |---- | 6160| type | [WebHitTestType](#webhittesttype) | Yes| No| Element type of the area being clicked.| 6161| 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.| 6162 6163## WebMessage 6164 6165Describes the data types supported for [WebMessagePort](#webmessageport). 6166 6167**System capability**: SystemCapability.Web.Webview.Core 6168 6169| Type | Description | 6170| -------- | -------------------------------------- | 6171| string | String type.| 6172| ArrayBuffer | Binary type.| 6173 6174## JsMessageType<sup>10+</sup> 6175 6176Describes the type of the returned result of script execution using [runJavaScirptExt](#runjavascriptext10). 6177 6178**System capability**: SystemCapability.Web.Webview.Core 6179 6180| Name | Value| Description | 6181| ------------ | -- |--------------------------------- | 6182| NOT_SUPPORT | 0 |Unsupported data type.| 6183| STRING | 1 |String type.| 6184| NUMBER | 2 |Number type.| 6185| BOOLEAN | 3 |Boolean type.| 6186| ARRAY_BUFFER | 4 |Raw binary data buffer.| 6187| ARRAY | 5 |Array type.| 6188 6189## WebMessageType<sup>10+</sup> 6190 6191Describes the data type supported by the [webMessagePort](#webmessageport) API. 6192 6193**System capability**: SystemCapability.Web.Webview.Core 6194 6195| Name | Value| Description | 6196| ------------ | -- |------------------------------- | 6197| NOT_SUPPORT | 0 |Unsupported data type.| 6198| STRING | 1 |String type.| 6199| NUMBER | 2 |Number type.| 6200| BOOLEAN | 3 |Boolean type.| 6201| ARRAY_BUFFER | 4 |Raw binary data buffer.| 6202| ARRAY | 5 |Array type.| 6203| ERROR | 6 |Error object type.| 6204 6205## JsMessageExt<sup>10+</sup> 6206 6207Implements the **JsMessageExt** data object that is returned after script execution using the [runJavaScirptExt](#runjavascriptext10) API. 6208 6209### getType<sup>10+</sup> 6210 6211getType(): JsMessageType 6212 6213Obtains the type of the data object. 6214 6215**System capability**: SystemCapability.Web.Webview.Core 6216 6217**Return value** 6218 6219| Type | Description | 6220| --------------| --------------------------------------------------------- | 6221| [JsMessageType](#jsmessagetype10) | Type of the data object that is returned after script execution using the [runJavaScirptExt](#runjavascriptext10) API.| 6222 6223### getString<sup>10+</sup> 6224 6225getString(): string 6226 6227Obtains string-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 6228 6229**System capability**: SystemCapability.Web.Webview.Core 6230 6231**Return value** 6232 6233| Type | Description | 6234| --------------| ------------- | 6235| string | Data of the string type.| 6236 6237**Error codes** 6238 6239For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 6240 6241| ID| Error Message | 6242| -------- | ------------------------------------- | 6243| 17100014 | The type does not match with the value of the result. | 6244 6245### getNumber<sup>10+</sup> 6246 6247getNumber(): number 6248 6249Obtains number-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 6250 6251**System capability**: SystemCapability.Web.Webview.Core 6252 6253**Return value** 6254 6255| Type | Description | 6256| --------------| ------------- | 6257| number | Data of the number type.| 6258 6259**Error codes** 6260 6261For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 6262 6263| ID| Error Message | 6264| -------- | ------------------------------------- | 6265| 17100014 | The type does not match with the value of the result. | 6266 6267### getBoolean<sup>10+</sup> 6268 6269getBoolean(): boolean 6270 6271Obtains Boolean-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 6272 6273**System capability**: SystemCapability.Web.Webview.Core 6274 6275**Return value** 6276 6277| Type | Description | 6278| --------------| ------------- | 6279| boolean | Data of the Boolean type.| 6280 6281**Error codes** 6282 6283For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 6284 6285| ID| Error Message | 6286| -------- | ------------------------------------- | 6287| 17100014 | The type does not match with the value of the result. | 6288 6289### getArrayBuffer<sup>10+</sup> 6290 6291getArrayBuffer(): ArrayBuffer 6292 6293Obtains raw binary data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 6294**System capability**: SystemCapability.Web.Webview.Core 6295 6296**Return value** 6297 6298| Type | Description | 6299| --------------| ------------- | 6300| ArrayBuffer | Raw binary data.| 6301 6302**Error codes** 6303 6304For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 6305 6306| ID| Error Message | 6307| -------- | ------------------------------------- | 6308| 17100014 | The type does not match with the value of the result. | 6309 6310### getArray<sup>10+</sup> 6311 6312getArray(): Array\<string | number | boolean\> 6313 6314Obtains array-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 6315 6316**System capability**: SystemCapability.Web.Webview.Core 6317 6318**Return value** 6319 6320| Type | Description | 6321| --------------| ------------- | 6322| Array\<string | number | boolean\> | Data of the array type.| 6323 6324**Error codes** 6325 6326For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 6327 6328| ID| Error Message | 6329| -------- | ------------------------------------- | 6330| 17100014 | The type does not match with the value of the result. | 6331 6332## WebMessageExt<sup>10+</sup> 6333 6334Data object received and sent by the [webMessagePort](#webmessageport) interface. 6335 6336### getType<sup>10+</sup> 6337 6338getType(): WebMessageType 6339 6340Obtains the type of the data object. 6341 6342**System capability**: SystemCapability.Web.Webview.Core 6343 6344**Return value** 6345 6346| Type | Description | 6347| --------------| --------------------------------------------------------- | 6348| [WebMessageType](#webmessagetype10) | Data type supported by the [webMessagePort](#webmessageport) API.| 6349 6350### getString<sup>10+</sup> 6351 6352getString(): string 6353 6354Obtains string-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 6355 6356**System capability**: SystemCapability.Web.Webview.Core 6357 6358**Return value** 6359 6360| Type | Description | 6361| --------------| ------------- | 6362| string | Data of the string type.| 6363 6364**Error codes** 6365 6366For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 6367 6368| ID| Error Message | 6369| -------- | ------------------------------------- | 6370| 17100014 | The type does not match with the value of the web message. | 6371 6372### getNumber<sup>10+</sup> 6373 6374getNumber(): number 6375 6376Obtains number-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 6377 6378**System capability**: SystemCapability.Web.Webview.Core 6379 6380**Return value** 6381 6382| Type | Description | 6383| --------------| ------------- | 6384| number | Data of the number type.| 6385 6386**Error codes** 6387 6388For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 6389 6390| ID| Error Message | 6391| -------- | ------------------------------------- | 6392| 17100014 | The type does not match with the value of the web message. | 6393 6394### getBoolean<sup>10+</sup> 6395 6396getBoolean(): boolean 6397 6398Obtains Boolean-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 6399 6400**System capability**: SystemCapability.Web.Webview.Core 6401 6402**Return value** 6403 6404| Type | Description | 6405| --------------| ------------- | 6406| boolean | Data of the Boolean type.| 6407 6408**Error codes** 6409 6410For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 6411 6412| ID| Error Message | 6413| -------- | ------------------------------------- | 6414| 17100014 | The type does not match with the value of the web message. | 6415 6416### getArrayBuffer<sup>10+</sup> 6417 6418getArrayBuffer(): ArrayBuffer 6419 6420Obtains raw binary data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 6421**System capability**: SystemCapability.Web.Webview.Core 6422 6423**Return value** 6424 6425| Type | Description | 6426| --------------| ------------- | 6427| ArrayBuffer | Raw binary data.| 6428 6429**Error codes** 6430 6431For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 6432 6433| ID| Error Message | 6434| -------- | ------------------------------------- | 6435| 17100014 | The type does not match with the value of the web message. | 6436 6437### getArray<sup>10+</sup> 6438 6439getArray(): Array\<string | number | boolean\> 6440 6441Obtains array-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 6442 6443**System capability**: SystemCapability.Web.Webview.Core 6444 6445**Return value** 6446 6447| Type | Description | 6448| --------------| ------------- | 6449| Array\<string | number | boolean\> | Data of the array type.| 6450 6451**Error codes** 6452 6453For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 6454 6455| ID| Error Message | 6456| -------- | ------------------------------------- | 6457| 17100014 | The type does not match with the value of the web message. | 6458 6459### getError<sup>10+</sup> 6460 6461getError(): Error 6462 6463Obtains the error-object-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 6464 6465**System capability**: SystemCapability.Web.Webview.Core 6466 6467**Return value** 6468 6469| Type | Description | 6470| --------------| ------------- | 6471| Error | Data of the error object type.| 6472 6473**Error codes** 6474 6475For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 6476 6477| ID| Error Message | 6478| -------- | ------------------------------------- | 6479| 17100014 | The type does not match with the value of the web message. | 6480 6481### setType<sup>10+</sup> 6482 6483setType(type: WebMessageType): void 6484 6485Sets the type for the data object. 6486 6487**System capability**: SystemCapability.Web.Webview.Core 6488 6489**Parameters** 6490 6491| Name| Type | Mandatory| Description | 6492| ------ | ------ | ---- | ---------------------- | 6493| type | [WebMessageType](#webmessagetype10) | Yes | Data type supported by the [webMessagePort](#webmessageport) API.| 6494 6495**Error codes** 6496 6497| ID| Error Message | 6498| -------- | ------------------------------------- | 6499| 17100014 | The type does not match with the value of the web message. | 6500 6501### setString<sup>10+</sup> 6502 6503setString(message: string): void 6504 6505Sets the string-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 6506 6507**System capability**: SystemCapability.Web.Webview.Core 6508 6509**Parameters** 6510 6511| Name| Type | Mandatory| Description | 6512| ------ | ------ | ---- | -------------------- | 6513| message | string | Yes | String type.| 6514 6515**Error codes** 6516 6517| ID| Error Message | 6518| -------- | ------------------------------------- | 6519| 17100014 | The type does not match with the value of the web message. | 6520 6521### setNumber<sup>10+</sup> 6522 6523setNumber(message: number): void 6524 6525Sets the number-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 6526 6527**System capability**: SystemCapability.Web.Webview.Core 6528 6529**Parameters** 6530 6531| Name| Type | Mandatory| Description | 6532| ------ | ------ | ---- | -------------------- | 6533| message | number | Yes | Data of the number type.| 6534 6535**Error codes** 6536 6537| ID| Error Message | 6538| -------- | ------------------------------------- | 6539| 17100014 | The type does not match with the value of the web message. | 6540 6541### setBoolean<sup>10+</sup> 6542 6543setBoolean(message: boolean): void 6544 6545Sets the Boolean-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 6546 6547**System capability**: SystemCapability.Web.Webview.Core 6548 6549**Parameters** 6550 6551| Name| Type | Mandatory| Description | 6552| ------ | ------ | ---- | -------------------- | 6553| message | boolean | Yes | Data of the Boolean type.| 6554 6555**Error codes** 6556 6557| ID| Error Message | 6558| -------- | ------------------------------------- | 6559| 17100014 | The type does not match with the value of the web message. | 6560 6561### setArrayBuffer<sup>10+</sup> 6562 6563setArrayBuffer(message: ArrayBuffer): void 6564 6565Sets the raw binary data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 6566 6567**System capability**: SystemCapability.Web.Webview.Core 6568 6569**Parameters** 6570 6571| Name| Type | Mandatory| Description | 6572| ------ | ------ | ---- | -------------------- | 6573| message | ArrayBuffer | Yes | Raw binary data.| 6574 6575**Error codes** 6576 6577| ID| Error Message | 6578| -------- | ------------------------------------- | 6579| 17100014 | The type does not match with the value of the web message. | 6580 6581### setArray<sup>10+</sup> 6582 6583setArray(message: Array\<string | number | boolean\>): void 6584 6585Sets the array-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 6586 6587**System capability**: SystemCapability.Web.Webview.Core 6588 6589**Parameters** 6590 6591| Name| Type | Mandatory| Description | 6592| ------ | ------ | ---- | -------------------- | 6593| message | Array\<string \| number \| boolean\> | Yes | Data of the array type.| 6594 6595**Error codes** 6596 6597| ID| Error Message | 6598| -------- | ------------------------------------- | 6599| 17100014 | The type does not match with the value of the web message. | 6600 6601### setError<sup>10+</sup> 6602 6603setError(message: Error): void 6604 6605Sets the error-object-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 6606 6607**System capability**: SystemCapability.Web.Webview.Core 6608 6609**Parameters** 6610 6611| Name| Type | Mandatory| Description | 6612| ------ | ------ | ---- | -------------------- | 6613| message | Error | Yes | Data of the error object type.| 6614 6615**Error codes** 6616 6617| ID| Error Message | 6618| -------- | ------------------------------------- | 6619| 17100014 | The type does not match with the value of the web message. | 6620 6621## WebStorageOrigin 6622 6623Provides usage information of the Web SQL Database. 6624 6625**System capability**: SystemCapability.Web.Webview.Core 6626 6627| Name | Type | Readable| Writable| Description| 6628| ------ | ------ | ---- | ---- | ---- | 6629| origin | string | Yes | No| Index of the origin.| 6630| usage | number | Yes | No| Storage usage of the origin. | 6631| quota | number | Yes | No| Storage quota of the origin. | 6632 6633## BackForwardList 6634 6635Provides the historical information list of the current webview. 6636 6637**System capability**: SystemCapability.Web.Webview.Core 6638 6639| Name | Type | Readable| Writable| Description | 6640| ------------ | ------ | ---- | ---- | ------------------------------------------------------------ | 6641| currentIndex | number | Yes | No | Index of the current page in the page history stack. | 6642| 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.| 6643 6644### getItemAtIndex 6645 6646getItemAtIndex(index: number): HistoryItem 6647 6648Obtains the page record with the specified index in the history stack. 6649 6650**System capability**: SystemCapability.Web.Webview.Core 6651 6652**Parameters** 6653 6654| Name| Type | Mandatory| Description | 6655| ------ | ------ | ---- | ---------------------- | 6656| index | number | Yes | Index of the target page record in the history stack.| 6657 6658**Return value** 6659 6660| Type | Description | 6661| --------------------------- | ------------ | 6662| [HistoryItem](#historyitem) | Historical page record.| 6663 6664**Example** 6665 6666```ts 6667// xxx.ets 6668import web_webview from '@ohos.web.webview'; 6669import image from "@ohos.multimedia.image"; 6670import business_error from '@ohos.base'; 6671 6672@Entry 6673@Component 6674struct WebComponent { 6675 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6676 @State icon: image.PixelMap | undefined = undefined; 6677 6678 build() { 6679 Column() { 6680 Button('getBackForwardEntries') 6681 .onClick(() => { 6682 try { 6683 let list = this.controller.getBackForwardEntries(); 6684 let historyItem = list.getItemAtIndex(list.currentIndex); 6685 console.log("HistoryItem: " + JSON.stringify(historyItem)); 6686 this.icon = historyItem.icon; 6687 } catch (error) { 6688 let e: business_error.BusinessError = error as business_error.BusinessError; 6689 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 6690 } 6691 }) 6692 Web({ src: 'www.example.com', controller: this.controller }) 6693 } 6694 } 6695} 6696``` 6697 6698## HistoryItem 6699 6700Describes a historical page record. 6701 6702**System capability**: SystemCapability.Web.Webview.Core 6703 6704| Name | Type | Readable| Writable| Description | 6705| ------------- | -------------------------------------- | ---- | ---- | ---------------------------- | 6706| icon | [PixelMap](js-apis-image.md#pixelmap7) | Yes | No | **PixelMap** object of the icon on the historical page.| 6707| historyUrl | string | Yes | No | URL of the historical page. | 6708| historyRawUrl | string | Yes | No | Original URL of the historical page. | 6709| title | string | Yes | No | Title of the historical page. | 6710 6711## WebCustomScheme 6712 6713Defines a custom URL scheme. 6714 6715**System capability**: SystemCapability.Web.Webview.Core 6716 6717| Name | Type | Readable| Writable| Description | 6718| -------------- | --------- | ---- | ---- | ---------------------------- | 6719| 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 (-). | 6720| isSupportCORS | boolean | Yes | Yes | Whether to support cross-origin resource sharing (CORS). | 6721| isSupportFetch | boolean | Yes | Yes | Whether to support fetch requests. | 6722 6723## SecureDnsMode<sup>10+</sup> 6724 6725Describes the mode in which the **\<Web>** component uses HTTPDNS. 6726 6727**System capability**: SystemCapability.Web.Webview.Core 6728 6729| Name | Value| Description | 6730| ------------- | -- |----------------------------------------- | 6731| OFF | 0 |HTTPDNS is not used. This value can be used to revoke the previously used HTTPDNS configuration.| 6732| AUTO | 1 |HTTPDNS is used in automatic mode. When the specified HTTPDNS server is unavailable for resolution, the component will fall back to the system DNS server.| 6733| SECURE_ONLY | 2 |The specified HTTPDNS server is forcibly used for DNS resolution.| 6734