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/declare-permissions.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| callback | 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 HTML 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 244class TestObj { 245 test(str: string): ArrayBuffer { 246 let buf = new ArrayBuffer(str.length); 247 let buff = new Uint8Array(buf); 248 249 for (let i = 0; i < str.length; i++) { 250 buff[i] = str.charCodeAt(i); 251 } 252 return buf; 253 } 254} 255 256// 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. 257@Entry 258@Component 259struct WebComponent { 260 controller: web_webview.WebviewController = new web_webview.WebviewController(); 261 ports: web_webview.WebMessagePort[] = []; 262 nativePort: web_webview.WebMessagePort | null = null; 263 @State msg1: string = ""; 264 @State msg2: string = ""; 265 message: web_webview.WebMessageExt = new web_webview.WebMessageExt(); 266 @State testObjtest: TestObj = new TestObj(); 267 268 build() { 269 Column() { 270 Text(this.msg1).fontSize(16) 271 Text(this.msg2).fontSize(16) 272 Button('SendToH5 setString').margin({ 273 right: 800, 274 }) 275 .onClick(() => { 276 // Use the local port to send messages to HTML5. 277 try { 278 console.log("In ArkTS side send true start"); 279 if (this.nativePort) { 280 this.message.setString("helloFromEts"); 281 this.message.setType(2); 282 this.nativePort.postMessageEventExt(this.message); 283 } 284 } 285 catch (error) { 286 let e: business_error.BusinessError = error as business_error.BusinessError; 287 console.log("In ArkTS side send message catch error:" + e.code + ", msg:" + e.message); 288 } 289 }) 290 Button('SendToH5 setNumber').margin({ 291 top: 10, 292 right: 800, 293 }) 294 .onClick(() => { 295 // Use the local port to send messages to HTML5. 296 try { 297 console.log("In ArkTS side send true start"); 298 if (this.nativePort) { 299 this.message.setNumber(12345); 300 this.nativePort.postMessageEventExt(this.message); 301 } 302 } 303 catch (error) { 304 let e: business_error.BusinessError = error as business_error.BusinessError; 305 console.log("In ArkTS side send message catch error:" + e.code + ", msg:" + e.message); 306 } 307 }) 308 Button('SendToH5 setBoolean').margin({ 309 top: -90, 310 }) 311 .onClick(() => { 312 // Use the local port to send messages to HTML5. 313 try { 314 console.log("In ArkTS side send true start"); 315 if (this.nativePort) { 316 this.message.setBoolean(true); 317 this.nativePort.postMessageEventExt(this.message); 318 } 319 } 320 catch (error) { 321 let e: business_error.BusinessError = error as business_error.BusinessError; 322 console.log("In ArkTS side send message catch error:" + e.code + ", msg:" + e.message); 323 } 324 }) 325 Button('SendToH5 setArrayBuffer').margin({ 326 top: 10, 327 }) 328 .onClick(() => { 329 // Use the local port to send messages to HTML5. 330 try { 331 console.log("In ArkTS side send true start"); 332 if (this.nativePort) { 333 this.message.setArrayBuffer(this.testObjtest.test("Name=test&Password=test")); 334 this.nativePort.postMessageEventExt(this.message); 335 } 336 } 337 catch (error) { 338 let e: business_error.BusinessError = error as business_error.BusinessError; 339 console.log("In ArkTS side send message catch error:" + e.code + ", msg:" + e.message); 340 } 341 }) 342 Button('SendToH5 setArray').margin({ 343 top: -90, 344 left: 800, 345 }) 346 .onClick(() => { 347 // Use the local port to send messages to HTML5. 348 try { 349 console.log("In ArkTS side send true start"); 350 if (this.nativePort) { 351 this.message.setArray([1,2,3]); 352 this.nativePort.postMessageEventExt(this.message); 353 } 354 } 355 catch (error) { 356 let e: business_error.BusinessError = error as business_error.BusinessError; 357 console.log("In ArkTS side send message catch error:" + e.code + ", msg:" + e.message); 358 } 359 }) 360 Button('SendToH5 setError').margin({ 361 top: 10, 362 left: 800, 363 }) 364 .onClick(() => { 365 // Use the local port to send messages to HTML5. 366 try { 367 console.log("In ArkTS side send true start"); 368 throw new ReferenceError("ReferenceError"); 369 } 370 catch (error) { 371 if (this.nativePort) { 372 this.message.setError(error); 373 this.nativePort.postMessageEventExt(this.message); 374 } 375 let e: business_error.BusinessError = error as business_error.BusinessError; 376 console.log("In ArkTS side send message catch error:" + e.code + ", msg:" + e.message); 377 } 378 }) 379 380 Web({ src: $rawfile('index.html'), controller: this.controller }) 381 .onPageEnd(() => { 382 console.log("In ArkTS side message onPageEnd init mesaage channel"); 383 // 1. Create a message port. 384 this.ports = this.controller.createWebMessagePorts(true); 385 // 2. Send port 1 to HTML5. 386 this.controller.postMessage("init_web_messageport", [this.ports[1]], "*"); 387 // 3. Save port 0 to the local host. 388 this.nativePort = this.ports[0]; 389 // 4. Set the callback. 390 this.nativePort.onMessageEventExt((result) => { 391 console.log("In ArkTS side got message"); 392 try { 393 let type = result.getType(); 394 console.log("In ArkTS side getType:" + type); 395 switch (type) { 396 case web_webview.WebMessageType.STRING: { 397 this.msg1 = "result type:" + typeof (result.getString()); 398 this.msg2 = "result getString:" + ((result.getString())); 399 break; 400 } 401 case web_webview.WebMessageType.NUMBER: { 402 this.msg1 = "result type:" + typeof (result.getNumber()); 403 this.msg2 = "result getNumber:" + ((result.getNumber())); 404 break; 405 } 406 case web_webview.WebMessageType.BOOLEAN: { 407 this.msg1 = "result type:" + typeof (result.getBoolean()); 408 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 409 break; 410 } 411 case web_webview.WebMessageType.ARRAY_BUFFER: { 412 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 413 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 414 break; 415 } 416 case web_webview.WebMessageType.ARRAY: { 417 this.msg1 = "result type:" + typeof (result.getArray()); 418 this.msg2 = "result getArray:" + result.getArray(); 419 break; 420 } 421 case web_webview.WebMessageType.ERROR: { 422 this.msg1 = "result type:" + typeof (result.getError()); 423 this.msg2 = "result getError:" + result.getError(); 424 break; 425 } 426 default: { 427 this.msg1 = "default break, type:" + type; 428 break; 429 } 430 } 431 } 432 catch (error) { 433 let e: business_error.BusinessError = error as business_error.BusinessError; 434 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 435 } 436 }); 437 }) 438 } 439 } 440} 441``` 442 443HTML file to be loaded: 444```html 445<!--index.html--> 446<!DOCTYPE html> 447<html lang="en-gb"> 448<head> 449 <title>WebView MessagePort Demo</title> 450</head> 451 452<body> 453<h1>Html5 Send and Receive Message</h1> 454<h3 id="msg">Receive string:</h3> 455<h3 id="msg2">Receive arraybuffer:</h3> 456<div style="font-size: 10pt; text-align: center;"> 457 <input type="button" value="Send String" onclick="postStringToApp();" /><br/> 458</div> 459</body> 460<script src="index.js"></script> 461</html> 462``` 463 464```js 465//index.js 466var h5Port; 467window.addEventListener('message', function(event) { 468 if (event.data == 'init_web_messageport') { 469 if(event.ports[0] != null) { 470 h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side. 471 h5Port.onmessage = function(event) { 472 console.log("hwd In html got message"); 473 // 2. Receive the message sent from the eTS side. 474 var result = event.data; 475 console.log("In html got message, typeof: ", typeof(result)); 476 console.log("In html got message, result: ", (result)); 477 if (typeof(result) == "string") { 478 console.log("In html got message, String: ", result); 479 document.getElementById("msg").innerHTML = "String:" + result; 480 } else if (typeof(result) == "number") { 481 console.log("In html side got message, number: ", result); 482 document.getElementById("msg").innerHTML = "Number:" + result; 483 } else if (typeof(result) == "boolean") { 484 console.log("In html side got message, boolean: ", result); 485 document.getElementById("msg").innerHTML = "Boolean:" + result; 486 } else if (typeof(result) == "object") { 487 if (result instanceof ArrayBuffer) { 488 document.getElementById("msg2").innerHTML = "ArrayBuffer:" + result.byteLength; 489 console.log("In html got message, byteLength: ", result.byteLength); 490 } else if (result instanceof Error) { 491 console.log("In html error message, err:" + (result)); 492 console.log("In html error message, typeof err:" + typeof(result)); 493 document.getElementById("msg2").innerHTML = "Error:" + result.name + ", msg:" + result.message; 494 } else if (result instanceof Array) { 495 console.log("In html got message, Array"); 496 console.log("In html got message, Array length:" + result.length); 497 console.log("In html got message, Array[0]:" + (result[0])); 498 console.log("In html got message, typeof Array[0]:" + typeof(result[0])); 499 document.getElementById("msg2").innerHTML = "Array len:" + result.length + ", value:" + result; 500 } else { 501 console.log("In html got message, not any instance of support type"); 502 document.getElementById("msg").innerHTML = "not any instance of support type"; 503 } 504 } else { 505 console.log("In html got message, not support type"); 506 document.getElementById("msg").innerHTML = "not support type"; 507 } 508 } 509 h5Port.onmessageerror = (event) => { 510 console.error(`hwd In html Error receiving message: ${event}`); 511 }; 512 } 513 } 514}) 515 516// Use h5Port to send a message of the string type to the ets side. 517function postStringToApp() { 518 if (h5Port) { 519 console.log("In html send string message"); 520 h5Port.postMessage("hello"); 521 console.log("In html send string message end"); 522 } else { 523 console.error("In html h5port is null, please init first"); 524 } 525} 526``` 527 528### close 529 530close(): void 531 532Closes this message port. To use this API, a message port must first be created using [createWebMessagePorts](#createwebmessageports). 533 534**System capability**: SystemCapability.Web.Webview.Core 535 536**Example** 537 538```ts 539// xxx.ets 540import web_webview from '@ohos.web.webview'; 541import business_error from '@ohos.base'; 542 543@Entry 544@Component 545struct WebComponent { 546 controller: web_webview.WebviewController = new web_webview.WebviewController(); 547 msgPort: web_webview.WebMessagePort[] = []; 548 549 build() { 550 Column() { 551 // Use createWebMessagePorts to create a message port. 552 Button('createWebMessagePorts') 553 .onClick(() => { 554 try { 555 this.msgPort = this.controller.createWebMessagePorts(); 556 console.log("createWebMessagePorts size:" + this.msgPort.length) 557 } catch (error) { 558 let e: business_error.BusinessError = error as business_error.BusinessError; 559 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 560 } 561 }) 562 Button('close') 563 .onClick(() => { 564 try { 565 if (this.msgPort && this.msgPort.length == 2) { 566 this.msgPort[1].close(); 567 } else { 568 console.error("msgPort is null, Please initialize first"); 569 } 570 } catch (error) { 571 let e: business_error.BusinessError = error as business_error.BusinessError; 572 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 573 } 574 }) 575 Web({ src: 'www.example.com', controller: this.controller }) 576 } 577 } 578} 579``` 580 581## WebviewController 582 583Implements 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. 584 585### initializeWebEngine 586 587static initializeWebEngine(): void 588 589Loads 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. 590 591**System capability**: SystemCapability.Web.Webview.Core 592 593**Example** 594 595The following code snippet exemplifies calling this API after the EntryAbility is created. 596 597```ts 598// xxx.ts 599import UIAbility from '@ohos.app.ability.UIAbility'; 600import web_webview from '@ohos.web.webview'; 601import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 602import Want from '@ohos.app.ability.Want'; 603 604export default class EntryAbility extends UIAbility { 605 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 606 console.log("EntryAbility onCreate") 607 web_webview.WebviewController.initializeWebEngine() 608 console.log("EntryAbility onCreate done") 609 } 610} 611``` 612 613### setHttpDns<sup>10+</sup> 614 615static setHttpDns(secureDnsMode:SecureDnsMode, secureDnsConfig:string): void 616 617Sets how the \<Web> component uses HTTPDNS for DNS resolution. 618 619**System capability**: SystemCapability.Web.Webview.Core 620 621**Parameters** 622 623| Name | Type | Mandatory | Description| 624| ------------------ | ------- | ---- | ------------- | 625| secureDnsMode | [SecureDnsMode](#securednsmode10) | Yes | Mode in which HTTPDNS is used.| 626| secureDnsConfig | string | Yes| Information about the HTTPDNS server to use, which must use HTTPS. Only one HTTPDNS server can be configured.| 627 628**Example** 629 630```ts 631// xxx.ts 632import UIAbility from '@ohos.app.ability.UIAbility'; 633import web_webview from '@ohos.web.webview'; 634import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 635import Want from '@ohos.app.ability.Want'; 636import business_error from '@ohos.base'; 637 638export default class EntryAbility extends UIAbility { 639 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 640 console.log("EntryAbility onCreate") 641 try { 642 web_webview.WebviewController.setHttpDns(web_webview.SecureDnsMode.AUTO, "https://example1.test") 643 } catch (error) { 644 let e: business_error.BusinessError = error as business_error.BusinessError; 645 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 646 } 647 648 AppStorage.setOrCreate("abilityWant", want); 649 console.log("EntryAbility onCreate done") 650 } 651} 652``` 653 654### setWebDebuggingAccess 655 656static setWebDebuggingAccess(webDebuggingAccess: boolean): void 657 658Sets whether to enable web debugging. For details, see [Debugging Frontend Pages by Using DevTools](../../web/web-debugging-with-devtools.md). 659 660**System capability**: SystemCapability.Web.Webview.Core 661 662**Parameters** 663 664| Name | Type | Mandatory | Description| 665| ------------------ | ------- | ---- | ------------- | 666| webDebuggingAccess | boolean | Yes | Whether to enable web debugging.| 667 668**Example** 669 670```ts 671// xxx.ets 672import web_webview from '@ohos.web.webview'; 673import business_error from '@ohos.base'; 674 675@Entry 676@Component 677struct WebComponent { 678 controller: web_webview.WebviewController = new web_webview.WebviewController(); 679 680 aboutToAppear(): void { 681 try { 682 web_webview.WebviewController.setWebDebuggingAccess(true); 683 } catch (error) { 684 let e: business_error.BusinessError = error as business_error.BusinessError; 685 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 686 } 687 } 688 689 build() { 690 Column() { 691 Web({ src: 'www.example.com', controller: this.controller }) 692 } 693 } 694} 695``` 696 697### loadUrl 698 699loadUrl(url: string | Resource, headers?: Array\<WebHeader>): void 700 701Loads a specified URL. 702 703**System capability**: SystemCapability.Web.Webview.Core 704 705**Parameters** 706 707| Name | Type | Mandatory| Description | 708| ------- | ---------------- | ---- | :-------------------- | 709| url | string \| Resource | Yes | URL to load. | 710| headers | Array\<[WebHeader](#webheader)> | No | Additional HTTP request header of the URL.| 711 712**Error codes** 713 714For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 715 716| ID| Error Message | 717| -------- | ------------------------------------------------------------ | 718| 17100001 | Init error. The WebviewController must be associated with a Web component. | 719| 17100002 | Invalid url. | 720| 17100003 | Invalid resource path or file type. | 721 722**Example** 723 724```ts 725// xxx.ets 726import web_webview from '@ohos.web.webview'; 727import business_error from '@ohos.base'; 728 729@Entry 730@Component 731struct WebComponent { 732 controller: web_webview.WebviewController = new web_webview.WebviewController(); 733 734 build() { 735 Column() { 736 Button('loadUrl') 737 .onClick(() => { 738 try { 739 // The URL to be loaded is of the string type. 740 this.controller.loadUrl('www.example.com'); 741 } catch (error) { 742 let e: business_error.BusinessError = error as business_error.BusinessError; 743 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 744 } 745 }) 746 Web({ src: 'www.example.com', controller: this.controller }) 747 } 748 } 749} 750``` 751 752```ts 753// xxx.ets 754import web_webview from '@ohos.web.webview'; 755import business_error from '@ohos.base'; 756 757@Entry 758@Component 759struct WebComponent { 760 controller: web_webview.WebviewController = new web_webview.WebviewController(); 761 762 build() { 763 Column() { 764 Button('loadUrl') 765 .onClick(() => { 766 try { 767 // The headers parameter is passed. 768 this.controller.loadUrl('www.example.com', [{ headerKey: "headerKey", headerValue: "headerValue" }]); 769 } catch (error) { 770 let e: business_error.BusinessError = error as business_error.BusinessError; 771 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 772 } 773 }) 774 Web({ src: 'www.example.com', controller: this.controller }) 775 } 776 } 777} 778``` 779 780There are three methods for loading local resource files: 781 7821. Using $rawfile 783```ts 784// xxx.ets 785import web_webview from '@ohos.web.webview'; 786import business_error from '@ohos.base'; 787 788@Entry 789@Component 790struct WebComponent { 791 controller: web_webview.WebviewController = new web_webview.WebviewController(); 792 793 build() { 794 Column() { 795 Button('loadUrl') 796 .onClick(() => { 797 try { 798 // Load a local resource file through $rawfile. 799 this.controller.loadUrl($rawfile('index.html')); 800 } catch (error) { 801 let e: business_error.BusinessError = error as business_error.BusinessError; 802 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 803 } 804 }) 805 Web({ src: 'www.example.com', controller: this.controller }) 806 } 807 } 808} 809``` 810 8112. Using the resources protocol 812```ts 813// xxx.ets 814import web_webview from '@ohos.web.webview'; 815import business_error from '@ohos.base'; 816 817@Entry 818@Component 819struct WebComponent { 820 controller: web_webview.WebviewController = new web_webview.WebviewController(); 821 822 build() { 823 Column() { 824 Button('loadUrl') 825 .onClick(() => { 826 try { 827 // Load local resource files through the resource protocol. 828 this.controller.loadUrl("resource://rawfile/index.html"); 829 } catch (error) { 830 let e: business_error.BusinessError = error as business_error.BusinessError; 831 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 832 } 833 }) 834 Web({ src: 'www.example.com', controller: this.controller }) 835 } 836 } 837} 838``` 839 8403. 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). 841 842HTML file to be loaded: 843```html 844<!-- index.html --> 845<!DOCTYPE html> 846<html> 847 <body> 848 <p>Hello World</p> 849 </body> 850</html> 851``` 852 853### loadData 854 855loadData(data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string): void 856 857Loads specified data. 858 859**System capability**: SystemCapability.Web.Webview.Core 860 861**Parameters** 862 863| Name | Type | Mandatory| Description | 864| ---------- | ------ | ---- | ------------------------------------------------------------ | 865| data | string | Yes | Character string obtained after being Base64 or URL encoded. | 866| mimeType | string | Yes | Media type (MIME). | 867| encoding | string | Yes | Encoding type, which can be Base64 or URL. | 868| baseUrl | string | No | URL (HTTP/HTTPS/data compliant), which is assigned by the **\<Web>** component to **window.origin**.| 869| 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.| 870 871> **NOTE** 872> 873> To load a local image, you can assign a space to either **baseUrl** or **historyUrl**. For details, see the sample code. 874> In the scenario of loading a local image, **baseUrl** and **historyUrl** cannot be both empty. Otherwise, the image cannot be loaded. 875 876**Error codes** 877 878For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 879 880| ID| Error Message | 881| -------- | ------------------------------------------------------------ | 882| 17100001 | Init error. The WebviewController must be associated with a Web component. | 883 884**Example** 885 886```ts 887// xxx.ets 888import web_webview from '@ohos.web.webview'; 889import business_error from '@ohos.base'; 890 891@Entry 892@Component 893struct WebComponent { 894 controller: web_webview.WebviewController = new web_webview.WebviewController(); 895 896 build() { 897 Column() { 898 Button('loadData') 899 .onClick(() => { 900 try { 901 this.controller.loadData( 902 "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>", 903 "text/html", 904 "UTF-8" 905 ); 906 } catch (error) { 907 let e: business_error.BusinessError = error as business_error.BusinessError; 908 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 909 } 910 }) 911 Web({ src: 'www.example.com', controller: this.controller }) 912 } 913 } 914} 915``` 916 917Example of loading local resource: 918```ts 919// xxx.ets 920import web_webview from '@ohos.web.webview'; 921import business_error from '@ohos.base'; 922 923@Entry 924@Component 925struct WebComponent { 926 controller: web_webview.WebviewController = new web_webview.WebviewController(); 927 updataContent: string = '<body><div><image src=resource://rawfile/xxx.png alt="image -- end" width="500" height="250"></image></div></body>' 928 929 build() { 930 Column() { 931 Button('loadData') 932 .onClick(() => { 933 try { 934 this.controller.loadData(this.updataContent, "text/html", "UTF-8", " ", " "); 935 } catch (error) { 936 let e: business_error.BusinessError = error as business_error.BusinessError; 937 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 938 } 939 }) 940 Web({ src: 'www.example.com', controller: this.controller }) 941 } 942 } 943} 944``` 945 946### accessForward 947 948accessForward(): boolean 949 950Checks whether going to the next page can be performed on the current page. 951 952**System capability**: SystemCapability.Web.Webview.Core 953 954**Return value** 955 956| Type | Description | 957| ------- | --------------------------------- | 958| boolean | Returns **true** if going to the next page can be performed on the current page; returns **false** otherwise.| 959 960**Error codes** 961 962For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 963 964| ID| Error Message | 965| -------- | ------------------------------------------------------------ | 966| 17100001 | Init error. The WebviewController must be associated with a Web component. | 967 968**Example** 969 970```ts 971// xxx.ets 972import web_webview from '@ohos.web.webview'; 973import business_error from '@ohos.base'; 974 975@Entry 976@Component 977struct WebComponent { 978 controller: web_webview.WebviewController = new web_webview.WebviewController(); 979 980 build() { 981 Column() { 982 Button('accessForward') 983 .onClick(() => { 984 try { 985 let result = this.controller.accessForward(); 986 console.log('result:' + result); 987 } catch (error) { 988 let e: business_error.BusinessError = error as business_error.BusinessError; 989 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 990 } 991 }) 992 Web({ src: 'www.example.com', controller: this.controller }) 993 } 994 } 995} 996``` 997 998### forward 999 1000forward(): void 1001 1002Moves to the next page based on the history stack. This API is generally used together with **accessForward**. 1003 1004**System capability**: SystemCapability.Web.Webview.Core 1005 1006**Error codes** 1007 1008For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1009 1010| ID| Error Message | 1011| -------- | ------------------------------------------------------------ | 1012| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1013 1014**Example** 1015 1016```ts 1017// xxx.ets 1018import web_webview from '@ohos.web.webview'; 1019import business_error from '@ohos.base'; 1020 1021@Entry 1022@Component 1023struct WebComponent { 1024 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1025 1026 build() { 1027 Column() { 1028 Button('forward') 1029 .onClick(() => { 1030 try { 1031 this.controller.forward(); 1032 } catch (error) { 1033 let e: business_error.BusinessError = error as business_error.BusinessError; 1034 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1035 } 1036 }) 1037 Web({ src: 'www.example.com', controller: this.controller }) 1038 } 1039 } 1040} 1041``` 1042 1043### accessBackward 1044 1045accessBackward(): boolean 1046 1047Checks whether moving to the previous page can be performed on the current page. 1048 1049**System capability**: SystemCapability.Web.Webview.Core 1050 1051**Return value** 1052 1053| Type | Description | 1054| ------- | -------------------------------- | 1055| boolean | Returns **true** if moving to the previous page can be performed on the current page; returns **false** otherwise.| 1056 1057**Error codes** 1058 1059For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1060 1061| ID| Error Message | 1062| -------- | ------------------------------------------------------------ | 1063| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1064 1065**Example** 1066 1067```ts 1068// xxx.ets 1069import web_webview from '@ohos.web.webview'; 1070import business_error from '@ohos.base'; 1071 1072@Entry 1073@Component 1074struct WebComponent { 1075 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1076 1077 build() { 1078 Column() { 1079 Button('accessBackward') 1080 .onClick(() => { 1081 try { 1082 let result = this.controller.accessBackward(); 1083 console.log('result:' + result); 1084 } catch (error) { 1085 let e: business_error.BusinessError = error as business_error.BusinessError; 1086 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1087 } 1088 }) 1089 Web({ src: 'www.example.com', controller: this.controller }) 1090 } 1091 } 1092} 1093``` 1094 1095### backward 1096 1097backward(): void 1098 1099Moves to the previous page based on the history stack. This API is generally used together with **accessBackward**. 1100 1101**System capability**: SystemCapability.Web.Webview.Core 1102 1103**Error codes** 1104 1105For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1106 1107| ID| Error Message | 1108| -------- | ------------------------------------------------------------ | 1109| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1110 1111**Example** 1112 1113```ts 1114// xxx.ets 1115import web_webview from '@ohos.web.webview'; 1116import business_error from '@ohos.base'; 1117 1118@Entry 1119@Component 1120struct WebComponent { 1121 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1122 1123 build() { 1124 Column() { 1125 Button('backward') 1126 .onClick(() => { 1127 try { 1128 this.controller.backward(); 1129 } catch (error) { 1130 let e: business_error.BusinessError = error as business_error.BusinessError; 1131 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1132 } 1133 }) 1134 Web({ src: 'www.example.com', controller: this.controller }) 1135 } 1136 } 1137} 1138``` 1139 1140### onActive 1141 1142onActive(): void 1143 1144Invoked to instruct the **\<Web>** component to enter the active foreground state. 1145 1146**System capability**: SystemCapability.Web.Webview.Core 1147 1148**Error codes** 1149 1150For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1151 1152| ID| Error Message | 1153| -------- | ------------------------------------------------------------ | 1154| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1155 1156**Example** 1157 1158```ts 1159// xxx.ets 1160import web_webview from '@ohos.web.webview'; 1161import business_error from '@ohos.base'; 1162 1163@Entry 1164@Component 1165struct WebComponent { 1166 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1167 1168 build() { 1169 Column() { 1170 Button('onActive') 1171 .onClick(() => { 1172 try { 1173 this.controller.onActive(); 1174 } catch (error) { 1175 let e: business_error.BusinessError = error as business_error.BusinessError; 1176 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1177 } 1178 }) 1179 Web({ src: 'www.example.com', controller: this.controller }) 1180 } 1181 } 1182} 1183``` 1184 1185### onInactive 1186 1187onInactive(): void 1188 1189Invoked to instruct the **\<Web>** component to enter the inactive state. 1190 1191**System capability**: SystemCapability.Web.Webview.Core 1192 1193**Error codes** 1194 1195For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1196 1197| ID| Error Message | 1198| -------- | ------------------------------------------------------------ | 1199| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1200 1201**Example** 1202 1203```ts 1204// xxx.ets 1205import web_webview from '@ohos.web.webview'; 1206import business_error from '@ohos.base'; 1207 1208@Entry 1209@Component 1210struct WebComponent { 1211 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1212 1213 build() { 1214 Column() { 1215 Button('onInactive') 1216 .onClick(() => { 1217 try { 1218 this.controller.onInactive(); 1219 } catch (error) { 1220 let e: business_error.BusinessError = error as business_error.BusinessError; 1221 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1222 } 1223 }) 1224 Web({ src: 'www.example.com', controller: this.controller }) 1225 } 1226 } 1227} 1228``` 1229 1230### refresh 1231refresh(): void 1232 1233Invoked to instruct the **\<Web>** component to refresh the web page. 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 component. | 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('refresh') 1260 .onClick(() => { 1261 try { 1262 this.controller.refresh(); 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### accessStep 1275 1276accessStep(step: number): boolean 1277 1278Checks whether a specific number of steps forward or backward can be performed on the current page. 1279 1280**System capability**: SystemCapability.Web.Webview.Core 1281 1282**Parameters** 1283 1284| Name| Type| Mandatory| Description | 1285| ------ | -------- | ---- | ------------------------------------------ | 1286| step | number | Yes | Number of the steps to take. A positive number means to move forward, and a negative number means to move backward.| 1287 1288**Return value** 1289 1290| Type | Description | 1291| ------- | ------------------ | 1292| boolean | Whether moving forward or backward is performed on the current page.| 1293 1294**Error codes** 1295 1296For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1297 1298| ID| Error Message | 1299| -------- | ------------------------------------------------------------ | 1300| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1301 1302**Example** 1303 1304```ts 1305// xxx.ets 1306import web_webview from '@ohos.web.webview'; 1307import business_error from '@ohos.base'; 1308 1309@Entry 1310@Component 1311struct WebComponent { 1312 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1313 @State steps: number = 2; 1314 1315 build() { 1316 Column() { 1317 Button('accessStep') 1318 .onClick(() => { 1319 try { 1320 let result = this.controller.accessStep(this.steps); 1321 console.log('result:' + result); 1322 } catch (error) { 1323 let e: business_error.BusinessError = error as business_error.BusinessError; 1324 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1325 } 1326 }) 1327 Web({ src: 'www.example.com', controller: this.controller }) 1328 } 1329 } 1330} 1331``` 1332 1333### clearHistory 1334 1335clearHistory(): void 1336 1337Clears the browsing history. 1338 1339**System capability**: SystemCapability.Web.Webview.Core 1340 1341**Error codes** 1342 1343For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1344 1345| ID| Error Message | 1346| -------- | ------------------------------------------------------------ | 1347| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1348 1349**Example** 1350 1351```ts 1352// xxx.ets 1353import web_webview from '@ohos.web.webview'; 1354import business_error from '@ohos.base'; 1355 1356@Entry 1357@Component 1358struct WebComponent { 1359 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1360 1361 build() { 1362 Column() { 1363 Button('clearHistory') 1364 .onClick(() => { 1365 try { 1366 this.controller.clearHistory(); 1367 } catch (error) { 1368 let e: business_error.BusinessError = error as business_error.BusinessError; 1369 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1370 } 1371 }) 1372 Web({ src: 'www.example.com', controller: this.controller }) 1373 } 1374 } 1375} 1376``` 1377 1378### getHitTest 1379 1380getHitTest(): WebHitTestType 1381 1382Obtains the element type of the area being clicked. 1383 1384**System capability**: SystemCapability.Web.Webview.Core 1385 1386**Return value** 1387 1388| Type | Description | 1389| ------------------------------------------------------------ | ---------------------- | 1390| [WebHitTestType](#webhittesttype)| Element type of the area being clicked.| 1391 1392**Error codes** 1393 1394For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1395 1396| ID| Error Message | 1397| -------- | ------------------------------------------------------------ | 1398| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1399 1400**Example** 1401 1402```ts 1403// xxx.ets 1404import web_webview from '@ohos.web.webview'; 1405import business_error from '@ohos.base'; 1406 1407@Entry 1408@Component 1409struct WebComponent { 1410 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1411 1412 build() { 1413 Column() { 1414 Button('getHitTest') 1415 .onClick(() => { 1416 try { 1417 let hitTestType = this.controller.getHitTest(); 1418 console.log("hitTestType: " + hitTestType); 1419 } catch (error) { 1420 let e: business_error.BusinessError = error as business_error.BusinessError; 1421 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1422 } 1423 }) 1424 Web({ src: 'www.example.com', controller: this.controller }) 1425 } 1426 } 1427} 1428``` 1429 1430### registerJavaScriptProxy 1431 1432registerJavaScriptProxy(object: object, name: string, methodList: Array\<string>): void 1433 1434Registers 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. 1435 1436**System capability**: SystemCapability.Web.Webview.Core 1437 1438**Parameters** 1439 1440| Name | Type | Mandatory| Description | 1441| ---------- | -------------- | ---- | ------------------------------------------------------------ | 1442| object | object | Yes | Application-side JavaScript object to be registered. Methods can be declared, but not attributes.<br> The parameters and return values of the methods can be of the following types:<br>- String, number, or Boolean type<br>- Dictionary or Array type, with a maximum of 10 nested layers, and each layer containing 10,000 data records<br>- Object type, to which you need to add the **methodNameListForJsProxy:[fun1, fun2]** attribute, where *fun1* and *fun2* are methods that can be called<br>The parameters can be a function or promise, but its callback cannot have any return value.<br>The return value can be a promise, but its callback cannot have any return value. For more examples, see [Invoking Application Functions on the Frontend Page](../../web/web-in-page-app-function-invoking.md).| 1443| 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.| 1444| methodList | Array\<string> | Yes | Methods of the JavaScript object to be registered at the application side. | 1445 1446**Error codes** 1447 1448For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1449 1450| ID| Error Message | 1451| -------- | ------------------------------------------------------------ | 1452| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1453 1454**Example** 1455 1456```ts 1457// xxx.ets 1458import web_webview from '@ohos.web.webview'; 1459import business_error from '@ohos.base'; 1460 1461class TestObj { 1462 constructor() { 1463 } 1464 1465 test(testStr:string): string { 1466 console.log('Web Component str' + testStr); 1467 return testStr; 1468 } 1469 1470 toString(): void { 1471 console.log('Web Component toString'); 1472 } 1473 1474 testNumber(testNum:number): number { 1475 console.log('Web Component number' + testNum); 1476 return testNum; 1477 } 1478 1479 testBool(testBol:boolean): boolean { 1480 console.log('Web Component boolean' + testBol); 1481 return testBol; 1482 } 1483} 1484 1485class WebObj { 1486 constructor() { 1487 } 1488 1489 webTest(): string { 1490 console.log('Web test'); 1491 return "Web test"; 1492 } 1493 1494 webString(): void { 1495 console.log('Web test toString'); 1496 } 1497} 1498 1499@Entry 1500@Component 1501struct Index { 1502 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1503 @State testObjtest: TestObj = new TestObj(); 1504 @State webTestObj: WebObj = new WebObj(); 1505 build() { 1506 Column() { 1507 Button('refresh') 1508 .onClick(() => { 1509 try { 1510 this.controller.refresh(); 1511 } catch (error) { 1512 let e: business_error.BusinessError = error as business_error.BusinessError; 1513 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1514 } 1515 }) 1516 Button('Register JavaScript To Window') 1517 .onClick(() => { 1518 try { 1519 this.controller.registerJavaScriptProxy(this.testObjtest, "objName", ["test", "toString", "testNumber", "testBool"]); 1520 this.controller.registerJavaScriptProxy(this.webTestObj, "objTestName", ["webTest", "webString"]); 1521 } catch (error) { 1522 let e: business_error.BusinessError = error as business_error.BusinessError; 1523 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1524 } 1525 }) 1526 Web({ src: $rawfile('index.html'), controller: this.controller }) 1527 .javaScriptAccess(true) 1528 } 1529 } 1530} 1531``` 1532 1533HTML file to be loaded: 1534```html 1535<!-- index.html --> 1536<!DOCTYPE html> 1537<html> 1538 <meta charset="utf-8"> 1539 <body> 1540 <button type="button" onclick="htmlTest()">Click Me!</button> 1541 <p id="demo"></p> 1542 <p id="webDemo"></p> 1543 </body> 1544 <script type="text/javascript"> 1545 function htmlTest() { 1546 // This function call expects to return "ArkUI Web Component" 1547 let str=objName.test("webtest data"); 1548 objName.testNumber(1); 1549 objName.testBool(true); 1550 document.getElementById("demo").innerHTML=str; 1551 console.log('objName.test result:'+ str) 1552 1553 // This function call expects to return "Web test" 1554 let webStr = objTestName.webTest(); 1555 document.getElementById("webDemo").innerHTML=webStr; 1556 console.log('objTestName.webTest result:'+ webStr) 1557 } 1558</script> 1559</html> 1560``` 1561For more examples, see [Invoking Application Functions on the Frontend Page](../../web/web-in-page-app-function-invoking.md). 1562 1563### runJavaScript 1564 1565runJavaScript(script: string, callback : AsyncCallback\<string>): void 1566 1567Executes 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**. 1568 1569**System capability**: SystemCapability.Web.Webview.Core 1570 1571**Parameters** 1572 1573| Name | Type | Mandatory| Description | 1574| -------- | -------------------- | ---- | ---------------------------- | 1575| script | string | Yes | JavaScript script. | 1576| 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.| 1577 1578**Error codes** 1579 1580For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1581 1582| ID| Error Message | 1583| -------- | ------------------------------------------------------------ | 1584| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1585 1586**Example** 1587 1588```ts 1589import web_webview from '@ohos.web.webview'; 1590import business_error from '@ohos.base'; 1591 1592@Entry 1593@Component 1594struct WebComponent { 1595 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1596 @State webResult: string = '' 1597 1598 build() { 1599 Column() { 1600 Text(this.webResult).fontSize(20) 1601 Web({ src: $rawfile('index.html'), controller: this.controller }) 1602 .javaScriptAccess(true) 1603 .onPageEnd(e => { 1604 try { 1605 this.controller.runJavaScript( 1606 'test()', 1607 (error, result) => { 1608 if (error) { 1609 console.info(`run JavaScript error: ` + JSON.stringify(error)) 1610 return; 1611 } 1612 if (result) { 1613 this.webResult = result 1614 console.info(`The test() return value is: ${result}`) 1615 } 1616 }); 1617 if (e) { 1618 console.info('url: ', e.url); 1619 } 1620 } catch (error) { 1621 let e: business_error.BusinessError = error as business_error.BusinessError; 1622 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1623 } 1624 }) 1625 } 1626 } 1627} 1628``` 1629 1630HTML file to be loaded: 1631```html 1632<!-- index.html --> 1633<!DOCTYPE html> 1634<html> 1635 <meta charset="utf-8"> 1636 <body> 1637 Hello world! 1638 </body> 1639 <script type="text/javascript"> 1640 function test() { 1641 console.log('Ark WebComponent') 1642 return "This value is from index.html" 1643 } 1644 </script> 1645</html> 1646``` 1647 1648### runJavaScript 1649 1650runJavaScript(script: string): Promise\<string> 1651 1652Executes 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**. 1653 1654**System capability**: SystemCapability.Web.Webview.Core 1655 1656**Parameters** 1657 1658| Name| Type| Mandatory| Description | 1659| ------ | -------- | ---- | ---------------- | 1660| script | string | Yes | JavaScript script.| 1661 1662**Return value** 1663 1664| Type | Description | 1665| --------------- | --------------------------------------------------- | 1666| Promise\<string> | Promise used to return the result if the operation is successful and null otherwise.| 1667 1668**Error codes** 1669 1670For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1671 1672| ID| Error Message | 1673| -------- | ------------------------------------------------------------ | 1674| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1675 1676**Example** 1677 1678```ts 1679// xxx.ets 1680import web_webview from '@ohos.web.webview'; 1681import business_error from '@ohos.base'; 1682 1683@Entry 1684@Component 1685struct WebComponent { 1686 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1687 1688 build() { 1689 Column() { 1690 Web({ src: $rawfile('index.html'), controller: this.controller }) 1691 .javaScriptAccess(true) 1692 .onPageEnd(e => { 1693 try { 1694 this.controller.runJavaScript('test()') 1695 .then((result) => { 1696 console.log('result: ' + result); 1697 }) 1698 .catch((error: business_error.BusinessError) => { 1699 console.error("error: " + error); 1700 }) 1701 if (e) { 1702 console.info('url: ', e.url); 1703 } 1704 } catch (error) { 1705 let e: business_error.BusinessError = error as business_error.BusinessError; 1706 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1707 } 1708 }) 1709 } 1710 } 1711} 1712``` 1713 1714HTML file to be loaded: 1715```html 1716<!-- index.html --> 1717<!DOCTYPE html> 1718<html> 1719 <meta charset="utf-8"> 1720 <body> 1721 Hello world! 1722 </body> 1723 <script type="text/javascript"> 1724 function test() { 1725 console.log('Ark WebComponent') 1726 return "This value is from index.html" 1727 } 1728 </script> 1729</html> 1730``` 1731 1732### runJavaScriptExt<sup>10+</sup> 1733 1734runJavaScriptExt(script: string, callback : AsyncCallback\<JsMessageExt>): void 1735 1736Executes 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**. 1737 1738**System capability**: SystemCapability.Web.Webview.Core 1739 1740**Parameters** 1741 1742| Name | Type | Mandatory| Description | 1743| -------- | -------------------- | ---- | ---------------------------- | 1744| script | string | Yes | JavaScript script. | 1745| callback | AsyncCallback\<[JsMessageExt](#jsmessageext10)\> | Yes | Callback used to return the result.| 1746 1747**Error codes** 1748 1749For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1750 1751| ID| Error Message | 1752| -------- | ------------------------------------------------------------ | 1753| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1754 1755**Example** 1756 1757```ts 1758import web_webview from '@ohos.web.webview'; 1759import business_error from '@ohos.base'; 1760 1761@Entry 1762@Component 1763struct WebComponent { 1764 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1765 @State msg1: string = '' 1766 @State msg2: string = '' 1767 1768 build() { 1769 Column() { 1770 Text(this.msg1).fontSize(20) 1771 Text(this.msg2).fontSize(20) 1772 Web({ src: $rawfile('index.html'), controller: this.controller }) 1773 .javaScriptAccess(true) 1774 .onPageEnd(e => { 1775 try { 1776 this.controller.runJavaScriptExt( 1777 'test()', 1778 (error, result) => { 1779 if (error) { 1780 console.info(`run JavaScript error: ` + JSON.stringify(error)) 1781 return; 1782 } 1783 if (result) { 1784 try { 1785 let type = result.getType(); 1786 switch (type) { 1787 case web_webview.JsMessageType.STRING: { 1788 this.msg1 = "result type:" + typeof (result.getString()); 1789 this.msg2 = "result getString:" + ((result.getString())); 1790 break; 1791 } 1792 case web_webview.JsMessageType.NUMBER: { 1793 this.msg1 = "result type:" + typeof (result.getNumber()); 1794 this.msg2 = "result getNumber:" + ((result.getNumber())); 1795 break; 1796 } 1797 case web_webview.JsMessageType.BOOLEAN: { 1798 this.msg1 = "result type:" + typeof (result.getBoolean()); 1799 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 1800 break; 1801 } 1802 case web_webview.JsMessageType.ARRAY_BUFFER: { 1803 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 1804 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 1805 break; 1806 } 1807 case web_webview.JsMessageType.ARRAY: { 1808 this.msg1 = "result type:" + typeof (result.getArray()); 1809 this.msg2 = "result getArray:" + result.getArray(); 1810 break; 1811 } 1812 default: { 1813 this.msg1 = "default break, type:" + type; 1814 break; 1815 } 1816 } 1817 } 1818 catch (resError) { 1819 let e: business_error.BusinessError = resError as business_error.BusinessError; 1820 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1821 } 1822 } 1823 }); 1824 if (e) { 1825 console.info('url: ', e.url); 1826 } 1827 } catch (error) { 1828 let e: business_error.BusinessError = error as business_error.BusinessError; 1829 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1830 } 1831 }) 1832 } 1833 } 1834} 1835``` 1836 1837HTML file to be loaded: 1838```html 1839<!-- index.html --> 1840<!DOCTYPE html> 1841<html lang="en-gb"> 1842<body> 1843<h1>run JavaScript Ext demo</h1> 1844</body> 1845<script type="text/javascript"> 1846function test() { 1847 return "hello, world"; 1848} 1849</script> 1850</html> 1851``` 1852 1853### runJavaScriptExt<sup>10+</sup> 1854 1855runJavaScriptExt(script: string): Promise\<JsMessageExt> 1856 1857Executes 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**. 1858 1859**System capability**: SystemCapability.Web.Webview.Core 1860 1861**Parameters** 1862 1863| Name| Type| Mandatory| Description | 1864| ------ | -------- | ---- | ---------------- | 1865| script | string | Yes | JavaScript script.| 1866 1867**Return value** 1868 1869| Type | Description | 1870| --------------- | --------------------------------------------------- | 1871| Promise\<[JsMessageExt](#jsmessageext10)> | Promise used to return the script execution result.| 1872 1873**Error codes** 1874 1875For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1876 1877| ID| Error Message | 1878| -------- | ------------------------------------------------------------ | 1879| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1880 1881**Example** 1882 1883```ts 1884// xxx.ets 1885import web_webview from '@ohos.web.webview'; 1886import business_error from '@ohos.base'; 1887 1888@Entry 1889@Component 1890struct WebComponent { 1891 controller: web_webview.WebviewController = new web_webview.WebviewController(); 1892 @State webResult: string = ''; 1893 @State msg1: string = '' 1894 @State msg2: string = '' 1895 1896 build() { 1897 Column() { 1898 Text(this.webResult).fontSize(20) 1899 Text(this.msg1).fontSize(20) 1900 Text(this.msg2).fontSize(20) 1901 Web({ src: $rawfile('index.html'), controller: this.controller }) 1902 .javaScriptAccess(true) 1903 .onPageEnd(() => { 1904 this.controller.runJavaScriptExt('test()') 1905 .then((result) => { 1906 try { 1907 let type = result.getType(); 1908 switch (type) { 1909 case web_webview.JsMessageType.STRING: { 1910 this.msg1 = "result type:" + typeof (result.getString()); 1911 this.msg2 = "result getString:" + ((result.getString())); 1912 break; 1913 } 1914 case web_webview.JsMessageType.NUMBER: { 1915 this.msg1 = "result type:" + typeof (result.getNumber()); 1916 this.msg2 = "result getNumber:" + ((result.getNumber())); 1917 break; 1918 } 1919 case web_webview.JsMessageType.BOOLEAN: { 1920 this.msg1 = "result type:" + typeof (result.getBoolean()); 1921 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 1922 break; 1923 } 1924 case web_webview.JsMessageType.ARRAY_BUFFER: { 1925 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 1926 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 1927 break; 1928 } 1929 case web_webview.JsMessageType.ARRAY: { 1930 this.msg1 = "result type:" + typeof (result.getArray()); 1931 this.msg2 = "result getArray:" + result.getArray(); 1932 break; 1933 } 1934 default: { 1935 this.msg1 = "default break, type:" + type; 1936 break; 1937 } 1938 } 1939 } 1940 catch (resError) { 1941 let e: business_error.BusinessError = resError as business_error.BusinessError; 1942 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 1943 } 1944 }) 1945 .catch((error: business_error.BusinessError) => { 1946 console.error("error: " + error); 1947 }) 1948 }) 1949 } 1950 } 1951} 1952``` 1953 1954HTML file to be loaded: 1955```html 1956<!-- index.html --> 1957<!DOCTYPE html> 1958<html lang="en-gb"> 1959<body> 1960<h1>run JavaScript Ext demo</h1> 1961</body> 1962<script type="text/javascript"> 1963function test() { 1964 return "hello, world"; 1965} 1966</script> 1967</html> 1968``` 1969 1970### deleteJavaScriptRegister 1971 1972deleteJavaScriptRegister(name: string): void 1973 1974Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. After the deletion, the [refresh](#refresh) API must be called. 1975 1976**System capability**: SystemCapability.Web.Webview.Core 1977 1978**Parameters** 1979 1980| Name| Type| Mandatory| Description | 1981| ------ | -------- | ---- | ---- | 1982| 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.| 1983 1984**Error codes** 1985 1986For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 1987 1988| ID| Error Message | 1989| -------- | ------------------------------------------------------------ | 1990| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1991| 17100008 | Cannot delete JavaScriptProxy. | 1992 1993**Example** 1994 1995```ts 1996// xxx.ets 1997import web_webview from '@ohos.web.webview'; 1998import business_error from '@ohos.base'; 1999 2000class TestObj { 2001 constructor() { 2002 } 2003 2004 test(): string { 2005 return "ArkUI Web Component"; 2006 } 2007 2008 toString(): void { 2009 console.log('Web Component toString'); 2010 } 2011} 2012 2013@Entry 2014@Component 2015struct WebComponent { 2016 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2017 @State testObjtest: TestObj = new TestObj(); 2018 @State name: string = 'objName'; 2019 build() { 2020 Column() { 2021 Button('refresh') 2022 .onClick(() => { 2023 try { 2024 this.controller.refresh(); 2025 } catch (error) { 2026 let e: business_error.BusinessError = error as business_error.BusinessError; 2027 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2028 } 2029 }) 2030 Button('Register JavaScript To Window') 2031 .onClick(() => { 2032 try { 2033 this.controller.registerJavaScriptProxy(this.testObjtest, this.name, ["test", "toString"]); 2034 } catch (error) { 2035 let e: business_error.BusinessError = error as business_error.BusinessError; 2036 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2037 } 2038 }) 2039 Button('deleteJavaScriptRegister') 2040 .onClick(() => { 2041 try { 2042 this.controller.deleteJavaScriptRegister(this.name); 2043 } catch (error) { 2044 let e: business_error.BusinessError = error as business_error.BusinessError; 2045 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2046 } 2047 }) 2048 Web({ src: $rawfile('index.html'), controller: this.controller }) 2049 .javaScriptAccess(true) 2050 } 2051 } 2052} 2053``` 2054 2055HTML file to be loaded: 2056```html 2057<!-- index.html --> 2058<!DOCTYPE html> 2059<html> 2060 <meta charset="utf-8"> 2061 <body> 2062 <button type="button" onclick="htmlTest()">Click Me!</button> 2063 <p id="demo"></p> 2064 </body> 2065 <script type="text/javascript"> 2066 function htmlTest() { 2067 let str=objName.test(); 2068 document.getElementById("demo").innerHTML=str; 2069 console.log('objName.test result:'+ str) 2070 } 2071</script> 2072</html> 2073``` 2074 2075### zoom 2076 2077zoom(factor: number): void 2078 2079Zooms in or out of this web page. This API is effective only when [zoomAccess](../arkui-ts/ts-basic-components-web.md#zoomaccess) is **true**. 2080 2081**System capability**: SystemCapability.Web.Webview.Core 2082 2083**Parameters** 2084 2085| Name| Type| Mandatory| Description| 2086| ------ | -------- | ---- | ------------------------------------------------------------ | 2087| 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.| 2088 2089**Error codes** 2090 2091For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2092 2093| ID| Error Message | 2094| -------- | ------------------------------------------------------------ | 2095| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2096| 17100004 | Function not enable. | 2097 2098**Example** 2099 2100```ts 2101// xxx.ets 2102import web_webview from '@ohos.web.webview'; 2103import business_error from '@ohos.base'; 2104 2105@Entry 2106@Component 2107struct WebComponent { 2108 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2109 @State factor: number = 1; 2110 2111 build() { 2112 Column() { 2113 Button('zoom') 2114 .onClick(() => { 2115 try { 2116 this.controller.zoom(this.factor); 2117 } catch (error) { 2118 let e: business_error.BusinessError = error as business_error.BusinessError; 2119 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2120 } 2121 }) 2122 Web({ src: 'www.example.com', controller: this.controller }) 2123 .zoomAccess(true) 2124 } 2125 } 2126} 2127``` 2128 2129### searchAllAsync 2130 2131searchAllAsync(searchString: string): void 2132 2133Searches 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). 2134 2135**System capability**: SystemCapability.Web.Webview.Core 2136 2137**Parameters** 2138 2139| Name | Type| Mandatory| Description | 2140| ------------ | -------- | ---- | -------------- | 2141| searchString | string | Yes | Search keyword.| 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 component. | 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 @State searchString: string = "Hello World"; 2163 2164 build() { 2165 Column() { 2166 Button('searchString') 2167 .onClick(() => { 2168 try { 2169 this.controller.searchAllAsync(this.searchString); 2170 } catch (error) { 2171 let e: business_error.BusinessError = error as business_error.BusinessError; 2172 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2173 } 2174 }) 2175 Web({ src: $rawfile('index.html'), controller: this.controller }) 2176 .onSearchResultReceive(ret => { 2177 if (ret) { 2178 console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal + 2179 "[total]" + ret.numberOfMatches + "[isDone]" + ret.isDoneCounting); 2180 } 2181 }) 2182 } 2183 } 2184} 2185``` 2186 2187HTML file to be loaded: 2188```html 2189<!-- index.html --> 2190<!DOCTYPE html> 2191<html> 2192 <body> 2193 <p>Hello World Highlight Hello World</p> 2194 </body> 2195</html> 2196``` 2197 2198### clearMatches 2199 2200clearMatches(): void 2201 2202Clears the matches found through [searchAllAsync](#searchallasync). 2203 2204**System capability**: SystemCapability.Web.Webview.Core 2205 2206**Error codes** 2207 2208For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2209 2210| ID| Error Message | 2211| -------- | ------------------------------------------------------------ | 2212| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2213 2214**Example** 2215 2216```ts 2217// xxx.ets 2218import web_webview from '@ohos.web.webview'; 2219import business_error from '@ohos.base'; 2220 2221@Entry 2222@Component 2223struct WebComponent { 2224 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2225 2226 build() { 2227 Column() { 2228 Button('clearMatches') 2229 .onClick(() => { 2230 try { 2231 this.controller.clearMatches(); 2232 } catch (error) { 2233 let e: business_error.BusinessError = error as business_error.BusinessError; 2234 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2235 } 2236 }) 2237 Web({ src: $rawfile('index.html'), controller: this.controller }) 2238 } 2239 } 2240} 2241``` 2242 2243For details about the HTML file loaded, see the HMTL file loaded using [searchAllAsync](#searchallasync). 2244 2245### searchNext 2246 2247searchNext(forward: boolean): void 2248 2249Searches for and highlights the next match. 2250 2251**System capability**: SystemCapability.Web.Webview.Core 2252 2253**Parameters** 2254 2255| Name | Type| Mandatory| Description | 2256| ------- | -------- | ---- | ---------------------- | 2257| forward | boolean | Yes | Whether to search forward.| 2258 2259**Error codes** 2260 2261For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2262 2263| ID| Error Message | 2264| -------- | ------------------------------------------------------------ | 2265| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2266 2267**Example** 2268 2269```ts 2270// xxx.ets 2271import web_webview from '@ohos.web.webview'; 2272import business_error from '@ohos.base'; 2273 2274@Entry 2275@Component 2276struct WebComponent { 2277 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2278 2279 build() { 2280 Column() { 2281 Button('searchNext') 2282 .onClick(() => { 2283 try { 2284 this.controller.searchNext(true); 2285 } catch (error) { 2286 let e: business_error.BusinessError = error as business_error.BusinessError; 2287 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2288 } 2289 }) 2290 Web({ src: $rawfile('index.html'), controller: this.controller }) 2291 } 2292 } 2293} 2294``` 2295 2296For details about the HTML file loaded, see the HMTL file loaded using [searchAllAsync](#searchallasync). 2297 2298### clearSslCache 2299 2300clearSslCache(): void 2301 2302Clears the user operation corresponding to the SSL certificate error event recorded by the **\<Web>** component. 2303 2304**System capability**: SystemCapability.Web.Webview.Core 2305 2306**Error codes** 2307 2308For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2309 2310| ID| Error Message | 2311| -------- | ------------------------------------------------------------ | 2312| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2313 2314**Example** 2315 2316```ts 2317// xxx.ets 2318import web_webview from '@ohos.web.webview'; 2319import business_error from '@ohos.base'; 2320 2321@Entry 2322@Component 2323struct WebComponent { 2324 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2325 2326 build() { 2327 Column() { 2328 Button('clearSslCache') 2329 .onClick(() => { 2330 try { 2331 this.controller.clearSslCache(); 2332 } catch (error) { 2333 let e: business_error.BusinessError = error as business_error.BusinessError; 2334 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2335 } 2336 }) 2337 Web({ src: 'www.example.com', controller: this.controller }) 2338 } 2339 } 2340} 2341``` 2342 2343### clearClientAuthenticationCache 2344 2345clearClientAuthenticationCache(): void 2346 2347Clears the user operation corresponding to the client certificate request event recorded by the **\<Web>** component. 2348 2349**System capability**: SystemCapability.Web.Webview.Core 2350 2351**Error codes** 2352 2353For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2354 2355| ID| Error Message | 2356| -------- | ------------------------------------------------------------ | 2357| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2358 2359**Example** 2360 2361```ts 2362// xxx.ets 2363import web_webview from '@ohos.web.webview'; 2364import business_error from '@ohos.base'; 2365 2366@Entry 2367@Component 2368struct WebComponent { 2369 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2370 2371 build() { 2372 Column() { 2373 Button('clearClientAuthenticationCache') 2374 .onClick(() => { 2375 try { 2376 this.controller.clearClientAuthenticationCache(); 2377 } catch (error) { 2378 let e: business_error.BusinessError = error as business_error.BusinessError; 2379 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2380 } 2381 }) 2382 Web({ src: 'www.example.com', controller: this.controller }) 2383 } 2384 } 2385} 2386``` 2387 2388### createWebMessagePorts 2389 2390createWebMessagePorts(isExtentionType?: boolean): Array\<WebMessagePort> 2391 2392Creates web message ports. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 2393 2394**System capability**: SystemCapability.Web.Webview.Core 2395 2396**Parameters** 2397 2398| Name| Type | Mandatory| Description | 2399| ------ | ---------------------- | ---- | :------------------------------| 2400| 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.| 2401 2402**Return value** 2403 2404| Type | Description | 2405| ---------------------- | ----------------- | 2406| Array\<[WebMessagePort](#webmessageport)> | List of web message ports.| 2407 2408**Error codes** 2409 2410For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2411 2412| ID| Error Message | 2413| -------- | ------------------------------------------------------------ | 2414| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2415 2416**Example** 2417 2418 ```ts 2419// xxx.ets 2420import web_webview from '@ohos.web.webview'; 2421import business_error from '@ohos.base'; 2422 2423@Entry 2424@Component 2425struct WebComponent { 2426 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2427 ports: web_webview.WebMessagePort[] = []; 2428 2429 build() { 2430 Column() { 2431 Button('createWebMessagePorts') 2432 .onClick(() => { 2433 try { 2434 this.ports = this.controller.createWebMessagePorts(); 2435 console.log("createWebMessagePorts size:" + this.ports.length) 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### postMessage 2448 2449postMessage(name: string, ports: Array\<WebMessagePort>, uri: string): void 2450 2451Sends a web message to an HTML window. 2452 2453**System capability**: SystemCapability.Web.Webview.Core 2454 2455**Parameters** 2456 2457| Name| Type | Mandatory| Description | 2458| ------ | ---------------------- | ---- | :------------------------------- | 2459| name | string | Yes | Name of the message to send. | 2460| ports | Array\<WebMessagePort> | Yes | Message ports for sending the message. | 2461| uri | string | Yes | URI for receiving the message. | 2462 2463**Error codes** 2464 2465For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2466 2467| ID| Error Message | 2468| -------- | ------------------------------------------------------------ | 2469| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2470 2471**Example** 2472 2473```ts 2474// xxx.ets 2475import web_webview from '@ohos.web.webview'; 2476import business_error from '@ohos.base'; 2477 2478@Entry 2479@Component 2480struct WebComponent { 2481 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2482 ports: web_webview.WebMessagePort[] = []; 2483 @State sendFromEts: string = 'Send this message from ets to HTML'; 2484 @State receivedFromHtml: string = 'Display received message send from HTML'; 2485 2486 build() { 2487 Column() { 2488 // Display the received HTML content. 2489 Text(this.receivedFromHtml) 2490 // Send the content in the text box to an HTML window. 2491 TextInput({ placeholder: 'Send this message from ets to HTML' }) 2492 .onChange((value: string) => { 2493 this.sendFromEts = value; 2494 }) 2495 2496 Button('postMessage') 2497 .onClick(() => { 2498 try { 2499 // 1. Create two message ports. 2500 this.ports = this.controller.createWebMessagePorts(); 2501 // 2. Register a callback on a message port (for example, port 1) on the application side. 2502 this.ports[1].onMessageEvent((result: web_webview.WebMessage) => { 2503 let msg = 'Got msg from HTML:'; 2504 if (typeof(result) == "string") { 2505 console.log("received string message from html5, string is:" + result); 2506 msg = msg + result; 2507 } else if (typeof(result) == "object") { 2508 if (result instanceof ArrayBuffer) { 2509 console.log("received arraybuffer from html5, length is:" + result.byteLength); 2510 msg = msg + "lenght is " + result.byteLength; 2511 } else { 2512 console.log("not support"); 2513 } 2514 } else { 2515 console.log("not support"); 2516 } 2517 this.receivedFromHtml = msg; 2518 }) 2519 // 3. Send another message port (for example, port 0) to the HTML side, which can then save the port for future use. 2520 this.controller.postMessage('__init_port__', [this.ports[0]], '*'); 2521 } catch (error) { 2522 let e: business_error.BusinessError = error as business_error.BusinessError; 2523 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2524 } 2525 }) 2526 2527 // 4. Use the port on the application side to send messages to the port that has been sent to the HTML side. 2528 Button('SendDataToHTML') 2529 .onClick(() => { 2530 try { 2531 if (this.ports && this.ports[1]) { 2532 this.ports[1].postMessageEvent(this.sendFromEts); 2533 } else { 2534 console.error(`ports is null, Please initialize first`); 2535 } 2536 } catch (error) { 2537 let e: business_error.BusinessError = error as business_error.BusinessError; 2538 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2539 } 2540 }) 2541 Web({ src: $rawfile('index.html'), controller: this.controller }) 2542 } 2543 } 2544} 2545``` 2546 2547HTML file to be loaded: 2548```html 2549<!--index.html--> 2550<!DOCTYPE html> 2551<html> 2552<head> 2553 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 2554 <title>WebView Message Port Demo</title> 2555</head> 2556 2557 <body> 2558 <h1>WebView Message Port Demo</h1> 2559 <div> 2560 <input type="button" value="SendToEts" onclick="PostMsgToEts(msgFromJS.value);"/><br/> 2561 <input id="msgFromJS" type="text" value="send this message from HTML to ets"/><br/> 2562 </div> 2563 <p class="output">display received message send from ets</p> 2564 </body> 2565 <script src="xxx.js"></script> 2566</html> 2567``` 2568 2569```js 2570//xxx.js 2571var h5Port; 2572var output = document.querySelector('.output'); 2573window.addEventListener('message', function (event) { 2574 if (event.data == '__init_port__') { 2575 if (event.ports[0] != null) { 2576 h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side. 2577 h5Port.onmessage = function (event) { 2578 // 2. Receive the message sent from the eTS side. 2579 var msg = 'Got message from ets:'; 2580 var result = event.data; 2581 if (typeof(result) == "string") { 2582 console.log("received string message from html5, string is:" + result); 2583 msg = msg + result; 2584 } else if (typeof(result) == "object") { 2585 if (result instanceof ArrayBuffer) { 2586 console.log("received arraybuffer from html5, length is:" + result.byteLength); 2587 msg = msg + "lenght is " + result.byteLength; 2588 } else { 2589 console.log("not support"); 2590 } 2591 } else { 2592 console.log("not support"); 2593 } 2594 output.innerHTML = msg; 2595 } 2596 } 2597 } 2598}) 2599 2600// 3. Use h5Port to send messages to the eTS side. 2601function PostMsgToEts(data) { 2602 if (h5Port) { 2603 h5Port.postMessage(data); 2604 } else { 2605 console.error("h5Port is null, Please initialize first"); 2606 } 2607} 2608``` 2609 2610### requestFocus 2611 2612requestFocus(): void 2613 2614Requests focus for this web page. 2615 2616**System capability**: SystemCapability.Web.Webview.Core 2617 2618**Error codes** 2619 2620For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2621 2622| ID| Error Message | 2623| -------- | ------------------------------------------------------------ | 2624| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2625 2626**Example** 2627 2628```ts 2629// xxx.ets 2630import web_webview from '@ohos.web.webview'; 2631import business_error from '@ohos.base'; 2632 2633@Entry 2634@Component 2635struct WebComponent { 2636 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2637 2638 build() { 2639 Column() { 2640 Button('requestFocus') 2641 .onClick(() => { 2642 try { 2643 this.controller.requestFocus(); 2644 } catch (error) { 2645 let e: business_error.BusinessError = error as business_error.BusinessError; 2646 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2647 } 2648 }); 2649 Web({ src: 'www.example.com', controller: this.controller }) 2650 } 2651 } 2652} 2653``` 2654 2655### zoomIn 2656 2657zoomIn(): void 2658 2659Zooms in on this web page by 20%. 2660 2661**System capability**: SystemCapability.Web.Webview.Core 2662 2663**Error codes** 2664 2665For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2666 2667| ID| Error Message | 2668| -------- | ------------------------------------------------------------ | 2669| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2670| 17100004 | Function not enable. | 2671 2672**Example** 2673 2674```ts 2675// xxx.ets 2676import web_webview from '@ohos.web.webview'; 2677import business_error from '@ohos.base'; 2678 2679@Entry 2680@Component 2681struct WebComponent { 2682 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2683 2684 build() { 2685 Column() { 2686 Button('zoomIn') 2687 .onClick(() => { 2688 try { 2689 this.controller.zoomIn(); 2690 } catch (error) { 2691 let e: business_error.BusinessError = error as business_error.BusinessError; 2692 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2693 } 2694 }) 2695 Web({ src: 'www.example.com', controller: this.controller }) 2696 } 2697 } 2698} 2699``` 2700 2701### zoomOut 2702 2703zoomOut(): void 2704 2705Zooms out of this web page by 20%. 2706 2707**System capability**: SystemCapability.Web.Webview.Core 2708 2709**Error codes** 2710 2711For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2712 2713| ID| Error Message | 2714| -------- | ------------------------------------------------------------ | 2715| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2716| 17100004 | Function not enable. | 2717 2718**Example** 2719 2720```ts 2721// xxx.ets 2722import web_webview from '@ohos.web.webview'; 2723import business_error from '@ohos.base'; 2724 2725@Entry 2726@Component 2727struct WebComponent { 2728 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2729 2730 build() { 2731 Column() { 2732 Button('zoomOut') 2733 .onClick(() => { 2734 try { 2735 this.controller.zoomOut(); 2736 } catch (error) { 2737 let e: business_error.BusinessError = error as business_error.BusinessError; 2738 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2739 } 2740 }) 2741 Web({ src: 'www.example.com', controller: this.controller }) 2742 } 2743 } 2744} 2745``` 2746 2747### getHitTestValue 2748 2749getHitTestValue(): HitTestValue 2750 2751Obtains the element information of the area being clicked. 2752 2753**System capability**: SystemCapability.Web.Webview.Core 2754 2755**Return value** 2756 2757| Type | Description | 2758| ------------ | -------------------- | 2759| [HitTestValue](#hittestvalue) | Element information of the area being clicked.| 2760 2761**Error codes** 2762 2763For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2764 2765| ID| Error Message | 2766| -------- | ------------------------------------------------------------ | 2767| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2768 2769**Example** 2770 2771```ts 2772// xxx.ets 2773import web_webview from '@ohos.web.webview'; 2774import business_error from '@ohos.base'; 2775 2776@Entry 2777@Component 2778struct WebComponent { 2779 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2780 2781 build() { 2782 Column() { 2783 Button('getHitTestValue') 2784 .onClick(() => { 2785 try { 2786 let hitValue = this.controller.getHitTestValue(); 2787 console.log("hitType: " + hitValue.type); 2788 console.log("extra: " + hitValue.extra); 2789 } catch (error) { 2790 let e: business_error.BusinessError = error as business_error.BusinessError; 2791 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2792 } 2793 }) 2794 Web({ src: 'www.example.com', controller: this.controller }) 2795 } 2796 } 2797} 2798``` 2799 2800### getWebId 2801 2802getWebId(): number 2803 2804Obtains the index value of this **\<Web>** component, which can be used for **\<Web>** component management. 2805 2806**System capability**: SystemCapability.Web.Webview.Core 2807 2808**Return value** 2809 2810| Type | Description | 2811| ------ | --------------------- | 2812| number | Index value of the current **\<Web>** component.| 2813 2814**Error codes** 2815 2816For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2817 2818| ID| Error Message | 2819| -------- | ------------------------------------------------------------ | 2820| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2821 2822**Example** 2823 2824```ts 2825// xxx.ets 2826import web_webview from '@ohos.web.webview'; 2827import business_error from '@ohos.base'; 2828 2829@Entry 2830@Component 2831struct WebComponent { 2832 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2833 2834 build() { 2835 Column() { 2836 Button('getWebId') 2837 .onClick(() => { 2838 try { 2839 let id = this.controller.getWebId(); 2840 console.log("id: " + id); 2841 } catch (error) { 2842 let e: business_error.BusinessError = error as business_error.BusinessError; 2843 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2844 } 2845 }) 2846 Web({ src: 'www.example.com', controller: this.controller }) 2847 } 2848 } 2849} 2850``` 2851 2852### getUserAgent 2853 2854getUserAgent(): string 2855 2856Obtains the default user agent of this web page. 2857 2858**System capability**: SystemCapability.Web.Webview.Core 2859 2860**Return value** 2861 2862| Type | Description | 2863| ------ | -------------- | 2864| string | Default user agent.| 2865 2866**Error codes** 2867 2868For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2869 2870| ID| Error Message | 2871| -------- | ------------------------------------------------------------ | 2872| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2873 2874**Example** 2875 2876```ts 2877// xxx.ets 2878import web_webview from '@ohos.web.webview'; 2879import business_error from '@ohos.base'; 2880 2881@Entry 2882@Component 2883struct WebComponent { 2884 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2885 2886 build() { 2887 Column() { 2888 Button('getUserAgent') 2889 .onClick(() => { 2890 try { 2891 let userAgent = this.controller.getUserAgent(); 2892 console.log("userAgent: " + userAgent); 2893 } catch (error) { 2894 let e:business_error.BusinessError = error as business_error.BusinessError; 2895 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2896 } 2897 }) 2898 Web({ src: 'www.example.com', controller: this.controller }) 2899 } 2900 } 2901} 2902``` 2903 2904You can customize the user agent based on the default user agent. 2905```ts 2906// xxx.ets 2907import web_webview from '@ohos.web.webview'; 2908import business_error from '@ohos.base'; 2909 2910@Entry 2911@Component 2912struct WebComponent { 2913 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2914 @State ua: string = "" 2915 2916 aboutToAppear():void { 2917 web_webview.once('webInited', () => { 2918 try { 2919 // Customize the user agent on the application side. 2920 this.ua = this.controller.getUserAgent() + 'xxx'; 2921 } catch(error) { 2922 let e:business_error.BusinessError = error as business_error.BusinessError; 2923 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2924 } 2925 }) 2926 } 2927 2928 build() { 2929 Column() { 2930 Web({ src: 'www.example.com', controller: this.controller }) 2931 .userAgent(this.ua) 2932 } 2933 } 2934} 2935``` 2936 2937### getTitle 2938 2939getTitle(): string 2940 2941Obtains the title of the current web page. 2942 2943**System capability**: SystemCapability.Web.Webview.Core 2944 2945**Return value** 2946 2947| Type | Description | 2948| ------ | -------------------- | 2949| string | Title of the current web page.| 2950 2951**Error codes** 2952 2953For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 2954 2955| ID| Error Message | 2956| -------- | ------------------------------------------------------------ | 2957| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2958 2959**Example** 2960 2961```ts 2962// xxx.ets 2963import web_webview from '@ohos.web.webview'; 2964import business_error from '@ohos.base'; 2965 2966@Entry 2967@Component 2968struct WebComponent { 2969 controller: web_webview.WebviewController = new web_webview.WebviewController(); 2970 2971 build() { 2972 Column() { 2973 Button('getTitle') 2974 .onClick(() => { 2975 try { 2976 let title = this.controller.getTitle(); 2977 console.log("title: " + title); 2978 } catch (error) { 2979 let e:business_error.BusinessError = error as business_error.BusinessError; 2980 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 2981 } 2982 }) 2983 Web({ src: 'www.example.com', controller: this.controller }) 2984 } 2985 } 2986} 2987``` 2988 2989### getPageHeight 2990 2991getPageHeight(): number 2992 2993Obtains the height of this web page. 2994 2995**System capability**: SystemCapability.Web.Webview.Core 2996 2997**Return value** 2998 2999| Type | Description | 3000| ------ | -------------------- | 3001| number | Height of the current web page.| 3002 3003**Error codes** 3004 3005For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3006 3007| ID| Error Message | 3008| -------- | ------------------------------------------------------------ | 3009| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3010 3011**Example** 3012 3013```ts 3014// xxx.ets 3015import web_webview from '@ohos.web.webview'; 3016import business_error from '@ohos.base'; 3017 3018@Entry 3019@Component 3020struct WebComponent { 3021 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3022 3023 build() { 3024 Column() { 3025 Button('getPageHeight') 3026 .onClick(() => { 3027 try { 3028 let pageHeight = this.controller.getPageHeight(); 3029 console.log("pageHeight : " + pageHeight); 3030 } catch (error) { 3031 let e:business_error.BusinessError = error as business_error.BusinessError; 3032 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3033 } 3034 }) 3035 Web({ src: 'www.example.com', controller: this.controller }) 3036 } 3037 } 3038} 3039``` 3040 3041### storeWebArchive 3042 3043storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback\<string>): void 3044 3045Stores this web page. This API uses an asynchronous callback to return the result. 3046 3047**System capability**: SystemCapability.Web.Webview.Core 3048 3049**Parameters** 3050 3051| Name | Type | Mandatory| Description | 3052| -------- | --------------------- | ---- | ------------------------------------------------------------ | 3053| baseName | string | Yes | Save path of the web page. The value cannot be null. | 3054| 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. | 3055| callback | AsyncCallback\<string> | Yes | Callback used to return the save path if the operation is successful and null otherwise. | 3056 3057**Error codes** 3058 3059For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3060 3061| ID| Error Message | 3062| -------- | ------------------------------------------------------------ | 3063| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3064| 17100003 | Invalid resource path or file type. | 3065 3066**Example** 3067 3068```ts 3069// xxx.ets 3070import web_webview from '@ohos.web.webview' 3071import business_error from '@ohos.base' 3072 3073@Entry 3074@Component 3075struct WebComponent { 3076 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3077 3078 build() { 3079 Column() { 3080 Button('storeWebArchive') 3081 .onClick(() => { 3082 try { 3083 this.controller.storeWebArchive("/data/storage/el2/base/", true, (error, filename) => { 3084 if (error) { 3085 console.info(`save web archive error: ` + JSON.stringify(error)) 3086 return; 3087 } 3088 if (filename != null) { 3089 console.info(`save web archive success: ${filename}`) 3090 } 3091 }); 3092 } catch (error) { 3093 let e:business_error.BusinessError = error as business_error.BusinessError; 3094 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3095 } 3096 }) 3097 Web({ src: 'www.example.com', controller: this.controller }) 3098 } 3099 } 3100} 3101``` 3102 3103### storeWebArchive 3104 3105storeWebArchive(baseName: string, autoName: boolean): Promise\<string> 3106 3107Stores this web page. This API uses a promise to return the result. 3108 3109**System capability**: SystemCapability.Web.Webview.Core 3110 3111**Parameters** 3112 3113| Name | Type| Mandatory| Description | 3114| -------- | -------- | ---- | ------------------------------------------------------------ | 3115| baseName | string | Yes | Save path of the web page. The value cannot be null. | 3116| 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. | 3117 3118**Return value** 3119 3120| Type | Description | 3121| --------------- | ----------------------------------------------------- | 3122| Promise\<string> | Promise used to return the save path if the operation is successful and null otherwise.| 3123 3124**Error codes** 3125 3126For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3127 3128| ID| Error Message | 3129| -------- | ------------------------------------------------------------ | 3130| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3131| 17100003 | Invalid resource path or file type. | 3132 3133**Example** 3134 3135```ts 3136// xxx.ets 3137import web_webview from '@ohos.web.webview' 3138import business_error from '@ohos.base' 3139 3140@Entry 3141@Component 3142struct WebComponent { 3143 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3144 3145 build() { 3146 Column() { 3147 Button('storeWebArchive') 3148 .onClick(() => { 3149 try { 3150 this.controller.storeWebArchive("/data/storage/el2/base/", true) 3151 .then(filename => { 3152 if (filename != null) { 3153 console.info(`save web archive success: ${filename}`) 3154 } 3155 }) 3156 .catch((error:business_error.BusinessError) => { 3157 console.log('error: ' + JSON.stringify(error)); 3158 }) 3159 } catch (error) { 3160 let e:business_error.BusinessError = error as business_error.BusinessError; 3161 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3162 } 3163 }) 3164 Web({ src: 'www.example.com', controller: this.controller }) 3165 } 3166 } 3167} 3168``` 3169 3170### getUrl 3171 3172getUrl(): string 3173 3174Obtains the URL of this page. 3175 3176**System capability**: SystemCapability.Web.Webview.Core 3177 3178**Return value** 3179 3180| Type | Description | 3181| ------ | ------------------- | 3182| string | URL of the current page.| 3183 3184**Error codes** 3185 3186For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3187 3188| ID| Error Message | 3189| -------- | ------------------------------------------------------------ | 3190| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3191 3192**Example** 3193 3194```ts 3195// xxx.ets 3196import web_webview from '@ohos.web.webview'; 3197import business_error from '@ohos.base'; 3198 3199@Entry 3200@Component 3201struct WebComponent { 3202 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3203 3204 build() { 3205 Column() { 3206 Button('getUrl') 3207 .onClick(() => { 3208 try { 3209 let url = this.controller.getUrl(); 3210 console.log("url: " + url); 3211 } catch (error) { 3212 let e:business_error.BusinessError = error as business_error.BusinessError; 3213 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3214 } 3215 }) 3216 Web({ src: 'www.example.com', controller: this.controller }) 3217 } 3218 } 3219} 3220``` 3221 3222### stop 3223 3224stop(): void 3225 3226Stops page loading. 3227 3228**System capability**: SystemCapability.Web.Webview.Core 3229 3230**Error codes** 3231 3232For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3233 3234| ID| Error Message | 3235| -------- | ------------------------------------------------------------ | 3236| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3237 3238**Example** 3239 3240```ts 3241// xxx.ets 3242import web_webview from '@ohos.web.webview'; 3243import business_error from '@ohos.base'; 3244 3245@Entry 3246@Component 3247struct WebComponent { 3248 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3249 3250 build() { 3251 Column() { 3252 Button('stop') 3253 .onClick(() => { 3254 try { 3255 this.controller.stop(); 3256 } catch (error) { 3257 let e:business_error.BusinessError = error as business_error.BusinessError; 3258 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3259 } 3260 }); 3261 Web({ src: 'www.example.com', controller: this.controller }) 3262 } 3263 } 3264} 3265``` 3266 3267### backOrForward 3268 3269backOrForward(step: number): void 3270 3271Performs 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. 3272 3273Because the previously loaded web pages are used for the operation, no page reloading is involved. 3274 3275**System capability**: SystemCapability.Web.Webview.Core 3276 3277**Parameters** 3278 3279| Name| Type| Mandatory| Description | 3280| ------ | -------- | ---- | ---------------------- | 3281| step | number | Yes | Number of the steps to take.| 3282 3283**Error codes** 3284 3285For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3286 3287| ID| Error Message | 3288| -------- | ------------------------------------------------------------ | 3289| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3290 3291**Example** 3292 3293```ts 3294// xxx.ets 3295import web_webview from '@ohos.web.webview'; 3296import business_error from '@ohos.base'; 3297 3298@Entry 3299@Component 3300struct WebComponent { 3301 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3302 @State step: number = -2; 3303 3304 build() { 3305 Column() { 3306 Button('backOrForward') 3307 .onClick(() => { 3308 try { 3309 this.controller.backOrForward(this.step); 3310 } catch (error) { 3311 let e:business_error.BusinessError = error as business_error.BusinessError; 3312 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3313 } 3314 }) 3315 Web({ src: 'www.example.com', controller: this.controller }) 3316 } 3317 } 3318} 3319``` 3320 3321### scrollTo 3322 3323scrollTo(x:number, y:number): void 3324 3325Scrolls the page to the specified absolute position. 3326 3327**System capability**: SystemCapability.Web.Webview.Core 3328 3329**Parameters** 3330 3331| Name| Type| Mandatory| Description | 3332| ------ | -------- | ---- | ---------------------- | 3333| x | number | Yes | X coordinate of the absolute position. If the value is a negative number, the value 0 is used.| 3334| y | number | Yes | Y coordinate of the absolute position. If the value is a negative number, the value 0 is used.| 3335 3336**Error codes** 3337 3338For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3339 3340| ID| Error Message | 3341| -------- | ------------------------------------------------------------ | 3342| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3343 3344**Example** 3345 3346```ts 3347// xxx.ets 3348import web_webview from '@ohos.web.webview'; 3349import business_error from '@ohos.base'; 3350 3351@Entry 3352@Component 3353struct WebComponent { 3354 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3355 3356 build() { 3357 Column() { 3358 Button('scrollTo') 3359 .onClick(() => { 3360 try { 3361 this.controller.scrollTo(50, 50); 3362 } catch (error) { 3363 let e:business_error.BusinessError = error as business_error.BusinessError; 3364 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3365 } 3366 }) 3367 Web({ src: $rawfile('index.html'), controller: this.controller }) 3368 } 3369 } 3370} 3371``` 3372 3373HTML file to be loaded: 3374```html 3375<!--index.html--> 3376<!DOCTYPE html> 3377<html> 3378<head> 3379 <title>Demo</title> 3380 <style> 3381 body { 3382 width:3000px; 3383 height:3000px; 3384 padding-right:170px; 3385 padding-left:170px; 3386 border:5px solid blueviolet 3387 } 3388 </style> 3389</head> 3390<body> 3391Scroll Test 3392</body> 3393</html> 3394``` 3395 3396### scrollBy 3397 3398scrollBy(deltaX:number, deltaY:number): void 3399 3400Scrolls the page by the specified amount. 3401 3402**System capability**: SystemCapability.Web.Webview.Core 3403 3404**Parameters** 3405 3406| Name| Type| Mandatory| Description | 3407| ------ | -------- | ---- | ---------------------- | 3408| deltaX | number | Yes | Amount to scroll by along the x-axis. The positive direction is rightward.| 3409| deltaY | number | Yes | Amount to scroll by along the y-axis. The positive direction is downward.| 3410 3411**Error codes** 3412 3413For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3414 3415| ID| Error Message | 3416| -------- | ------------------------------------------------------------ | 3417| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3418 3419**Example** 3420 3421```ts 3422// xxx.ets 3423import web_webview from '@ohos.web.webview'; 3424import business_error from '@ohos.base'; 3425 3426@Entry 3427@Component 3428struct WebComponent { 3429 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3430 3431 build() { 3432 Column() { 3433 Button('scrollBy') 3434 .onClick(() => { 3435 try { 3436 this.controller.scrollBy(50, 50); 3437 } catch (error) { 3438 let e:business_error.BusinessError = error as business_error.BusinessError; 3439 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3440 } 3441 }) 3442 Web({ src: $rawfile('index.html'), controller: this.controller }) 3443 } 3444 } 3445} 3446``` 3447 3448HTML file to be loaded: 3449```html 3450<!--index.html--> 3451<!DOCTYPE html> 3452<html> 3453<head> 3454 <title>Demo</title> 3455 <style> 3456 body { 3457 width:3000px; 3458 height:3000px; 3459 padding-right:170px; 3460 padding-left:170px; 3461 border:5px solid blueviolet 3462 } 3463 </style> 3464</head> 3465<body> 3466Scroll Test 3467</body> 3468</html> 3469``` 3470 3471### slideScroll 3472 3473slideScroll(vx:number, vy:number): void 3474 3475Simulates a slide-to-scroll action on the page at the specified velocity. 3476 3477**System capability**: SystemCapability.Web.Webview.Core 3478 3479**Parameters** 3480 3481| Name| Type| Mandatory| Description | 3482| ------ | -------- | ---- | ---------------------- | 3483| vx | number | Yes | Horizontal velocity component of the slide-to-scroll action, where the positive direction is rightward.| 3484| vy | number | Yes | Vertical velocity component of the slide-to-scroll action, where the positive direction is downward.| 3485 3486**Error codes** 3487 3488For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3489 3490| ID| Error Message | 3491| -------- | ------------------------------------------------------------ | 3492| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3493 3494**Example** 3495 3496```ts 3497// xxx.ets 3498import web_webview from '@ohos.web.webview'; 3499import business_error from '@ohos.base'; 3500 3501@Entry 3502@Component 3503struct WebComponent { 3504 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3505 3506 build() { 3507 Column() { 3508 Button('slideScroll') 3509 .onClick(() => { 3510 try { 3511 this.controller.slideScroll(500, 500); 3512 } catch (error) { 3513 let e:business_error.BusinessError = error as business_error.BusinessError; 3514 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3515 } 3516 }) 3517 Web({ src: $rawfile('index.html'), controller: this.controller }) 3518 } 3519 } 3520} 3521``` 3522 3523HTML file to be loaded: 3524```html 3525<!--index.html--> 3526<!DOCTYPE html> 3527<html> 3528<head> 3529 <title>Demo</title> 3530 <style> 3531 body { 3532 width:3000px; 3533 height:3000px; 3534 padding-right:170px; 3535 padding-left:170px; 3536 border:5px solid blueviolet 3537 } 3538 </style> 3539</head> 3540<body> 3541Scroll Test 3542</body> 3543</html> 3544``` 3545 3546### getOriginalUrl 3547 3548getOriginalUrl(): string 3549 3550Obtains the original URL of this page. 3551 3552**System capability**: SystemCapability.Web.Webview.Core 3553 3554**Return value** 3555 3556| Type | Description | 3557| ------ | ----------------------- | 3558| string | Original URL of the current page.| 3559 3560**Error codes** 3561 3562For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3563 3564| ID| Error Message | 3565| -------- | ------------------------------------------------------------ | 3566| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3567 3568**Example** 3569 3570```ts 3571// xxx.ets 3572import web_webview from '@ohos.web.webview'; 3573import business_error from '@ohos.base'; 3574 3575@Entry 3576@Component 3577struct WebComponent { 3578 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3579 3580 build() { 3581 Column() { 3582 Button('getOrgUrl') 3583 .onClick(() => { 3584 try { 3585 let url = this.controller.getOriginalUrl(); 3586 console.log("original url: " + url); 3587 } catch (error) { 3588 let e:business_error.BusinessError = error as business_error.BusinessError; 3589 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3590 } 3591 }) 3592 Web({ src: 'www.example.com', controller: this.controller }) 3593 } 3594 } 3595} 3596``` 3597 3598### getFavicon 3599 3600getFavicon(): image.PixelMap 3601 3602Obtains the favicon of this page. 3603 3604**System capability**: SystemCapability.Web.Webview.Core 3605 3606**Return value** 3607 3608| Type | Description | 3609| -------------------------------------- | ------------------------------- | 3610| [PixelMap](js-apis-image.md#pixelmap7) | **PixelMap** object of the favicon of the page.| 3611 3612**Error codes** 3613 3614For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3615 3616| ID| Error Message | 3617| -------- | ------------------------------------------------------------ | 3618| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3619 3620**Example** 3621 3622```ts 3623// xxx.ets 3624import web_webview from '@ohos.web.webview'; 3625import image from "@ohos.multimedia.image"; 3626import business_error from '@ohos.base'; 3627 3628@Entry 3629@Component 3630struct WebComponent { 3631 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3632 @State pixelmap: image.PixelMap | undefined = undefined; 3633 3634 build() { 3635 Column() { 3636 Button('getFavicon') 3637 .onClick(() => { 3638 try { 3639 this.pixelmap = this.controller.getFavicon(); 3640 } catch (error) { 3641 let e:business_error.BusinessError = error as business_error.BusinessError; 3642 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3643 } 3644 }) 3645 Web({ src: 'www.example.com', controller: this.controller }) 3646 } 3647 } 3648} 3649``` 3650 3651### setNetworkAvailable 3652 3653setNetworkAvailable(enable: boolean): void 3654 3655Sets the **window.navigator.onLine** attribute in JavaScript. 3656 3657**System capability**: SystemCapability.Web.Webview.Core 3658 3659**Parameters** 3660 3661| Name| Type | Mandatory| Description | 3662| ------ | ------- | ---- | --------------------------------- | 3663| enable | boolean | Yes | Whether to enable **window.navigator.onLine**.| 3664 3665**Error codes** 3666 3667For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3668 3669| ID| Error Message | 3670| -------- | ------------------------------------------------------------ | 3671| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3672 3673**Example** 3674 3675```ts 3676// xxx.ets 3677import web_webview from '@ohos.web.webview'; 3678import business_error from '@ohos.base'; 3679 3680@Entry 3681@Component 3682struct WebComponent { 3683 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3684 3685 build() { 3686 Column() { 3687 Button('setNetworkAvailable') 3688 .onClick(() => { 3689 try { 3690 this.controller.setNetworkAvailable(true); 3691 } catch (error) { 3692 let e:business_error.BusinessError = error as business_error.BusinessError; 3693 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3694 } 3695 }) 3696 Web({ src: $rawfile('index.html'), controller: this.controller }) 3697 } 3698 } 3699} 3700``` 3701 3702HTML file to be loaded: 3703```html 3704<!-- index.html --> 3705<!DOCTYPE html> 3706<html> 3707<body> 3708<h1>online attribute </h1> 3709<p id="demo"></p> 3710<button onclick="func()">click</button> 3711<script> 3712 let online = navigator.onLine; 3713 document.getElementById ("demo").innerHTML = "Browser online:" + online; 3714 3715 function func(){ 3716 var online = navigator.onLine; 3717 document.getElementById ("demo").innerHTML = "Browser online:" + online; 3718 } 3719</script> 3720</body> 3721</html> 3722``` 3723 3724### hasImage 3725 3726hasImage(callback: AsyncCallback\<boolean>): void 3727 3728Checks whether this page contains images. This API uses an asynchronous callback to return the result. 3729 3730**System capability**: SystemCapability.Web.Webview.Core 3731 3732**Parameters** 3733 3734| Name | Type | Mandatory| Description | 3735| -------- | ----------------------- | ---- | -------------------------- | 3736| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result.| 3737 3738**Error codes** 3739 3740For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3741 3742| ID| Error Message | 3743| -------- | ------------------------------------------------------------ | 3744| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3745 3746**Example** 3747 3748```ts 3749// xxx.ets 3750import web_webview from '@ohos.web.webview'; 3751import business_error from '@ohos.base'; 3752 3753@Entry 3754@Component 3755struct WebComponent { 3756 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3757 3758 build() { 3759 Column() { 3760 Button('hasImageCb') 3761 .onClick(() => { 3762 try { 3763 this.controller.hasImage((error, data) => { 3764 if (error) { 3765 console.info(`hasImage error: ` + JSON.stringify(error)) 3766 return; 3767 } 3768 console.info("hasImage: " + data); 3769 }); 3770 } catch (error) { 3771 let e:business_error.BusinessError = error as business_error.BusinessError; 3772 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3773 } 3774 }) 3775 Web({ src: 'www.example.com', controller: this.controller }) 3776 } 3777 } 3778} 3779``` 3780 3781### hasImage 3782 3783hasImage(): Promise\<boolean> 3784 3785Checks whether this page contains images. This API uses a promise to return the result. 3786 3787**System capability**: SystemCapability.Web.Webview.Core 3788 3789**Return value** 3790 3791| Type | Description | 3792| ----------------- | --------------------------------------- | 3793| Promise\<boolean> | Promise used to return the result.| 3794 3795**Error codes** 3796 3797For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3798 3799| ID| Error Message | 3800| -------- | ------------------------------------------------------------ | 3801| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3802 3803**Example** 3804 3805```ts 3806// xxx.ets 3807import web_webview from '@ohos.web.webview'; 3808import business_error from '@ohos.base'; 3809 3810@Entry 3811@Component 3812struct WebComponent { 3813 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3814 3815 build() { 3816 Column() { 3817 Button('hasImagePm') 3818 .onClick(() => { 3819 try { 3820 this.controller.hasImage().then((data) => { 3821 console.info('hasImage: ' + data); 3822 }) 3823 .catch((error:business_error.BusinessError) => { 3824 console.error("error: " + error); 3825 }) 3826 } catch (error) { 3827 let e:business_error.BusinessError = error as business_error.BusinessError; 3828 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3829 } 3830 }) 3831 Web({ src: 'www.example.com', controller: this.controller }) 3832 } 3833 } 3834} 3835``` 3836 3837### removeCache 3838 3839removeCache(clearRom: boolean): void 3840 3841Clears the cache in the application. This API will clear the cache for all webviews in the same application. 3842 3843**System capability**: SystemCapability.Web.Webview.Core 3844 3845**Parameters** 3846 3847| Name | Type | Mandatory| Description | 3848| -------- | ------- | ---- | -------------------------------------------------------- | 3849| 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.| 3850 3851**Error codes** 3852 3853For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3854 3855| ID| Error Message | 3856| -------- | ------------------------------------------------------------ | 3857| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3858 3859**Example** 3860 3861```ts 3862// xxx.ets 3863import web_webview from '@ohos.web.webview'; 3864import business_error from '@ohos.base'; 3865 3866@Entry 3867@Component 3868struct WebComponent { 3869 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3870 3871 build() { 3872 Column() { 3873 Button('removeCache') 3874 .onClick(() => { 3875 try { 3876 this.controller.removeCache(false); 3877 } catch (error) { 3878 let e:business_error.BusinessError = error as business_error.BusinessError; 3879 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3880 } 3881 }) 3882 Web({ src: 'www.example.com', controller: this.controller }) 3883 } 3884 } 3885} 3886``` 3887 3888### pageUp 3889 3890pageUp(top: boolean): void 3891 3892Scrolls the page up by half the viewport or jumps to the top of the page. 3893 3894**System capability**: SystemCapability.Web.Webview.Core 3895 3896**Parameters** 3897 3898| Name| Type | Mandatory| Description | 3899| ------ | ------- | ---- | ------------------------------------------------------------ | 3900| 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.| 3901 3902**Error codes** 3903 3904For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3905 3906| ID| Error Message | 3907| -------- | ------------------------------------------------------------ | 3908| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3909 3910**Example** 3911 3912```ts 3913// xxx.ets 3914import web_webview from '@ohos.web.webview'; 3915import business_error from '@ohos.base'; 3916 3917@Entry 3918@Component 3919struct WebComponent { 3920 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3921 3922 build() { 3923 Column() { 3924 Button('pageUp') 3925 .onClick(() => { 3926 try { 3927 this.controller.pageUp(false); 3928 } catch (error) { 3929 let e:business_error.BusinessError = error as business_error.BusinessError; 3930 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3931 } 3932 }) 3933 Web({ src: 'www.example.com', controller: this.controller }) 3934 } 3935 } 3936} 3937``` 3938 3939### pageDown 3940 3941pageDown(bottom: boolean): void 3942 3943Scrolls the page down by half the viewport or jumps to the bottom of the page. 3944 3945**System capability**: SystemCapability.Web.Webview.Core 3946 3947**Parameters** 3948 3949| Name| Type | Mandatory| Description | 3950| ------ | ------- | ---- | ------------------------------------------------------------ | 3951| 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.| 3952 3953**Error codes** 3954 3955For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 3956 3957| ID| Error Message | 3958| -------- | ------------------------------------------------------------ | 3959| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3960 3961**Example** 3962 3963```ts 3964// xxx.ets 3965import web_webview from '@ohos.web.webview'; 3966import business_error from '@ohos.base'; 3967 3968@Entry 3969@Component 3970struct WebComponent { 3971 controller: web_webview.WebviewController = new web_webview.WebviewController(); 3972 3973 build() { 3974 Column() { 3975 Button('pageDown') 3976 .onClick(() => { 3977 try { 3978 this.controller.pageDown(false); 3979 } catch (error) { 3980 let e:business_error.BusinessError = error as business_error.BusinessError; 3981 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 3982 } 3983 }) 3984 Web({ src: 'www.example.com', controller: this.controller }) 3985 } 3986 } 3987} 3988``` 3989 3990### getBackForwardEntries 3991 3992getBackForwardEntries(): BackForwardList 3993 3994Obtains the historical information list of the current webview. 3995 3996**System capability**: SystemCapability.Web.Webview.Core 3997 3998**Return value** 3999 4000| Type | Description | 4001| ----------------------------------- | --------------------------- | 4002| [BackForwardList](#backforwardlist) | Historical information list of the current webview.| 4003 4004**Error codes** 4005 4006For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4007 4008| ID| Error Message | 4009| -------- | ------------------------------------------------------------ | 4010| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4011 4012**Example** 4013 4014```ts 4015// xxx.ets 4016import web_webview from '@ohos.web.webview'; 4017import business_error from '@ohos.base'; 4018 4019@Entry 4020@Component 4021struct WebComponent { 4022 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4023 4024 build() { 4025 Column() { 4026 Button('getBackForwardEntries') 4027 .onClick(() => { 4028 try { 4029 let list = this.controller.getBackForwardEntries() 4030 } catch (error) { 4031 let e:business_error.BusinessError = error as business_error.BusinessError; 4032 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4033 } 4034 }) 4035 Web({ src: 'www.example.com', controller: this.controller }) 4036 } 4037 } 4038} 4039``` 4040 4041### serializeWebState 4042 4043serializeWebState(): Uint8Array 4044 4045Serializes the page status history of the current Webview. 4046 4047**System capability**: SystemCapability.Web.Webview.Core 4048 4049**Return value** 4050 4051| Type | Description | 4052| ---------- | --------------------------------------------- | 4053| Uint8Array | Serialized data of the page status history of the current WebView.| 4054 4055**Error codes** 4056 4057For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4058 4059| ID| Error Message | 4060| -------- | ------------------------------------------------------------ | 4061| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4062 4063**Example** 4064 40651. To perform operations on files, you must import the file management module. For details, see [File Management](./js-apis-file-fs.md). 4066```ts 4067// xxx.ets 4068import web_webview from '@ohos.web.webview'; 4069import fs from '@ohos.file.fs'; 4070import business_error from '@ohos.base'; 4071 4072@Entry 4073@Component 4074struct WebComponent { 4075 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4076 4077 build() { 4078 Column() { 4079 Button('serializeWebState') 4080 .onClick(() => { 4081 try { 4082 let state = this.controller.serializeWebState(); 4083 let path:string | undefined = AppStorage.get("cacheDir"); 4084 if (path) { 4085 path += '/WebState'; 4086 // Synchronously open a file. 4087 let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 4088 fs.writeSync(file.fd, state.buffer); 4089 fs.closeSync(file.fd); 4090 } 4091 } catch (error) { 4092 let e:business_error.BusinessError = error as business_error.BusinessError; 4093 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4094 } 4095 }) 4096 Web({ src: 'www.example.com', controller: this.controller }) 4097 } 4098 } 4099} 4100``` 4101 41022. Modify the **EntryAbility.ts** file. 4103Obtain the path of the application cache file. 4104```ts 4105// xxx.ts 4106import UIAbility from '@ohos.app.ability.UIAbility'; 4107import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 4108import Want from '@ohos.app.ability.Want'; 4109 4110export default class EntryAbility extends UIAbility { 4111 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 4112 // Data synchronization between the UIAbility component and the page can be implemented by binding cacheDir to the AppStorage object. 4113 AppStorage.setOrCreate("cacheDir", this.context.cacheDir); 4114 } 4115} 4116``` 4117 4118### restoreWebState 4119 4120restoreWebState(state: Uint8Array): void 4121 4122Restores the page status history from the serialized data of the current WebView. 4123 4124**System capability**: SystemCapability.Web.Webview.Core 4125 4126**Parameters** 4127 4128| Name| Type | Mandatory| Description | 4129| ------ | ---------- | ---- | ---------------------------- | 4130| state | Uint8Array | Yes | Serialized data of the page status history.| 4131 4132**Error codes** 4133 4134For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4135 4136| ID| Error Message | 4137| -------- | ------------------------------------------------------------ | 4138| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4139 4140**Example** 4141 41421. To perform operations on files, you must import the file management module. For details, see [File Management](./js-apis-file-fs.md). 4143```ts 4144// xxx.ets 4145import web_webview from '@ohos.web.webview'; 4146import fs from '@ohos.file.fs'; 4147import business_error from '@ohos.base'; 4148 4149@Entry 4150@Component 4151struct WebComponent { 4152 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4153 4154 build() { 4155 Column() { 4156 Button('RestoreWebState') 4157 .onClick(() => { 4158 try { 4159 let path:string | undefined = AppStorage.get("cacheDir"); 4160 if (path) { 4161 path += '/WebState'; 4162 // Synchronously open a file. 4163 let file = fs.openSync(path, fs.OpenMode.READ_WRITE); 4164 let stat = fs.statSync(path); 4165 let size = stat.size; 4166 let buf = new ArrayBuffer(size); 4167 fs.read(file.fd, buf, (err, readLen) => { 4168 if (err) { 4169 console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); 4170 } else { 4171 console.info("read file data succeed"); 4172 this.controller.restoreWebState(new Uint8Array(buf.slice(0, readLen))); 4173 fs.closeSync(file); 4174 } 4175 }); 4176 } 4177 } catch (error) { 4178 let e:business_error.BusinessError = error as business_error.BusinessError; 4179 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4180 } 4181 }) 4182 Web({ src: 'www.example.com', controller: this.controller }) 4183 } 4184 } 4185} 4186``` 4187 41882. Modify the **EntryAbility.ts** file. 4189Obtain the path of the application cache file. 4190```ts 4191// xxx.ts 4192import UIAbility from '@ohos.app.ability.UIAbility'; 4193import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 4194import Want from '@ohos.app.ability.Want'; 4195 4196export default class EntryAbility extends UIAbility { 4197 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 4198 // Data synchronization between the UIAbility component and the page can be implemented by binding cacheDir to the AppStorage object. 4199 AppStorage.setOrCreate("cacheDir", this.context.cacheDir); 4200 } 4201} 4202``` 4203 4204### customizeSchemes 4205 4206static customizeSchemes(schemes: Array\<WebCustomScheme\>): void 4207 4208Customizes the URL schemes (also known as protocols). It is recommended that this API be called before any **\<Web>** component is initialized. 4209 4210**System capability**: SystemCapability.Web.Webview.Core 4211 4212**Parameters** 4213 4214| Name | Type | Mandatory| Description | 4215| -------- | ------- | ---- | -------------------------------------- | 4216| schemes | Array\<[WebCustomScheme](#webcustomscheme)\> | Yes | Array of up to 10 custom schemes.| 4217 4218**Example** 4219 4220```ts 4221// xxx.ets 4222import web_webview from '@ohos.web.webview'; 4223import business_error from '@ohos.base'; 4224 4225@Entry 4226@Component 4227struct WebComponent { 4228 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4229 responseweb: WebResourceResponse = new WebResourceResponse() 4230 scheme1: web_webview.WebCustomScheme = {schemeName: "name1", isSupportCORS: true, isSupportFetch: true} 4231 scheme2: web_webview.WebCustomScheme = {schemeName: "name2", isSupportCORS: true, isSupportFetch: true} 4232 scheme3: web_webview.WebCustomScheme = {schemeName: "name3", isSupportCORS: true, isSupportFetch: true} 4233 4234 aboutToAppear():void { 4235 try { 4236 web_webview.WebviewController.customizeSchemes([this.scheme1, this.scheme2, this.scheme3]) 4237 } catch(error) { 4238 let e:business_error.BusinessError = error as business_error.BusinessError; 4239 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4240 } 4241 } 4242 4243 build() { 4244 Column() { 4245 Web({ src: 'www.example.com', controller: this.controller }) 4246 .onInterceptRequest((event) => { 4247 if (event) { 4248 console.log('url:' + event.request.getRequestUrl()) 4249 } 4250 return this.responseweb 4251 }) 4252 } 4253 } 4254} 4255``` 4256 4257### getCertificate<sup>10+</sup> 4258 4259getCertificate(): Promise<Array<cert.X509Cert>> 4260 4261Obtains 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#x509cert) of the current website. 4262 4263**System capability**: SystemCapability.Web.Webview.Core 4264 4265**Return value** 4266 4267| Type | Description | 4268| ---------- | --------------------------------------------- | 4269| Promise<Array<cert.X509Cert>> | Promise used to obtain the X.509 certificate array of the current HTTPS website.| 4270 4271**Error codes** 4272 4273For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4274 4275| ID| Error Message | 4276| -------- | ------------------------------------------------------------ | 4277| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4278 4279**Example** 4280 4281```ts 4282// xxx.ets 4283import web_webview from '@ohos.web.webview'; 4284import business_error from '@ohos.base'; 4285import cert from '@ohos.security.cert'; 4286 4287function Uint8ArrayToString(dataArray:Uint8Array) { 4288 let dataString = '' 4289 for (let i = 0; i < dataArray.length; i++) { 4290 dataString += String.fromCharCode(dataArray[i]) 4291 } 4292 return dataString 4293} 4294 4295function ParseX509CertInfo(x509CertArray:Array<cert.X509Cert>) { 4296 let res: string = 'getCertificate success: len = ' + x509CertArray.length; 4297 for (let i = 0; i < x509CertArray.length; i++) { 4298 res += ', index = ' + i + ', issuer name = ' 4299 + Uint8ArrayToString(x509CertArray[i].getIssuerName().data) + ', subject name = ' 4300 + Uint8ArrayToString(x509CertArray[i].getSubjectName().data) + ', valid start = ' 4301 + x509CertArray[i].getNotBeforeTime() 4302 + ', valid end = ' + x509CertArray[i].getNotAfterTime() 4303 } 4304 return res 4305} 4306 4307@Entry 4308@Component 4309struct Index { 4310 // outputStr displays debug information on the UI. 4311 @State outputStr: string = '' 4312 webviewCtl: web_webview.WebviewController = new web_webview.WebviewController(); 4313 4314 build() { 4315 Row() { 4316 Column() { 4317 List({space: 20, initialIndex: 0}) { 4318 ListItem() { 4319 Button() { 4320 Text('load bad ssl') 4321 .fontSize(10) 4322 .fontWeight(FontWeight.Bold) 4323 } 4324 .type(ButtonType.Capsule) 4325 .onClick(() => { 4326 // Load an expired certificate website and view the obtained certificate information. 4327 this.webviewCtl.loadUrl('https://expired.badssl.com') 4328 }) 4329 .height(50) 4330 } 4331 4332 ListItem() { 4333 Button() { 4334 Text('load example') 4335 .fontSize(10) 4336 .fontWeight(FontWeight.Bold) 4337 } 4338 .type(ButtonType.Capsule) 4339 .onClick(() => { 4340 // Load an HTTPS website and view the certificate information of the website. 4341 this.webviewCtl.loadUrl('https://www.example.com') 4342 }) 4343 .height(50) 4344 } 4345 4346 ListItem() { 4347 Button() { 4348 Text('getCertificate Promise') 4349 .fontSize(10) 4350 .fontWeight(FontWeight.Bold) 4351 } 4352 .type(ButtonType.Capsule) 4353 .onClick(() => { 4354 try { 4355 this.webviewCtl.getCertificate().then((x509CertArray:Array<cert.X509Cert>) => { 4356 this.outputStr = ParseX509CertInfo(x509CertArray); 4357 }) 4358 } catch (error) { 4359 let e:business_error.BusinessError = error as business_error.BusinessError; 4360 this.outputStr = 'getCertificate failed: ' + e.code + ", errMsg: " + e.message; 4361 } 4362 }) 4363 .height(50) 4364 } 4365 4366 ListItem() { 4367 Button() { 4368 Text('getCertificate AsyncCallback') 4369 .fontSize(10) 4370 .fontWeight(FontWeight.Bold) 4371 } 4372 .type(ButtonType.Capsule) 4373 .onClick(() => { 4374 try { 4375 this.webviewCtl.getCertificate((error:business_error.BusinessError, x509CertArray:Array<cert.X509Cert>) => { 4376 if (error) { 4377 this.outputStr = 'getCertificate failed: ' + error.code + ", errMsg: " + error.message; 4378 } else { 4379 this.outputStr = ParseX509CertInfo(x509CertArray); 4380 } 4381 }) 4382 } catch (error) { 4383 let e:business_error.BusinessError = error as business_error.BusinessError; 4384 this.outputStr = 'getCertificate failed: ' + e.code + ", errMsg: " + e.message; 4385 } 4386 }) 4387 .height(50) 4388 } 4389 } 4390 .listDirection(Axis.Horizontal) 4391 .height('10%') 4392 4393 Text(this.outputStr) 4394 .width('100%') 4395 .fontSize(10) 4396 4397 Web({ src: 'https://www.example.com', controller: this.webviewCtl }) 4398 .fileAccess(true) 4399 .javaScriptAccess(true) 4400 .domStorageAccess(true) 4401 .onlineImageAccess(true) 4402 .onPageEnd((e) => { 4403 if(e) { 4404 this.outputStr = 'onPageEnd : url = ' + e.url 4405 } 4406 }) 4407 .onSslErrorEventReceive((e) => { 4408 // Ignore SSL certificate errors to test websites whose certificates have expired, for example, https://expired.badssl.com. 4409 e.handler.handleConfirm() 4410 }) 4411 .width('100%') 4412 .height('70%') 4413 } 4414 .height('100%') 4415 } 4416 } 4417} 4418``` 4419 4420### getCertificate<sup>10+</sup> 4421 4422getCertificate(callback: AsyncCallback<Array<cert.X509Cert>>): void 4423 4424Obtains 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. 4425 4426**System capability**: SystemCapability.Web.Webview.Core 4427 4428**Parameters** 4429 4430| Name | Type | Mandatory| Description | 4431| -------- | ---------------------------- | ---- | ---------------------------------------- | 4432| callback | AsyncCallback<Array<cert.X509Cert>> | Yes | Callback used to obtain the X.509 certificate array of the current website.| 4433 4434**Error codes** 4435 4436For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4437 4438| ID| Error Message | 4439| -------- | ------------------------------------------------------------ | 4440| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4441 4442**Example** 4443 4444```ts 4445// xxx.ets 4446import web_webview from '@ohos.web.webview'; 4447import business_error from '@ohos.base'; 4448import cert from '@ohos.security.cert'; 4449 4450function Uint8ArrayToString(dataArray:Uint8Array) { 4451 let dataString = '' 4452 for (let i = 0; i < dataArray.length; i++) { 4453 dataString += String.fromCharCode(dataArray[i]) 4454 } 4455 return dataString 4456} 4457 4458function ParseX509CertInfo(x509CertArray:Array<cert.X509Cert>) { 4459 let res: string = 'getCertificate success: len = ' + x509CertArray.length; 4460 for (let i = 0; i < x509CertArray.length; i++) { 4461 res += ', index = ' + i + ', issuer name = ' 4462 + Uint8ArrayToString(x509CertArray[i].getIssuerName().data) + ', subject name = ' 4463 + Uint8ArrayToString(x509CertArray[i].getSubjectName().data) + ', valid start = ' 4464 + x509CertArray[i].getNotBeforeTime() 4465 + ', valid end = ' + x509CertArray[i].getNotAfterTime() 4466 } 4467 return res 4468} 4469 4470@Entry 4471@Component 4472struct Index { 4473 // outputStr displays debug information on the UI. 4474 @State outputStr: string = '' 4475 webviewCtl: web_webview.WebviewController = new web_webview.WebviewController(); 4476 4477 build() { 4478 Row() { 4479 Column() { 4480 List({space: 20, initialIndex: 0}) { 4481 ListItem() { 4482 Button() { 4483 Text('load bad ssl') 4484 .fontSize(10) 4485 .fontWeight(FontWeight.Bold) 4486 } 4487 .type(ButtonType.Capsule) 4488 .onClick(() => { 4489 // Load an expired certificate website and view the obtained certificate information. 4490 this.webviewCtl.loadUrl('https://expired.badssl.com') 4491 }) 4492 .height(50) 4493 } 4494 4495 ListItem() { 4496 Button() { 4497 Text('load example') 4498 .fontSize(10) 4499 .fontWeight(FontWeight.Bold) 4500 } 4501 .type(ButtonType.Capsule) 4502 .onClick(() => { 4503 // Load an HTTPS website and view the certificate information of the website. 4504 this.webviewCtl.loadUrl('https://www.example.com') 4505 }) 4506 .height(50) 4507 } 4508 4509 ListItem() { 4510 Button() { 4511 Text('getCertificate Promise') 4512 .fontSize(10) 4513 .fontWeight(FontWeight.Bold) 4514 } 4515 .type(ButtonType.Capsule) 4516 .onClick(() => { 4517 try { 4518 this.webviewCtl.getCertificate().then((x509CertArray:Array<cert.X509Cert>) => { 4519 this.outputStr = ParseX509CertInfo(x509CertArray); 4520 }) 4521 } catch (error) { 4522 let e:business_error.BusinessError = error as business_error.BusinessError; 4523 this.outputStr = 'getCertificate failed: ' + e.code + ", errMsg: " + e.message; 4524 } 4525 }) 4526 .height(50) 4527 } 4528 4529 ListItem() { 4530 Button() { 4531 Text('getCertificate AsyncCallback') 4532 .fontSize(10) 4533 .fontWeight(FontWeight.Bold) 4534 } 4535 .type(ButtonType.Capsule) 4536 .onClick(() => { 4537 try { 4538 this.webviewCtl.getCertificate((error:business_error.BusinessError, x509CertArray:Array<cert.X509Cert>) => { 4539 if (error) { 4540 this.outputStr = 'getCertificate failed: ' + error.code + ", errMsg: " + error.message; 4541 } else { 4542 this.outputStr = ParseX509CertInfo(x509CertArray); 4543 } 4544 }) 4545 } catch (error) { 4546 let e:business_error.BusinessError = error as business_error.BusinessError; 4547 this.outputStr = 'getCertificate failed: ' + e.code + ", errMsg: " + e.message; 4548 } 4549 }) 4550 .height(50) 4551 } 4552 } 4553 .listDirection(Axis.Horizontal) 4554 .height('10%') 4555 4556 Text(this.outputStr) 4557 .width('100%') 4558 .fontSize(10) 4559 4560 Web({ src: 'https://www.example.com', controller: this.webviewCtl }) 4561 .fileAccess(true) 4562 .javaScriptAccess(true) 4563 .domStorageAccess(true) 4564 .onlineImageAccess(true) 4565 .onPageEnd((e) => { 4566 if (e) { 4567 this.outputStr = 'onPageEnd : url = ' + e.url 4568 } 4569 }) 4570 .onSslErrorEventReceive((e) => { 4571 // Ignore SSL certificate errors to test websites whose certificates have expired, for example, https://expired.badssl.com. 4572 e.handler.handleConfirm() 4573 }) 4574 .width('100%') 4575 .height('70%') 4576 } 4577 .height('100%') 4578 } 4579 } 4580} 4581``` 4582 4583### setAudioMuted<sup>10+</sup> 4584 4585setAudioMuted(mute: boolean): void 4586 4587Mutes this web page. 4588 4589**System capability**: SystemCapability.Web.Webview.Core 4590 4591**Parameters** 4592 4593| Name | Type | Mandatory| Description | 4594| -------- | ------- | ---- | -------------------------------------- | 4595| mute | boolean | Yes | Whether to mute the web page. The value **true** means to mute the web page, and **false** means the opposite.| 4596 4597**Error codes** 4598 4599For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4600 4601| ID| Error Message | 4602| -------- | ------------------------------------------------------------ | 4603| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4604 4605**Example** 4606 4607```ts 4608// xxx.ets 4609import web_webview from '@ohos.web.webview' 4610 4611@Entry 4612@Component 4613struct WebComponent { 4614 controller: web_webview.WebviewController = new web_webview.WebviewController() 4615 @State muted: boolean = false 4616 build() { 4617 Column() { 4618 Button("Toggle Mute") 4619 .onClick(event => { 4620 this.muted = !this.muted 4621 this.controller.setAudioMuted(this.muted) 4622 }) 4623 Web({ src: 'www.example.com', controller: this.controller }) 4624 } 4625 } 4626} 4627``` 4628 4629### prefetchPage<sup>10+</sup> 4630 4631prefetchPage(url: string, additionalHeaders?: Array\<WebHeader>): void 4632 4633Prefetches 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. 4634 4635**System capability**: SystemCapability.Web.Webview.Core 4636 4637**Parameters** 4638 4639| Name | Type | Mandatory | Description | 4640| ------------------| --------------------------------| ---- | ------------- | 4641| url | string | Yes | URL to be preloaded.| 4642| additionalHeaders | Array\<[WebHeader](#webheader)> | No | Additional HTTP headers of the URL.| 4643 4644**Error codes** 4645 4646For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4647 4648| ID | Error Message | 4649| -------- | ------------------------------------------------------------ | 4650| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4651| 17100002 | Invalid url. | 4652 4653**Example** 4654 4655```ts 4656// xxx.ets 4657import web_webview from '@ohos.web.webview' 4658import business_error from '@ohos.base' 4659 4660@Entry 4661@Component 4662struct WebComponent { 4663 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4664 4665 build() { 4666 Column() { 4667 Button('prefetchPopularPage') 4668 .onClick(() => { 4669 try { 4670 // Replace 'https://www.example.com' with a real URL for the API to work. 4671 this.controller.prefetchPage('https://www.example.com'); 4672 } catch (error) { 4673 let e:business_error.BusinessError = error as business_error.BusinessError; 4674 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4675 } 4676 }) 4677 // Replace ''www.example1.com' with a real URL for the API to work. 4678 Web({ src: 'www.example1.com', controller: this.controller }) 4679 } 4680 } 4681} 4682``` 4683 4684### prepareForPageLoad<sup>10+</sup> 4685 4686static prepareForPageLoad(url: string, preconnectable: boolean, numSockets: number): void 4687 4688Preconnects 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. 4689 4690**System capability**: SystemCapability.Web.Webview.Core 4691 4692**Parameters** 4693 4694| Name | Type | Mandatory | Description | 4695| ---------------| ------- | ---- | ------------- | 4696| url | string | Yes | URL to be preconnected.| 4697| 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.| 4698| numSockets | number | Yes | Number of sockets to be preconnected. The value must be greater than 0. A maximum of six socket connections are allowed.| 4699 4700**Error codes** 4701 4702For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4703 4704| ID | Error Message | 4705| -------- | ------------------------------------------------------------ | 4706| 17100002 | Invalid url. | 4707| 171000013| The number of preconnect sockets is invalid. | 4708 4709**Example** 4710 4711```ts 4712// xxx.ts 4713import UIAbility from '@ohos.app.ability.UIAbility'; 4714import web_webview from '@ohos.web.webview'; 4715import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 4716import Want from '@ohos.app.ability.Want'; 4717 4718export default class EntryAbility extends UIAbility { 4719 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 4720 console.log("EntryAbility onCreate") 4721 web_webview.WebviewController.initializeWebEngine() 4722 // Replace 'https://www.example.com' with a real URL for the API to work. 4723 web_webview.WebviewController.prepareForPageLoad("https://www.example.com", true, 2); 4724 AppStorage.setOrCreate("abilityWant", want) 4725 console.log("EntryAbility onCreate done") 4726 } 4727} 4728``` 4729 4730### setCustomUserAgent<sup>10+</sup> 4731 4732setCustomUserAgent(userAgent: string): void 4733 4734Sets a custom user agent, which will overwrite the default user agent. 4735 4736**System capability**: SystemCapability.Web.Webview.Core 4737 4738**Parameters** 4739 4740| Name | Type | Mandatory | Description | 4741| ---------------| ------- | ---- | ------------- | 4742| userAgent | string | Yes | Information about the custom user agent.| 4743 4744**Error codes** 4745 4746For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4747 4748| ID | Error Message | 4749| -------- | ------------------------------------------------------------ | 4750| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4751 4752**Example** 4753 4754```ts 4755// xxx.ets 4756import web_webview from '@ohos.web.webview' 4757import business_error from '@ohos.base' 4758 4759@Entry 4760@Component 4761struct WebComponent { 4762 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4763 @State customUserAgent: string = 'test' 4764 4765 build() { 4766 Column() { 4767 Button('setCustomUserAgent') 4768 .onClick(() => { 4769 try { 4770 let userAgent = this.controller.getUserAgent() + this.customUserAgent; 4771 this.controller.setCustomUserAgent(userAgent); 4772 } catch (error) { 4773 let e:business_error.BusinessError = error as business_error.BusinessError; 4774 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4775 } 4776 }) 4777 Web({ src: 'www.example.com', controller: this.controller }) 4778 } 4779 } 4780} 4781``` 4782 4783### setDownloadDelegate<sup>11+</sup> 4784 4785setDownloadDelegate(delegate: WebDownloadDelegate): void 4786 4787Sets a **WebDownloadDelegate** object for this **\<Web>** component. The delegate is used to receive the download and download progress triggered on the page. 4788 4789**System capability**: SystemCapability.Web.Webview.Core 4790 4791**Parameters** 4792 4793| Name | Type | Mandatory | Description | 4794| ---------------| ------- | ---- | ------------- | 4795| delegate | [WebDownloadDelegate](#webdownloaddelegate11) | Yes | Delegate used to receive the download progress.| 4796 4797**Error codes** 4798 4799For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4800 4801| ID | Error Message | 4802| -------- | ------------------------------------------------------------ | 4803| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4804 4805**Example** 4806 4807```ts 4808// xxx.ets 4809import web_webview from '@ohos.web.webview' 4810import business_error from '@ohos.base' 4811 4812@Entry 4813@Component 4814struct WebComponent { 4815 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4816 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 4817 4818 build() { 4819 Column() { 4820 Button('setDownloadDelegate') 4821 .onClick(() => { 4822 try { 4823 this.controller.setDownloadDelegate(this.delegate); 4824 } catch (error) { 4825 let e:business_error.BusinessError = error as business_error.BusinessError; 4826 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4827 } 4828 }) 4829 Web({ src: 'www.example.com', controller: this.controller }) 4830 } 4831 } 4832} 4833``` 4834 4835### startDownload<sup>11+</sup> 4836 4837startDownload(url: string): void 4838 4839. 4840 4841**System capability**: SystemCapability.Web.Webview.Core 4842 4843**Parameters** 4844 4845| Name | Type | Mandatory | Description | 4846| ---------------| ------- | ---- | ------------- | 4847| url | string | Yes | Download URL.| 4848 4849**Error codes** 4850 4851For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4852 4853| ID | Error Message | 4854| -------- | ------------------------------------------------------------ | 4855| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4856| 17100002 | Invalid url. | 4857 4858**Example** 4859 4860```ts 4861// xxx.ets 4862import web_webview from '@ohos.web.webview' 4863import business_error from '@ohos.base' 4864 4865@Entry 4866@Component 4867struct WebComponent { 4868 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4869 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 4870 4871 build() { 4872 Column() { 4873 Button('setDownloadDelegate') 4874 .onClick(() => { 4875 try { 4876 this.controller.setDownloadDelegate(this.delegate); 4877 } catch (error) { 4878 let e:business_error.BusinessError = error as business_error.BusinessError; 4879 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4880 } 4881 }) 4882 Button('startDownload') 4883 .onClick(() => { 4884 try { 4885 this.controller.startDownload('www.example.com'); 4886 } catch (error) { 4887 let e:business_error.BusinessError = error as business_error.BusinessError; 4888 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4889 } 4890 }) 4891 Web({ src: 'www.example.com', controller: this.controller }) 4892 } 4893 } 4894} 4895``` 4896 4897### getCustomUserAgent<sup>10+</sup> 4898 4899getCustomUserAgent(): string 4900 4901Obtains a custom user agent. 4902 4903**System capability**: SystemCapability.Web.Webview.Core 4904 4905**Return value** 4906 4907| Type | Description | 4908| ------ | ------------------------- | 4909| string | Information about the custom user agent.| 4910 4911**Error codes** 4912 4913For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 4914 4915| ID | Error Message | 4916| -------- | ------------------------------------------------------------ | 4917| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4918 4919**Example** 4920 4921```ts 4922// xxx.ets 4923import web_webview from '@ohos.web.webview' 4924import business_error from '@ohos.base' 4925 4926@Entry 4927@Component 4928struct WebComponent { 4929 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4930 @State userAgent: string = '' 4931 4932 build() { 4933 Column() { 4934 Button('getCustomUserAgent') 4935 .onClick(() => { 4936 try { 4937 this.userAgent = this.controller.getCustomUserAgent(); 4938 console.log("userAgent: " + this.userAgent); 4939 } catch (error) { 4940 let e:business_error.BusinessError = error as business_error.BusinessError; 4941 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4942 } 4943 }) 4944 Web({ src: 'www.example.com', controller: this.controller }) 4945 } 4946 } 4947} 4948``` 4949 4950### setConnectionTimeout<sup>11+</sup> 4951 4952static setConnectionTimeout(timeout: number): void 4953 4954Sets the network connection timeout. You can use the **onErrorReceive** method in the **\<Web>** component to obtain the timeout error code. 4955 4956**System capability**: SystemCapability.Web.Webview.Core 4957 4958**Parameters** 4959 4960| Name | Type | Mandatory | Description | 4961| ---------------| ------- | ---- | ------------- | 4962| timeout | number | Yes | Socket connection timeout, in seconds.| 4963 4964**Example** 4965 4966```ts 4967// xxx.ets 4968import web_webview from '@ohos.web.webview' 4969import business_error from '@ohos.base' 4970 4971@Entry 4972@Component 4973struct WebComponent { 4974 controller: web_webview.WebviewController = new web_webview.WebviewController(); 4975 4976 build() { 4977 Column() { 4978 Button('setConnectionTimeout') 4979 .onClick(() => { 4980 try { 4981 web_webview.WebviewController.setConnectionTimeout(5); 4982 console.log("setConnectionTimeout: 5s"); 4983 } catch (error) { 4984 let e:business_error.BusinessError = error as business_error.BusinessError; 4985 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 4986 } 4987 }) 4988 Web({ src: 'www.example.com', controller: this.controller }) 4989 .onErrorReceive((event) => { 4990 if (event) { 4991 console.log('getErrorInfo:' + event.error.getErrorInfo()) 4992 console.log('getErrorCode:' + event.error.getErrorCode()) 4993 } 4994 }) 4995 } 4996 } 4997} 4998``` 4999 5000 5001 5002### enableSafeBrowsing<sup>11+</sup> 5003 5004enableSafeBrowsing(enable: boolean): void 5005 5006Enables the safe browsing feature. This feature is forcibly enabled and cannot be disabled for identified untrusted websites. 5007 5008**System capability**: SystemCapability.Web.Webview.Core 5009 5010**Parameters** 5011 5012| Name | Type | Mandatory | Description | 5013| --------| ------- | ---- | ---------------------------| 5014| enable | boolean | Yes | Whether to enable the safe browsing feature.| 5015 5016**Error codes** 5017 5018For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5019 5020| ID| Error Message | 5021| -------- | ----------------------- | 5022| 401 | Invalid input parameter. | 5023 5024**Example** 5025 5026```ts 5027// xxx.ets 5028import web_webview from '@ohos.web.webview' 5029import business_error from '@ohos.base' 5030 5031@Entry 5032@Component 5033struct WebComponent { 5034 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5035 5036 build() { 5037 Column() { 5038 Button('enableSafeBrowsing') 5039 .onClick(() => { 5040 try { 5041 web_webview.WebviewController.enableSafeBrowsing(true); 5042 console.log("enableSafeBrowsing: true"); 5043 } catch (error) { 5044 let e:business_error.BusinessError = error as business_error.BusinessError; 5045 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5046 } 5047 }) 5048 Web({ src: 'www.example.com', controller: this.controller }) 5049 } 5050 } 5051} 5052``` 5053 5054### isSafeBrowsingEnabled<sup>11+</sup> 5055 5056isSafeBrowsingEnabled(): boolean 5057 5058Checks whether the safe browsing feature is enabled for this web page. 5059 5060**System capability**: SystemCapability.Web.Webview.Core 5061 5062**Return value** 5063 5064| Type | Description | 5065| ------- | --------------------------------------- | 5066| boolean | Whether the safe browsing feature is enabled. The default value is **false**.| 5067 5068**Example** 5069 5070```ts 5071// xxx.ets 5072import web_webview from '@ohos.web.webview' 5073 5074@Entry 5075@Component 5076struct WebComponent { 5077 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5078 5079 build() { 5080 Column() { 5081 Button('isSafeBrowsingEnabled') 5082 .onClick(() => { 5083 let result = web_webview.WebviewController.isSafeBrowsingEnabled(); 5084 console.log("result: " + result); 5085 }) 5086 Web({ src: 'www.example.com', controller: this.controller }) 5087 } 5088 } 5089} 5090``` 5091 5092### postUrl<sup>11+</sup> 5093 5094postUrl(url: string, postData: ArrayBuffer): void 5095 5096Loads the specified URL with **postData** using the POST method. If **url** is not a network URL, it will be loaded with [loadUrl](#loadurl) instead, and the **postData** parameter will be ignored. 5097 5098**System capability**: SystemCapability.Web.Webview.Core 5099 5100**Parameters** 5101 5102| Name | Type | Mandatory| Description | 5103| ------- | ---------------- | ---- | :-------------------- | 5104| url | string | Yes | URL to load. | 5105| postData | ArrayBuffer | Yes | Data to transfer using the POST method. The request must be encoded in "application/x-www-form-urlencoded" format.| 5106 5107**Error codes** 5108 5109For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5110 5111| ID| Error Message | 5112| -------- | ------------------------------------------------------------ | 5113| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5114| 17100002 | Invalid url. | 5115 5116**Example** 5117 5118```ts 5119// xxx.ets 5120import web_webview from '@ohos.web.webview' 5121import business_error from '@ohos.base' 5122 5123class TestObj { 5124 constructor() { 5125 } 5126 5127 test(str: string): ArrayBuffer { 5128 let buf = new ArrayBuffer(str.length); 5129 let buff = new Uint8Array(buf); 5130 5131 for (let i = 0; i < str.length; i++) { 5132 buff[i] = str.charCodeAt(i); 5133 } 5134 return buf; 5135 } 5136} 5137 5138@Entry 5139@Component 5140struct WebComponent { 5141 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5142 @State testObjtest: TestObj = new TestObj(); 5143 5144 build() { 5145 Column() { 5146 Button('postUrl') 5147 .onClick(() => { 5148 try { 5149 // Convert data to the ArrayBuffer type. 5150 let postData = this.testObjtest.test("Name=test&Password=test"); 5151 this.controller.postUrl('www.example.com', postData); 5152 } catch (error) { 5153 let e: business_error.BusinessError = error as business_error.BusinessError; 5154 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5155 } 5156 }) 5157 Web({ src: '', controller: this.controller }) 5158 } 5159 } 5160} 5161``` 5162 5163### createWebPrintDocumentAdapter<sup>11+</sup> 5164 5165createWebPrintDocumentAdapter(jobName: string): print.PrintDocumentAdapter 5166 5167Creates a **PrintDocumentAdapter** instance to provide content for printing. 5168 5169**System capability**: SystemCapability.Web.Webview.Core 5170 5171**Parameters** 5172 5173| Name | Type | Mandatory| Description | 5174| ------- | ------ | ---- | :-------------------- | 5175| jobName | string | Yes | Name of the file to print. | 5176 5177**Return value** 5178 5179| Type | Description | 5180| -------------------- | ------------------------- | 5181| print.printDocumentAdapter | **PrintDocumentAdapter** instance created.| 5182 5183**Error codes** 5184 5185For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5186 5187| ID| Error Message | 5188| -------- | -------------------------------------------------------------------------- | 5189| 401 | Invalid input parameter. | 5190| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5191 5192**Example** 5193 5194```ts 5195// xxx.ets 5196import web_webview from '@ohos.web.webview' 5197import business_error from '@ohos.base' 5198import print from '@ohos.print' 5199 5200@Entry 5201@Component 5202struct WebComponent { 5203 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5204 5205 build() { 5206 Column() { 5207 Button('createWebPrintDocumentAdapter') 5208 .onClick(() => { 5209 try { 5210 let webPrintDocadapter = this.controller.createWebPrintDocumentAdapter('example.pdf'); 5211 print.print('example_jobid', webPrintDocadapter, null, getContext()); 5212 } catch (error) { 5213 let e: business_error.BusinessError = error as business_error.BusinessError; 5214 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5215 } 5216 }) 5217 Web({ src: 'www.example.com', controller: this.controller }) 5218 } 5219 } 5220} 5221``` 5222### isIncognitoMode<sup>11+</sup> 5223 5224isIncognitoMode(): boolean 5225 5226Checks whether this Webview is in incognito mode. 5227 5228**System capability**: SystemCapability.Web.Webview.Core 5229 5230**Return value** 5231 5232| Type | Description | 5233| -------------------- | ------------------------- | 5234| boolean | Whether the Webview is in incognito mode.| 5235 5236**Error codes** 5237 5238For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5239 5240| ID| Error Message | 5241| -------- | -------------------------------------------------------------------------- | 5242| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5243 5244**Example** 5245 5246```ts 5247// xxx.ets 5248import web_webview from '@ohos.web.webview' 5249import business_error from '@ohos.base' 5250 5251@Entry 5252@Component 5253struct WebComponent { 5254 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5255 5256 build() { 5257 Column() { 5258 Button('isIncognitoMode') 5259 .onClick(() => { 5260 try { 5261 let result = this.controller.isIncognitoMode(); 5262 console.log('isIncognitoMode' + result); 5263 } catch (error) { 5264 let e: business_error.BusinessError = error as business_error.BusinessError; 5265 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5266 } 5267 }) 5268 Web({ src: 'www.example.com', controller: this.controller }) 5269 } 5270 } 5271} 5272``` 5273 5274### getSecurityLevel<sup>11+</sup> 5275 5276getSecurityLevel(): SecurityLevel 5277 5278Obtains the security level of this web page. 5279 5280**System capability**: SystemCapability.Web.Webview.Core 5281 5282**Return value** 5283 5284| Type | Description | 5285| ----------------------------------- | --------------------------- | 5286| [SecurityLevel](#securitylevel11) | Security level of the web page. The value can be **NONE**, **SECURE**, **WARNING**, or **DANGEROUS**.| 5287 5288**Error codes** 5289 5290For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5291 5292| ID| Error Message | 5293| -------- | ------------------------------------------------------------ | 5294| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5295 5296**Example** 5297 5298```ts 5299import webview from '@ohos.web.webview' 5300 5301 5302 5303@Entry 5304@Component 5305struct WebComponent { 5306 controller: webview.WebviewController = new webview.WebviewController() 5307 build() { 5308 Column() { 5309 Web({ src: 'www.example.com', controller: this.controller }) 5310 .onPageEnd((event) => { 5311 if (event) { 5312 let securityLevel = this.controller.getSecurityLevel() 5313 console.info('securityLevel: ', securityLevel) 5314 } 5315 }) 5316 } 5317 } 5318} 5319``` 5320 5321## WebCookieManager 5322 5323Implements a **WebCookieManager** instance to manage behavior of cookies in **\<Web>** components. All **\<Web>** components in an application share a **WebCookieManager** instance. 5324 5325> **NOTE** 5326> 5327> You must load the **\<Web>** component before calling APIs in **WebCookieManager**. 5328 5329### getCookie<sup>(deprecated)</sup> 5330 5331static getCookie(url: string): string 5332 5333Obtains the cookie corresponding to the specified URL. 5334 5335> **NOTE** 5336> 5337> This API is supported since API version 9 and deprecated since API version 11. You are advised to use [fetchCookieSync](###fetchCookieSync11) instead. 5338 5339**System capability**: SystemCapability.Web.Webview.Core 5340 5341**Parameters** 5342 5343| Name| Type | Mandatory| Description | 5344| ------ | ------ | ---- | :------------------------ | 5345| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 5346 5347**Return value** 5348 5349| Type | Description | 5350| ------ | ------------------------- | 5351| string | Cookie value corresponding to the specified URL.| 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| 17100002 | Invalid url. | 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 5373 build() { 5374 Column() { 5375 Button('getCookie') 5376 .onClick(() => { 5377 try { 5378 let value = web_webview.WebCookieManager.getCookie('https://www.example.com'); 5379 console.log("value: " + value); 5380 } catch (error) { 5381 let e:business_error.BusinessError = error as business_error.BusinessError; 5382 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5383 } 5384 }) 5385 Web({ src: 'www.example.com', controller: this.controller }) 5386 } 5387 } 5388} 5389``` 5390 5391### fetchCookieSync<sup>11+</sup> 5392 5393static fetchCookieSync(url: string, incognito?: boolean): string 5394 5395Obtains the cookie corresponding to the specified URL. 5396 5397**System capability**: SystemCapability.Web.Webview.Core 5398 5399**Parameters** 5400 5401| Name| Type | Mandatory| Description | 5402| ------ | ------ | ---- | :------------------------ | 5403| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 5404| incognito | boolean | No | Whether to obtain the cookie in incognito mode. The value **true** means to obtain the cookie in incognito mode, and **false** means the opposite.| 5405 5406**Return value** 5407 5408| Type | Description | 5409| ------ | ------------------------- | 5410| string | Cookie value corresponding to the specified URL.| 5411 5412**Error codes** 5413 5414For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5415 5416| ID| Error Message | 5417| -------- | ------------------------------------------------------ | 5418| 17100002 | Invalid url. | 5419 5420**Example** 5421 5422```ts 5423// xxx.ets 5424import web_webview from '@ohos.web.webview' 5425import business_error from '@ohos.base' 5426 5427@Entry 5428@Component 5429struct WebComponent { 5430 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5431 5432 build() { 5433 Column() { 5434 Button('fetchCookieSync') 5435 .onClick(() => { 5436 try { 5437 let value = web_webview.WebCookieManager.fetchCookieSync('https://www.example.com'); 5438 console.log("fetchCookieSync cookie = " + value); 5439 } catch (error) { 5440 let e:business_error.BusinessError = error as business_error.BusinessError; 5441 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5442 } 5443 }) 5444 Web({ src: 'www.example.com', controller: this.controller }) 5445 } 5446 } 5447} 5448``` 5449 5450### fetchCookie<sup>11+</sup> 5451 5452static fetchCookie(url: string, callback: AsyncCallback\<string>): void 5453 5454Obtains the cookie value of a specified URL. This API uses an asynchronous callback to return the result. 5455 5456**System capability**: SystemCapability.Web.Webview.Core 5457 5458**Parameters** 5459 5460| Name| Type | Mandatory| Description | 5461| ------ | ------ | ---- | :------------------------ | 5462| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 5463| callback | AsyncCallback\<string> | Yes| Callback used to return the result.| 5464 5465**Error codes** 5466 5467For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5468 5469| ID| Error Message | 5470| -------- | ------------------------------------------------------ | 5471| 401 | Invalid input parameter. | 5472| 17100002 | Invalid url. | 5473 5474**Example** 5475 5476```ts 5477// xxx.ets 5478import web_webview from '@ohos.web.webview' 5479import business_error from '@ohos.base' 5480 5481@Entry 5482@Component 5483struct WebComponent { 5484 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5485 5486 build() { 5487 Column() { 5488 Button('fetchCookie') 5489 .onClick(() => { 5490 try { 5491 web_webview.WebCookieManager.fetchCookie('https://www.example.com', (error, cookie) => { 5492 if (error) { 5493 console.log('error: ' + JSON.stringify(error)); 5494 return; 5495 } 5496 if (cookie) { 5497 console.log('fetchCookie cookie = ' + cookie); 5498 } 5499 }) 5500 } catch (error) { 5501 let e:business_error.BusinessError = error as business_error.BusinessError; 5502 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5503 } 5504 }) 5505 Web({ src: 'www.example.com', controller: this.controller }) 5506 } 5507 } 5508} 5509``` 5510 5511### fetchCookie<sup>11+</sup> 5512 5513static fetchCookie(url: string): Promise\<string> 5514 5515Obtains the cookie value of a specified URL. This API uses a promise to return the result. 5516 5517**System capability**: SystemCapability.Web.Webview.Core 5518 5519**Parameters** 5520 5521| Name| Type | Mandatory| Description | 5522| ------ | ------ | ---- | :------------------------ | 5523| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 5524 5525**Return value** 5526 5527| Type | Description | 5528| ------ | ------------------------- | 5529| Promise\<string> | Promise used to return the result.| 5530 5531**Error codes** 5532 5533For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5534 5535| ID| Error Message | 5536| -------- | ------------------------------------------------------ | 5537| 401 | Invalid input parameter. | 5538| 17100002 | Invalid url. | 5539 5540**Example** 5541 5542```ts 5543// xxx.ets 5544import web_webview from '@ohos.web.webview' 5545import business_error from '@ohos.base' 5546 5547@Entry 5548@Component 5549struct WebComponent { 5550 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5551 5552 build() { 5553 Column() { 5554 Button('fetchCookie') 5555 .onClick(() => { 5556 try { 5557 web_webview.WebCookieManager.fetchCookie('https://www.example.com') 5558 .then(cookie => { 5559 console.log("fetchCookie cookie = " + cookie); 5560 }) 5561 .catch((error:business_error.BusinessError) => { 5562 console.log('error: ' + JSON.stringify(error)); 5563 }) 5564 } catch (error) { 5565 let e:business_error.BusinessError = error as business_error.BusinessError; 5566 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5567 } 5568 }) 5569 Web({ src: 'www.example.com', controller: this.controller }) 5570 } 5571 } 5572} 5573``` 5574 5575 5576### setCookie<sup>(deprecated)</sup> 5577 5578static setCookie(url: string, value: string): void 5579 5580Sets a cookie for the specified URL. 5581 5582> **NOTE** 5583> 5584> This API is supported since API version 9 and deprecated since API version 11. You are advised to use [configCookieSync<sup>11+</sup>](#configcookiesync11) instead. 5585 5586**System capability**: SystemCapability.Web.Webview.Core 5587 5588**Parameters** 5589 5590| Name| Type | Mandatory| Description | 5591| ------ | ------ | ---- | :------------------------ | 5592| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 5593| value | string | Yes | Cookie value to set. | 5594 5595**Error codes** 5596 5597For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5598 5599| ID| Error Message | 5600| -------- | ------------------------------------------------------ | 5601| 17100002 | Invalid url. | 5602| 17100005 | Invalid cookie value. | 5603 5604**Example** 5605 5606```ts 5607// xxx.ets 5608import web_webview from '@ohos.web.webview' 5609import business_error from '@ohos.base' 5610 5611@Entry 5612@Component 5613struct WebComponent { 5614 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5615 5616 build() { 5617 Column() { 5618 Button('setCookie') 5619 .onClick(() => { 5620 try { 5621 web_webview.WebCookieManager.setCookie('https://www.example.com', 'a=b'); 5622 } catch (error) { 5623 let e:business_error.BusinessError = error as business_error.BusinessError; 5624 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5625 } 5626 }) 5627 Web({ src: 'www.example.com', controller: this.controller }) 5628 } 5629 } 5630} 5631``` 5632 5633### configCookieSync<sup>11+</sup> 5634 5635static configCookieSync(url: string, value: string, incognito?: boolean): void 5636 5637Sets a cookie for the specified URL. 5638 5639**System capability**: SystemCapability.Web.Webview.Core 5640 5641**Parameters** 5642 5643| Name| Type | Mandatory| Description | 5644| ------ | ------ | ---- | :------------------------ | 5645| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 5646| value | string | Yes | Cookie value to set. | 5647| incognito | boolean | No | Whether to obtain the cookie in incognito mode. The value **true** means to obtain the cookie in incognito mode, and **false** means the opposite.| 5648 5649**Error codes** 5650 5651For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5652 5653| ID| Error Message | 5654| -------- | ------------------------------------------------------ | 5655| 17100002 | Invalid url. | 5656| 17100005 | Invalid cookie value. | 5657 5658**Example** 5659 5660```ts 5661// xxx.ets 5662import web_webview from '@ohos.web.webview' 5663import business_error from '@ohos.base' 5664 5665@Entry 5666@Component 5667struct WebComponent { 5668 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5669 5670 build() { 5671 Column() { 5672 Button('configCookieSync') 5673 .onClick(() => { 5674 try { 5675 web_webview.WebCookieManager.configCookieSync('https://www.example.com', 'a=b'); 5676 } catch (error) { 5677 let e:business_error.BusinessError = error as business_error.BusinessError; 5678 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5679 } 5680 }) 5681 Web({ src: 'www.example.com', controller: this.controller }) 5682 } 5683 } 5684} 5685``` 5686 5687### configCookie<sup>11+</sup> 5688 5689static configCookie(url: string, value: string, callback: AsyncCallback\<void>): void 5690 5691Sets the value of a single cookie for a specified URL. This API uses an asynchronous callback to return the result. 5692 5693**System capability**: SystemCapability.Web.Webview.Core 5694 5695**Parameters** 5696 5697| Name| Type | Mandatory| Description | 5698| ------ | ------ | ---- | :------------------------ | 5699| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 5700| value | string | Yes | Cookie value to set. | 5701| callback | AsyncCallback\<void> | Yes| Callback used to return the result.| 5702 5703**Error codes** 5704 5705For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5706 5707| ID| Error Message | 5708| -------- | ------------------------------------------------------ | 5709| 401 | Invalid input parameter. | 5710| 17100002 | Invalid url. | 5711| 17100005 | Invalid cookie value. | 5712 5713**Example** 5714 5715```ts 5716// xxx.ets 5717import web_webview from '@ohos.web.webview' 5718import business_error from '@ohos.base' 5719 5720@Entry 5721@Component 5722struct WebComponent { 5723 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5724 5725 build() { 5726 Column() { 5727 Button('configCookie') 5728 .onClick(() => { 5729 try { 5730 web_webview.WebCookieManager.configCookie('https://www.example.com', "a=b", (error) => { 5731 if (error) { 5732 console.log("error: " + JSON.stringify(error)); 5733 } 5734 }) 5735 } catch (error) { 5736 let e:business_error.BusinessError = error as business_error.BusinessError; 5737 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5738 } 5739 }) 5740 Web({ src: 'www.example.com', controller: this.controller }) 5741 } 5742 } 5743} 5744``` 5745 5746### configCookie<sup>11+</sup> 5747 5748static configCookie(url: string, value: string): Promise\<void> 5749 5750Sets the value of a single cookie for a specified URL. This API uses a promise to return the result. 5751 5752**System capability**: SystemCapability.Web.Webview.Core 5753 5754**Parameters** 5755 5756| Name| Type | Mandatory| Description | 5757| ------ | ------ | ---- | :------------------------ | 5758| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 5759| value | string | Yes | Cookie value to set. | 5760 5761**Return value** 5762 5763| Type | Description | 5764| ------ | ------------------------- | 5765| Promise\<void> | Promise used to return the result.| 5766 5767**Error codes** 5768 5769For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 5770 5771| ID| Error Message | 5772| -------- | ------------------------------------------------------ | 5773| 401 | Invalid input parameter. | 5774| 17100002 | Invalid url. | 5775| 17100005 | Invalid cookie value. | 5776 5777**Example** 5778 5779```ts 5780// xxx.ets 5781import web_webview from '@ohos.web.webview' 5782import business_error from '@ohos.base' 5783 5784@Entry 5785@Component 5786struct WebComponent { 5787 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5788 5789 build() { 5790 Column() { 5791 Button('configCookie') 5792 .onClick(() => { 5793 try { 5794 web_webview.WebCookieManager.configCookie('https://www.example.com', 'a=b') 5795 .then(() => { 5796 console.log('configCookie success!'); 5797 }) 5798 .catch((error:business_error.BusinessError) => { 5799 console.log('error: ' + JSON.stringify(error)); 5800 }) 5801 } catch (error) { 5802 let e:business_error.BusinessError = error as business_error.BusinessError; 5803 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5804 } 5805 }) 5806 Web({ src: 'www.example.com', controller: this.controller }) 5807 } 5808 } 5809} 5810``` 5811 5812### saveCookieAsync 5813 5814static saveCookieAsync(callback: AsyncCallback\<void>): void 5815 5816Saves the cookies in the memory to the drive. This API uses an asynchronous callback to return the result. 5817 5818**System capability**: SystemCapability.Web.Webview.Core 5819 5820**Parameters** 5821 5822| Name | Type | Mandatory| Description | 5823| -------- | ---------------------- | ---- | :------------------------------------------------- | 5824| callback | AsyncCallback\<void> | Yes | Callback used to return whether the cookies are successfully saved.| 5825 5826**Example** 5827 5828```ts 5829// xxx.ets 5830import web_webview from '@ohos.web.webview' 5831import business_error from '@ohos.base' 5832 5833@Entry 5834@Component 5835struct WebComponent { 5836 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5837 5838 build() { 5839 Column() { 5840 Button('saveCookieAsync') 5841 .onClick(() => { 5842 try { 5843 web_webview.WebCookieManager.saveCookieAsync((error) => { 5844 if (error) { 5845 console.log("error: " + error); 5846 } 5847 }) 5848 } catch (error) { 5849 let e:business_error.BusinessError = error as business_error.BusinessError; 5850 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5851 } 5852 }) 5853 Web({ src: 'www.example.com', controller: this.controller }) 5854 } 5855 } 5856} 5857``` 5858 5859### saveCookieAsync 5860 5861static saveCookieAsync(): Promise\<void> 5862 5863Saves the cookies in the memory to the drive. This API uses a promise to return the result. 5864 5865**System capability**: SystemCapability.Web.Webview.Core 5866 5867**Return value** 5868 5869| Type | Description | 5870| ---------------- | ----------------------------------------- | 5871| Promise\<void> | Promise used to return the operation result.| 5872 5873**Example** 5874 5875```ts 5876// xxx.ets 5877import web_webview from '@ohos.web.webview' 5878import business_error from '@ohos.base' 5879 5880@Entry 5881@Component 5882struct WebComponent { 5883 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5884 5885 build() { 5886 Column() { 5887 Button('saveCookieAsync') 5888 .onClick(() => { 5889 try { 5890 web_webview.WebCookieManager.saveCookieAsync() 5891 .then(() => { 5892 console.log("saveCookieAsyncCallback success!"); 5893 }) 5894 .catch((error:business_error.BusinessError) => { 5895 console.error("error: " + error); 5896 }); 5897 } catch (error) { 5898 let e:business_error.BusinessError = error as business_error.BusinessError; 5899 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5900 } 5901 }) 5902 Web({ src: 'www.example.com', controller: this.controller }) 5903 } 5904 } 5905} 5906``` 5907 5908### putAcceptCookieEnabled 5909 5910static putAcceptCookieEnabled(accept: boolean): void 5911 5912Sets whether the **WebCookieManager** instance has the permission to send and receive cookies. 5913 5914**System capability**: SystemCapability.Web.Webview.Core 5915 5916**Parameters** 5917 5918| Name| Type | Mandatory| Description | 5919| ------ | ------- | ---- | :----------------------------------- | 5920| accept | boolean | Yes | Whether the **WebCookieManager** instance has the permission to send and receive cookies.<br>Default value: **true**| 5921 5922**Example** 5923 5924```ts 5925// xxx.ets 5926import web_webview from '@ohos.web.webview' 5927import business_error from '@ohos.base' 5928 5929@Entry 5930@Component 5931struct WebComponent { 5932 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5933 5934 build() { 5935 Column() { 5936 Button('putAcceptCookieEnabled') 5937 .onClick(() => { 5938 try { 5939 web_webview.WebCookieManager.putAcceptCookieEnabled(false); 5940 } catch (error) { 5941 let e:business_error.BusinessError = error as business_error.BusinessError; 5942 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 5943 } 5944 }) 5945 Web({ src: 'www.example.com', controller: this.controller }) 5946 } 5947 } 5948} 5949``` 5950 5951### isCookieAllowed 5952 5953static isCookieAllowed(): boolean 5954 5955Checks whether the **WebCookieManager** instance has the permission to send and receive cookies. 5956 5957**System capability**: SystemCapability.Web.Webview.Core 5958 5959**Return value** 5960 5961| Type | Description | 5962| ------- | -------------------------------- | 5963| boolean | Whether the **WebCookieManager** instance has the permission to send and receive cookies. The default value is **true**.| 5964 5965**Example** 5966 5967```ts 5968// xxx.ets 5969import web_webview from '@ohos.web.webview' 5970 5971@Entry 5972@Component 5973struct WebComponent { 5974 controller: web_webview.WebviewController = new web_webview.WebviewController(); 5975 5976 build() { 5977 Column() { 5978 Button('isCookieAllowed') 5979 .onClick(() => { 5980 let result = web_webview.WebCookieManager.isCookieAllowed(); 5981 console.log("result: " + result); 5982 }) 5983 Web({ src: 'www.example.com', controller: this.controller }) 5984 } 5985 } 5986} 5987``` 5988 5989### putAcceptThirdPartyCookieEnabled 5990 5991static putAcceptThirdPartyCookieEnabled(accept: boolean): void 5992 5993Sets whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. 5994 5995**System capability**: SystemCapability.Web.Webview.Core 5996 5997**Parameters** 5998 5999| Name| Type | Mandatory| Description | 6000| ------ | ------- | ---- | :----------------------------------------- | 6001| accept | boolean | Yes | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies.<br>Default value: **false**| 6002 6003**Example** 6004 6005```ts 6006// xxx.ets 6007import web_webview from '@ohos.web.webview' 6008import business_error from '@ohos.base' 6009 6010@Entry 6011@Component 6012struct WebComponent { 6013 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6014 6015 build() { 6016 Column() { 6017 Button('putAcceptThirdPartyCookieEnabled') 6018 .onClick(() => { 6019 try { 6020 web_webview.WebCookieManager.putAcceptThirdPartyCookieEnabled(false); 6021 } catch (error) { 6022 let e:business_error.BusinessError = error as business_error.BusinessError; 6023 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 6024 } 6025 }) 6026 Web({ src: 'www.example.com', controller: this.controller }) 6027 } 6028 } 6029} 6030``` 6031 6032### isThirdPartyCookieAllowed 6033 6034static isThirdPartyCookieAllowed(): boolean 6035 6036Checks whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. 6037 6038**System capability**: SystemCapability.Web.Webview.Core 6039 6040**Return value** 6041 6042| Type | Description | 6043| ------- | -------------------------------------- | 6044| boolean | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. The default value is **false**.| 6045 6046**Example** 6047 6048```ts 6049// xxx.ets 6050import web_webview from '@ohos.web.webview' 6051 6052@Entry 6053@Component 6054struct WebComponent { 6055 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6056 6057 build() { 6058 Column() { 6059 Button('isThirdPartyCookieAllowed') 6060 .onClick(() => { 6061 let result = web_webview.WebCookieManager.isThirdPartyCookieAllowed(); 6062 console.log("result: " + result); 6063 }) 6064 Web({ src: 'www.example.com', controller: this.controller }) 6065 } 6066 } 6067} 6068``` 6069 6070### existCookie 6071 6072static existCookie(incognito?: boolean): boolean 6073 6074Checks whether cookies exist. 6075 6076**System capability**: SystemCapability.Web.Webview.Core 6077 6078**Parameters** 6079 6080| Name| Type | Mandatory| Description | 6081| ------ | ------- | ---- | :----------------------------------------- | 6082| incognito<sup>11+</sup> | boolean | No | Whether to check for cookies in incognito mode. The value **true** means to check for cookies in incognito mode, and **false** means the opposite.| 6083 6084**Return value** 6085 6086| Type | Description | 6087| ------- | -------------------------------------- | 6088| boolean | Whether cookies exist. The value **true** means that cookies exist, and **false** means the opposite.| 6089 6090**Example** 6091 6092```ts 6093// xxx.ets 6094import web_webview from '@ohos.web.webview' 6095 6096@Entry 6097@Component 6098struct WebComponent { 6099 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6100 6101 build() { 6102 Column() { 6103 Button('existCookie') 6104 .onClick(() => { 6105 let result = web_webview.WebCookieManager.existCookie(); 6106 console.log("result: " + result); 6107 }) 6108 Web({ src: 'www.example.com', controller: this.controller }) 6109 } 6110 } 6111} 6112``` 6113 6114### deleteEntireCookie<sup>(deprecated)</sup> 6115 6116static deleteEntireCookie(): void 6117 6118Deletes all cookies. 6119 6120> **NOTE** 6121> 6122> This API is supported since API version 9 and deprecated since API version 11. You are advised to use [clearAllCookiesSync](#clearallcookiessync11) instead. 6123 6124**System capability**: SystemCapability.Web.Webview.Core 6125 6126**Example** 6127 6128```ts 6129// xxx.ets 6130import web_webview from '@ohos.web.webview' 6131 6132@Entry 6133@Component 6134struct WebComponent { 6135 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6136 6137 build() { 6138 Column() { 6139 Button('deleteEntireCookie') 6140 .onClick(() => { 6141 web_webview.WebCookieManager.deleteEntireCookie(); 6142 }) 6143 Web({ src: 'www.example.com', controller: this.controller }) 6144 } 6145 } 6146} 6147``` 6148 6149### clearAllCookiesSync<sup>11+</sup> 6150 6151static clearAllCookiesSync(incognito?: boolean): void 6152 6153Deletes all cookies. 6154 6155**System capability**: SystemCapability.Web.Webview.Core 6156 6157**Parameters** 6158 6159| Name| Type | Mandatory| Description | 6160| ------ | ------- | ---- | :----------------------------------------- | 6161| incognito | boolean | No | Whether to delete all cookies in incognito mode. The value **true** means to delete all cookies in incognito mode, and **false** means the opposite.| 6162 6163**Example** 6164 6165```ts 6166// xxx.ets 6167import web_webview from '@ohos.web.webview' 6168 6169@Entry 6170@Component 6171struct WebComponent { 6172 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6173 6174 build() { 6175 Column() { 6176 Button('clearAllCookiesSync') 6177 .onClick(() => { 6178 web_webview.WebCookieManager.clearAllCookiesSync(); 6179 }) 6180 Web({ src: 'www.example.com', controller: this.controller }) 6181 } 6182 } 6183} 6184``` 6185 6186### clearAllCookies<sup>11+</sup> 6187 6188static clearAllCookies(callback: AsyncCallback\<void>): void 6189 6190Clears all cookies. This API uses an asynchronous callback to return the result. 6191 6192**System capability**: SystemCapability.Web.Webview.Core 6193 6194**Parameters** 6195 6196| Name | Type | Mandatory| Description | 6197| -------- | ---------------------- | ---- | :------------------------------------------------- | 6198| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 6199 6200**Example** 6201 6202```ts 6203// xxx.ets 6204import web_webview from '@ohos.web.webview' 6205import business_error from '@ohos.base' 6206 6207@Entry 6208@Component 6209struct WebComponent { 6210 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6211 6212 build() { 6213 Column() { 6214 Button('clearAllCookies') 6215 .onClick(() => { 6216 try { 6217 web_webview.WebCookieManager.clearAllCookies((error) => { 6218 if (error) { 6219 console.log("error: " + error); 6220 } 6221 }) 6222 } catch (error) { 6223 let e:business_error.BusinessError = error as business_error.BusinessError; 6224 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 6225 } 6226 }) 6227 Web({ src: 'www.example.com', controller: this.controller }) 6228 } 6229 } 6230} 6231``` 6232 6233### clearAllCookies<sup>11+</sup> 6234 6235static clearAllCookies(): Promise\<void> 6236 6237Clears all cookies. This API uses a promise to return the result. 6238 6239**System capability**: SystemCapability.Web.Webview.Core 6240 6241**Return value** 6242 6243| Type | Description | 6244| ---------------- | ----------------------------------------- | 6245| Promise\<void> | Promise used to return the result.| 6246 6247**Example** 6248 6249```ts 6250// xxx.ets 6251import web_webview from '@ohos.web.webview' 6252import business_error from '@ohos.base' 6253 6254@Entry 6255@Component 6256struct WebComponent { 6257 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6258 6259 build() { 6260 Column() { 6261 Button('clearAllCookies') 6262 .onClick(() => { 6263 try { 6264 web_webview.WebCookieManager.clearAllCookies() 6265 .then(() => { 6266 console.log("clearAllCookies success!"); 6267 }) 6268 .catch((error:business_error.BusinessError) => { 6269 console.error("error: " + error); 6270 }); 6271 } catch (error) { 6272 let e:business_error.BusinessError = error as business_error.BusinessError; 6273 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 6274 } 6275 }) 6276 Web({ src: 'www.example.com', controller: this.controller }) 6277 } 6278 } 6279} 6280``` 6281 6282### deleteSessionCookie<sup>(deprecated)</sup> 6283 6284static deleteSessionCookie(): void 6285 6286Deletes all session cookies. 6287 6288> **NOTE** 6289> 6290> This API is supported since API version 9 and deprecated since API version 11. You are advised to use [clearSessionCookiesync](#clearsessioncookiesync11) instead. 6291 6292**System capability**: SystemCapability.Web.Webview.Core 6293 6294**Example** 6295 6296```ts 6297// xxx.ets 6298import web_webview from '@ohos.web.webview' 6299 6300@Entry 6301@Component 6302struct WebComponent { 6303 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6304 6305 build() { 6306 Column() { 6307 Button('deleteSessionCookie') 6308 .onClick(() => { 6309 web_webview.WebCookieManager.deleteSessionCookie(); 6310 }) 6311 Web({ src: 'www.example.com', controller: this.controller }) 6312 } 6313 } 6314} 6315``` 6316 6317### clearSessionCookieSync<sup>11+</sup> 6318 6319static clearSessionCookieSync(): void 6320 6321Deletes all session cookies. 6322 6323**System capability**: SystemCapability.Web.Webview.Core 6324 6325**Example** 6326 6327```ts 6328// xxx.ets 6329import web_webview from '@ohos.web.webview' 6330 6331@Entry 6332@Component 6333struct WebComponent { 6334 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6335 6336 build() { 6337 Column() { 6338 Button('clearSessionCookieSync') 6339 .onClick(() => { 6340 web_webview.WebCookieManager.clearSessionCookieSync(); 6341 }) 6342 Web({ src: 'www.example.com', controller: this.controller }) 6343 } 6344 } 6345} 6346``` 6347 6348### clearSessionCookie<sup>11+</sup> 6349 6350static clearSessionCookie(callback: AsyncCallback\<void>): void 6351 6352Clears all session cookies. This API uses an asynchronous callback to return the result. 6353 6354**System capability**: SystemCapability.Web.Webview.Core 6355 6356**Parameters** 6357 6358| Name | Type | Mandatory| Description | 6359| -------- | ---------------------- | ---- | :------------------------------------------------- | 6360| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 6361 6362**Example** 6363 6364```ts 6365// xxx.ets 6366import web_webview from '@ohos.web.webview' 6367import business_error from '@ohos.base' 6368 6369@Entry 6370@Component 6371struct WebComponent { 6372 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6373 6374 build() { 6375 Column() { 6376 Button('clearSessionCookie') 6377 .onClick(() => { 6378 try { 6379 web_webview.WebCookieManager.clearSessionCookie((error) => { 6380 if (error) { 6381 console.log("error: " + error); 6382 } 6383 }) 6384 } catch (error) { 6385 let e:business_error.BusinessError = error as business_error.BusinessError; 6386 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 6387 } 6388 }) 6389 Web({ src: 'www.example.com', controller: this.controller }) 6390 } 6391 } 6392} 6393``` 6394 6395### clearSessionCookie<sup>11+</sup> 6396 6397static clearSessionCookie(): Promise\<void> 6398 6399Clears all session cookies. This API uses a promise to return the result. 6400 6401**System capability**: SystemCapability.Web.Webview.Core 6402 6403**Return value** 6404 6405| Type | Description | 6406| ---------------- | ----------------------------------------- | 6407| Promise\<void> | Promise used to return the result.| 6408 6409**Example** 6410 6411```ts 6412// xxx.ets 6413import web_webview from '@ohos.web.webview' 6414import business_error from '@ohos.base' 6415 6416@Entry 6417@Component 6418struct WebComponent { 6419 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6420 6421 build() { 6422 Column() { 6423 Button('clearSessionCookie') 6424 .onClick(() => { 6425 try { 6426 web_webview.WebCookieManager.clearSessionCookie() 6427 .then(() => { 6428 console.log("clearSessionCookie success!"); 6429 }) 6430 .catch((error:business_error.BusinessError) => { 6431 console.error("error: " + error); 6432 }); 6433 } catch (error) { 6434 let e:business_error.BusinessError = error as business_error.BusinessError; 6435 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 6436 } 6437 }) 6438 Web({ src: 'www.example.com', controller: this.controller }) 6439 } 6440 } 6441} 6442``` 6443 6444## WebStorage 6445 6446Implements a **WebStorage** object to manage the Web SQL database and HTML5 Web Storage APIs. All **\<Web>** components in an application share a **WebStorage** object. 6447 6448> **NOTE** 6449> 6450> You must load the **\<Web>** component before calling the APIs in **WebStorage**. 6451 6452### deleteOrigin 6453 6454static deleteOrigin(origin: string): void 6455 6456Deletes all data in the specified origin. 6457 6458**System capability**: SystemCapability.Web.Webview.Core 6459 6460**Parameters** 6461 6462| Name| Type | Mandatory| Description | 6463| ------ | ------ | ---- | ------------------------ | 6464| origin | string | Yes | Index of the origin, which is obtained through [getOrigins](#getorigins).| 6465 6466**Error codes** 6467 6468For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 6469 6470| ID| Error Message | 6471| -------- | ------------------------------------------------------ | 6472| 17100011 | Invalid origin. | 6473 6474**Example** 6475 6476```ts 6477// xxx.ets 6478import web_webview from '@ohos.web.webview'; 6479import business_error from '@ohos.base'; 6480 6481@Entry 6482@Component 6483struct WebComponent { 6484 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6485 origin: string = "resource://rawfile/"; 6486 6487 build() { 6488 Column() { 6489 Button('deleteOrigin') 6490 .onClick(() => { 6491 try { 6492 web_webview.WebStorage.deleteOrigin(this.origin); 6493 } catch (error) { 6494 let e: business_error.BusinessError = error as business_error.BusinessError; 6495 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 6496 } 6497 6498 }) 6499 Web({ src: $rawfile('index.html'), controller: this.controller }) 6500 .databaseAccess(true) 6501 } 6502 } 6503} 6504``` 6505 6506HTML file to be loaded: 6507 ```html 6508 <!-- index.html --> 6509 <!DOCTYPE html> 6510 <html> 6511 <head> 6512 <meta charset="UTF-8"> 6513 <title>test</title> 6514 <script type="text/javascript"> 6515 6516 var db = openDatabase('mydb','1.0','Test DB',2 * 1024 * 1024); 6517 var msg; 6518 6519 db.transaction(function(tx){ 6520 tx.executeSql('INSERT INTO LOGS (id,log) VALUES(1,"test1")'); 6521 tx.executeSql('INSERT INTO LOGS (id,log) VALUES(2,"test2")'); 6522 msg = '<p>Data table created, with two data records inserted.</p>'; 6523 6524 document.querySelector('#status').innerHTML = msg; 6525 }); 6526 6527 db.transaction(function(tx){ 6528 tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) { 6529 var len = results.rows.length,i; 6530 msg = "<p>Number of records: " + len + "</p>"; 6531 6532 document.querySelector('#status').innerHTML += msg; 6533 6534 for(i = 0; i < len; i++){ 6535 msg = "<p><b>" + results.rows.item(i).log + "</b></p>"; 6536 6537 document.querySelector('#status').innerHTML += msg; 6538 } 6539 },null); 6540 }); 6541 6542 </script> 6543 </head> 6544 <body> 6545 <div id="status" name="status">Status</div> 6546 </body> 6547 </html> 6548 ``` 6549 6550### getOrigins 6551 6552static getOrigins(callback: AsyncCallback\<Array\<WebStorageOrigin>>): void 6553 6554Obtains information about all origins that are currently using the Web SQL Database. This API uses an asynchronous callback to return the result. 6555 6556**System capability**: SystemCapability.Web.Webview.Core 6557 6558**Parameters** 6559 6560| Name | Type | Mandatory| Description | 6561| -------- | -------------------------------------- | ---- | ------------------------------------------------------ | 6562| callback | AsyncCallback\<Array\<[WebStorageOrigin](#webstorageorigin)>> | Yes | Callback used to return the information about the origins. For details, see [WebStorageOrigin](#webstorageorigin).| 6563 6564**Error codes** 6565 6566For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 6567 6568| ID| Error Message | 6569| -------- | ------------------------------------------------------ | 6570| 17100012 | Invalid web storage origin. | 6571 6572**Example** 6573 6574```ts 6575// xxx.ets 6576import web_webview from '@ohos.web.webview'; 6577import business_error from '@ohos.base'; 6578 6579@Entry 6580@Component 6581struct WebComponent { 6582 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6583 6584 build() { 6585 Column() { 6586 Button('getOrigins') 6587 .onClick(() => { 6588 try { 6589 web_webview.WebStorage.getOrigins((error, origins) => { 6590 if (error) { 6591 console.log('error: ' + JSON.stringify(error)); 6592 return; 6593 } 6594 for (let i = 0; i < origins.length; i++) { 6595 console.log('origin: ' + origins[i].origin); 6596 console.log('usage: ' + origins[i].usage); 6597 console.log('quota: ' + origins[i].quota); 6598 } 6599 }) 6600 } catch (error) { 6601 let e: business_error.BusinessError = error as business_error.BusinessError; 6602 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 6603 } 6604 6605 }) 6606 Web({ src: $rawfile('index.html'), controller: this.controller }) 6607 .databaseAccess(true) 6608 } 6609 } 6610} 6611``` 6612 6613For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 6614 6615### getOrigins 6616 6617static getOrigins(): Promise\<Array\<WebStorageOrigin>> 6618 6619Obtains information about all origins that are currently using the Web SQL Database. This API uses a promise to return the result. 6620 6621**System capability**: SystemCapability.Web.Webview.Core 6622 6623**Return value** 6624 6625| Type | Description | 6626| -------------------------------- | ------------------------------------------------------------ | 6627| Promise\<Array\<[WebStorageOrigin](#webstorageorigin)>> | Promise used to return the information about the origins. For details, see [WebStorageOrigin](#webstorageorigin).| 6628 6629**Error codes** 6630 6631For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 6632 6633| ID| Error Message | 6634| -------- | ------------------------------------------------------ | 6635| 17100012 | Invalid web storage origin. | 6636 6637**Example** 6638 6639```ts 6640// xxx.ets 6641import web_webview from '@ohos.web.webview'; 6642import business_error from '@ohos.base'; 6643 6644@Entry 6645@Component 6646struct WebComponent { 6647 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6648 6649 build() { 6650 Column() { 6651 Button('getOrigins') 6652 .onClick(() => { 6653 try { 6654 web_webview.WebStorage.getOrigins() 6655 .then(origins => { 6656 for (let i = 0; i < origins.length; i++) { 6657 console.log('origin: ' + origins[i].origin); 6658 console.log('usage: ' + origins[i].usage); 6659 console.log('quota: ' + origins[i].quota); 6660 } 6661 }) 6662 .catch((e : business_error.BusinessError) => { 6663 console.log('error: ' + JSON.stringify(e)); 6664 }) 6665 } catch (error) { 6666 let e: business_error.BusinessError = error as business_error.BusinessError; 6667 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 6668 } 6669 6670 }) 6671 Web({ src: $rawfile('index.html'), controller: this.controller }) 6672 .databaseAccess(true) 6673 } 6674 } 6675} 6676``` 6677 6678For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 6679 6680### getOriginQuota 6681 6682static getOriginQuota(origin: string, callback: AsyncCallback\<number>): void 6683 6684Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. 6685 6686**System capability**: SystemCapability.Web.Webview.Core 6687 6688**Parameters** 6689 6690| Name | Type | Mandatory| Description | 6691| -------- | --------------------- | ---- | ------------------ | 6692| origin | string | Yes | Index of the origin.| 6693| callback | AsyncCallback\<number> | Yes | Storage quota of the origin. | 6694 6695**Error codes** 6696 6697For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 6698 6699| ID| Error Message | 6700| -------- | ------------------------------------------------------ | 6701| 17100011 | Invalid origin. | 6702 6703**Example** 6704 6705```ts 6706// xxx.ets 6707import web_webview from '@ohos.web.webview'; 6708import business_error from '@ohos.base'; 6709 6710@Entry 6711@Component 6712struct WebComponent { 6713 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6714 origin: string = "resource://rawfile/"; 6715 6716 build() { 6717 Column() { 6718 Button('getOriginQuota') 6719 .onClick(() => { 6720 try { 6721 web_webview.WebStorage.getOriginQuota(this.origin, (error, quota) => { 6722 if (error) { 6723 console.log('error: ' + JSON.stringify(error)); 6724 return; 6725 } 6726 console.log('quota: ' + quota); 6727 }) 6728 } catch (error) { 6729 let e: business_error.BusinessError = error as business_error.BusinessError; 6730 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 6731 } 6732 6733 }) 6734 Web({ src: $rawfile('index.html'), controller: this.controller }) 6735 .databaseAccess(true) 6736 } 6737 } 6738} 6739``` 6740 6741For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 6742 6743### getOriginQuota 6744 6745static getOriginQuota(origin: string): Promise\<number> 6746 6747Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. 6748 6749**System capability**: SystemCapability.Web.Webview.Core 6750 6751**Parameters** 6752 6753| Name| Type | Mandatory| Description | 6754| ------ | ------ | ---- | ------------------ | 6755| origin | string | Yes | Index of the origin.| 6756 6757**Return value** 6758 6759| Type | Description | 6760| --------------- | --------------------------------------- | 6761| Promise\<number> | Promise used to return the storage quota of the origin.| 6762 6763**Error codes** 6764 6765For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 6766 6767| ID| Error Message | 6768| -------- | ------------------------------------------------------ | 6769| 17100011 | Invalid origin. | 6770 6771**Example** 6772 6773```ts 6774// xxx.ets 6775import web_webview from '@ohos.web.webview'; 6776import business_error from '@ohos.base'; 6777 6778@Entry 6779@Component 6780struct WebComponent { 6781 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6782 origin: string = "resource://rawfile/"; 6783 6784 build() { 6785 Column() { 6786 Button('getOriginQuota') 6787 .onClick(() => { 6788 try { 6789 web_webview.WebStorage.getOriginQuota(this.origin) 6790 .then(quota => { 6791 console.log('quota: ' + quota); 6792 }) 6793 .catch((e : business_error.BusinessError) => { 6794 console.log('error: ' + JSON.stringify(e)); 6795 }) 6796 } catch (error) { 6797 let e: business_error.BusinessError = error as business_error.BusinessError; 6798 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 6799 } 6800 6801 }) 6802 Web({ src: $rawfile('index.html'), controller: this.controller }) 6803 .databaseAccess(true) 6804 } 6805 } 6806} 6807``` 6808 6809For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 6810 6811### getOriginUsage 6812 6813static getOriginUsage(origin: string, callback: AsyncCallback\<number>): void 6814 6815Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. 6816 6817**System capability**: SystemCapability.Web.Webview.Core 6818 6819**Parameters** 6820 6821| Name | Type | Mandatory| Description | 6822| -------- | --------------------- | ---- | ------------------ | 6823| origin | string | Yes | Index of the origin.| 6824| callback | AsyncCallback\<number> | Yes | Storage usage of the origin. | 6825 6826**Error codes** 6827 6828For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 6829 6830| ID| Error Message | 6831| -------- | ------------------------------------------------------ | 6832| 17100011 | Invalid origin. | 6833 6834**Example** 6835 6836```ts 6837// xxx.ets 6838import web_webview from '@ohos.web.webview'; 6839import business_error from '@ohos.base'; 6840 6841@Entry 6842@Component 6843struct WebComponent { 6844 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6845 origin: string = "resource://rawfile/"; 6846 6847 build() { 6848 Column() { 6849 Button('getOriginUsage') 6850 .onClick(() => { 6851 try { 6852 web_webview.WebStorage.getOriginUsage(this.origin, (error, usage) => { 6853 if (error) { 6854 console.log('error: ' + JSON.stringify(error)); 6855 return; 6856 } 6857 console.log('usage: ' + usage); 6858 }) 6859 } catch (error) { 6860 let e: business_error.BusinessError = error as business_error.BusinessError; 6861 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 6862 } 6863 6864 }) 6865 Web({ src: $rawfile('index.html'), controller: this.controller }) 6866 .databaseAccess(true) 6867 } 6868 } 6869} 6870``` 6871 6872For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 6873 6874### getOriginUsage 6875 6876static getOriginUsage(origin: string): Promise\<number> 6877 6878Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. 6879 6880**System capability**: SystemCapability.Web.Webview.Core 6881 6882**Parameters** 6883 6884| Name| Type | Mandatory| Description | 6885| ------ | ------ | ---- | ------------------ | 6886| origin | string | Yes | Index of the origin.| 6887 6888**Return value** 6889 6890| Type | Description | 6891| --------------- | ------------------------------------- | 6892| Promise\<number> | Promise used to return the storage usage of the origin.| 6893 6894**Error codes** 6895 6896For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 6897 6898| ID| Error Message | 6899| -------- | ----------------------------------------------------- | 6900| 17100011 | Invalid origin. | 6901 6902**Example** 6903 6904```ts 6905// xxx.ets 6906import web_webview from '@ohos.web.webview'; 6907import business_error from '@ohos.base'; 6908 6909@Entry 6910@Component 6911struct WebComponent { 6912 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6913 origin: string = "resource://rawfile/"; 6914 6915 build() { 6916 Column() { 6917 Button('getOriginUsage') 6918 .onClick(() => { 6919 try { 6920 web_webview.WebStorage.getOriginUsage(this.origin) 6921 .then(usage => { 6922 console.log('usage: ' + usage); 6923 }) 6924 .catch((e : business_error.BusinessError) => { 6925 console.log('error: ' + JSON.stringify(e)); 6926 }) 6927 } catch (error) { 6928 let e: business_error.BusinessError = error as business_error.BusinessError; 6929 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 6930 } 6931 6932 }) 6933 Web({ src: $rawfile('index.html'), controller: this.controller }) 6934 .databaseAccess(true) 6935 } 6936 } 6937} 6938``` 6939 6940For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 6941 6942### deleteAllData 6943 6944static deleteAllData(incognito?: boolean): void 6945 6946Deletes all data in the Web SQL Database. 6947 6948**System capability**: SystemCapability.Web.Webview.Core 6949 6950**Parameters** 6951 6952| Name| Type | Mandatory| Description | 6953| ------ | ------ | ---- | ------------------ | 6954| incognito<sup>11+</sup> | boolean | No | Whether to delete all data in the Web SQL Database in incognito mode. The value **true** means to delete all data in the Web SQL Database in incognito mode, and **false** means the opposite.| 6955 6956**Example** 6957 6958```ts 6959// xxx.ets 6960import web_webview from '@ohos.web.webview'; 6961import business_error from '@ohos.base'; 6962 6963@Entry 6964@Component 6965struct WebComponent { 6966 controller: web_webview.WebviewController = new web_webview.WebviewController(); 6967 6968 build() { 6969 Column() { 6970 Button('deleteAllData') 6971 .onClick(() => { 6972 try { 6973 web_webview.WebStorage.deleteAllData(); 6974 } catch (error) { 6975 let e: business_error.BusinessError = error as business_error.BusinessError; 6976 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 6977 } 6978 }) 6979 Web({ src: $rawfile('index.html'), controller: this.controller }) 6980 .databaseAccess(true) 6981 } 6982 } 6983} 6984``` 6985 6986For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 6987 6988## WebDataBase 6989 6990Implements a **WebDataBase** object. 6991 6992> **NOTE** 6993> 6994> You must load the **\<Web>** component before calling the APIs in **WebDataBase**. 6995 6996### getHttpAuthCredentials 6997 6998static getHttpAuthCredentials(host: string, realm: string): Array\<string> 6999 7000Retrieves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. 7001 7002**System capability**: SystemCapability.Web.Webview.Core 7003 7004**Parameters** 7005 7006| Name| Type | Mandatory| Description | 7007| ------ | ------ | ---- | ---------------------------- | 7008| host | string | Yes | Host to which HTTP authentication credentials apply.| 7009| realm | string | Yes | Realm to which HTTP authentication credentials apply. | 7010 7011**Return value** 7012 7013| Type | Description | 7014| ----- | -------------------------------------------- | 7015| Array\<string> | Returns the array of the matching user names and passwords if the operation is successful; returns an empty array otherwise.| 7016 7017**Example** 7018 7019```ts 7020// xxx.ets 7021import web_webview from '@ohos.web.webview'; 7022import business_error from '@ohos.base'; 7023 7024@Entry 7025@Component 7026struct WebComponent { 7027 controller: web_webview.WebviewController = new web_webview.WebviewController(); 7028 host: string = "www.spincast.org"; 7029 realm: string = "protected example"; 7030 username_password: string[] = []; 7031 7032 build() { 7033 Column() { 7034 Button('getHttpAuthCredentials') 7035 .onClick(() => { 7036 try { 7037 this.username_password = web_webview.WebDataBase.getHttpAuthCredentials(this.host, this.realm); 7038 console.log('num: ' + this.username_password.length); 7039 } catch (error) { 7040 let e: business_error.BusinessError = error as business_error.BusinessError; 7041 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 7042 } 7043 }) 7044 Web({ src: 'www.example.com', controller: this.controller }) 7045 } 7046 } 7047} 7048``` 7049 7050### saveHttpAuthCredentials 7051 7052static saveHttpAuthCredentials(host: string, realm: string, username: string, password: string): void 7053 7054Saves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. 7055 7056**System capability**: SystemCapability.Web.Webview.Core 7057 7058**Parameters** 7059 7060| Name | Type | Mandatory| Description | 7061| -------- | ------ | ---- | ---------------------------- | 7062| host | string | Yes | Host to which HTTP authentication credentials apply.| 7063| realm | string | Yes | Realm to which HTTP authentication credentials apply. | 7064| username | string | Yes | User name. | 7065| password | string | Yes | Password. | 7066 7067**Example** 7068 7069```ts 7070// xxx.ets 7071import web_webview from '@ohos.web.webview'; 7072import business_error from '@ohos.base'; 7073 7074@Entry 7075@Component 7076struct WebComponent { 7077 controller: web_webview.WebviewController = new web_webview.WebviewController(); 7078 host: string = "www.spincast.org"; 7079 realm: string = "protected example"; 7080 7081 build() { 7082 Column() { 7083 Button('saveHttpAuthCredentials') 7084 .onClick(() => { 7085 try { 7086 web_webview.WebDataBase.saveHttpAuthCredentials(this.host, this.realm, "Stromgol", "Laroche"); 7087 } catch (error) { 7088 let e: business_error.BusinessError = error as business_error.BusinessError; 7089 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 7090 } 7091 }) 7092 Web({ src: 'www.example.com', controller: this.controller }) 7093 } 7094 } 7095} 7096``` 7097 7098### existHttpAuthCredentials 7099 7100static existHttpAuthCredentials(): boolean 7101 7102Checks whether any saved HTTP authentication credentials exist. This API returns the result synchronously. 7103 7104**System capability**: SystemCapability.Web.Webview.Core 7105 7106**Return value** 7107 7108| Type | Description | 7109| ------- | ------------------------------------------------------------ | 7110| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist; returns **false** otherwise.| 7111 7112**Example** 7113 7114```ts 7115// xxx.ets 7116import web_webview from '@ohos.web.webview'; 7117import business_error from '@ohos.base'; 7118 7119@Entry 7120@Component 7121struct WebComponent { 7122 controller: web_webview.WebviewController = new web_webview.WebviewController(); 7123 7124 build() { 7125 Column() { 7126 Button('existHttpAuthCredentials') 7127 .onClick(() => { 7128 try { 7129 let result = web_webview.WebDataBase.existHttpAuthCredentials(); 7130 } catch (error) { 7131 let e: business_error.BusinessError = error as business_error.BusinessError; 7132 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 7133 } 7134 }) 7135 Web({ src: 'www.example.com', controller: this.controller }) 7136 } 7137 } 7138} 7139``` 7140 7141### deleteHttpAuthCredentials 7142 7143static deleteHttpAuthCredentials(): void 7144 7145Deletes all HTTP authentication credentials saved in the cache. This API returns the result synchronously. 7146 7147**System capability**: SystemCapability.Web.Webview.Core 7148 7149**Example** 7150 7151```ts 7152// xxx.ets 7153import web_webview from '@ohos.web.webview'; 7154import business_error from '@ohos.base'; 7155 7156@Entry 7157@Component 7158struct WebComponent { 7159 controller: web_webview.WebviewController = new web_webview.WebviewController(); 7160 7161 build() { 7162 Column() { 7163 Button('deleteHttpAuthCredentials') 7164 .onClick(() => { 7165 try { 7166 web_webview.WebDataBase.deleteHttpAuthCredentials(); 7167 } catch (error) { 7168 let e: business_error.BusinessError = error as business_error.BusinessError; 7169 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 7170 } 7171 }) 7172 Web({ src: 'www.example.com', controller: this.controller }) 7173 } 7174 } 7175} 7176``` 7177 7178## GeolocationPermissions 7179 7180Implements a **GeolocationPermissions** object. 7181 7182> **NOTE** 7183> 7184> You must load the **\<Web>** component before calling the APIs in **GeolocationPermissions**. 7185 7186### Required Permissions 7187 7188**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). 7189 7190### allowGeolocation 7191 7192static allowGeolocation(origin: string, incognito?: boolean): void 7193 7194Allows the specified origin to use the geolocation information. 7195 7196**System capability**: SystemCapability.Web.Webview.Core 7197 7198**Parameters** 7199 7200| Name| Type | Mandatory| Description | 7201| ------ | ------ | ---- | ------------------ | 7202| origin | string | Yes |Index of the origin.| 7203| incognito<sup>11+</sup> | boolean | No | Whether to allow the specified origin to use the geolocation information in incognito mode. The value **true** means to allow the specified origin to use the geolocation information in incognito mode, and **false** means the opposite.| 7204 7205**Error codes** 7206 7207For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 7208 7209| ID| Error Message | 7210| -------- | ------------------------------------------------------ | 7211| 17100011 | Invalid origin. | 7212 7213**Example** 7214 7215```ts 7216// xxx.ets 7217import web_webview from '@ohos.web.webview'; 7218import business_error from '@ohos.base'; 7219 7220@Entry 7221@Component 7222struct WebComponent { 7223 controller: web_webview.WebviewController = new web_webview.WebviewController(); 7224 origin: string = "file:///"; 7225 7226 build() { 7227 Column() { 7228 Button('allowGeolocation') 7229 .onClick(() => { 7230 try { 7231 web_webview.GeolocationPermissions.allowGeolocation(this.origin); 7232 } catch (error) { 7233 let e: business_error.BusinessError = error as business_error.BusinessError; 7234 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 7235 } 7236 }) 7237 Web({ src: 'www.example.com', controller: this.controller }) 7238 } 7239 } 7240} 7241``` 7242 7243### deleteGeolocation 7244 7245static deleteGeolocation(origin: string, incognito?: boolean): void 7246 7247Clears the geolocation permission status of a specified origin. 7248 7249**System capability**: SystemCapability.Web.Webview.Core 7250 7251**Parameters** 7252 7253| Name| Type | Mandatory| Description | 7254| ------ | ------ | ---- | ------------------ | 7255| origin | string | Yes | Index of the origin.| 7256| incognito<sup>11+</sup> | boolean | No | Whether to clear the geolocation permission status of a specified origin in incognito mode. The value **true** means to clear the geolocation permission status of a specified origin in incognito mode, and **false** means the opposite.| 7257 7258**Error codes** 7259 7260For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 7261 7262| ID| Error Message | 7263| -------- | ------------------------------------------------------ | 7264| 17100011 | Invalid origin. | 7265 7266**Example** 7267 7268```ts 7269// xxx.ets 7270import web_webview from '@ohos.web.webview'; 7271import business_error from '@ohos.base'; 7272 7273@Entry 7274@Component 7275struct WebComponent { 7276 controller: web_webview.WebviewController = new web_webview.WebviewController(); 7277 origin: string = "file:///"; 7278 7279 build() { 7280 Column() { 7281 Button('deleteGeolocation') 7282 .onClick(() => { 7283 try { 7284 web_webview.GeolocationPermissions.deleteGeolocation(this.origin); 7285 } catch (error) { 7286 let e: business_error.BusinessError = error as business_error.BusinessError; 7287 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 7288 } 7289 }) 7290 Web({ src: 'www.example.com', controller: this.controller }) 7291 } 7292 } 7293} 7294``` 7295 7296### getAccessibleGeolocation 7297 7298static getAccessibleGeolocation(origin: string, callback: AsyncCallback\<boolean>, incognito?: boolean): void 7299 7300Obtains the geolocation permission status of the specified origin. This API uses an asynchronous callback to return the result. 7301 7302**System capability**: SystemCapability.Web.Webview.Core 7303 7304**Parameters** 7305 7306| Name | Type | Mandatory| Description | 7307| -------- | ---------------------- | ---- | ------------------------------------------------------------ | 7308| origin | string | Yes | Index of the origin. | 7309| 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.| 7310| incognito<sup>11+</sup> | boolean | No | Whether to obtain the geolocation permission status of the specified origin in incognito mode. The value **true** means to obtain the geolocation permission status of the specified origin in incognito mode, and **false** means the opposite.| 7311 7312**Error codes** 7313 7314For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 7315 7316| ID| Error Message | 7317| -------- | ------------------------------------------------------ | 7318| 17100011 | Invalid origin. | 7319 7320**Example** 7321 7322```ts 7323// xxx.ets 7324import web_webview from '@ohos.web.webview'; 7325import business_error from '@ohos.base'; 7326 7327@Entry 7328@Component 7329struct WebComponent { 7330 controller: web_webview.WebviewController = new web_webview.WebviewController(); 7331 origin: string = "file:///"; 7332 7333 build() { 7334 Column() { 7335 Button('getAccessibleGeolocation') 7336 .onClick(() => { 7337 try { 7338 web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin, (error, result) => { 7339 if (error) { 7340 console.log('getAccessibleGeolocationAsync error: ' + JSON.stringify(error)); 7341 return; 7342 } 7343 console.log('getAccessibleGeolocationAsync result: ' + result); 7344 }); 7345 } catch (error) { 7346 let e: business_error.BusinessError = error as business_error.BusinessError; 7347 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 7348 } 7349 }) 7350 Web({ src: 'www.example.com', controller: this.controller }) 7351 } 7352 } 7353} 7354``` 7355 7356### getAccessibleGeolocation 7357 7358static getAccessibleGeolocation(origin: string, incognito?: boolean): Promise\<boolean> 7359 7360Obtains the geolocation permission status of the specified origin. This API uses a promise to return the result. 7361 7362**System capability**: SystemCapability.Web.Webview.Core 7363 7364**Parameters** 7365 7366| Name| Type| Mandatory| Description | 7367| ------ | -------- | ---- | -------------------- | 7368| origin | string | Yes | Index of the origin.| 7369| incognito<sup>11+</sup> | boolean | No | Whether to obtain the geolocation permission status of the specified origin in incognito mode. The value **true** means to obtain the geolocation permission status of the specified origin in incognito mode, and **false** means the opposite.| 7370 7371**Return value** 7372 7373| Type | Description | 7374| ---------------- | ------------------------------------------------------------ | 7375| 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.| 7376 7377**Error codes** 7378 7379For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 7380 7381| ID| Error Message | 7382| -------- | ------------------------------------------------------ | 7383| 17100011 | Invalid origin. | 7384 7385**Example** 7386 7387```ts 7388// xxx.ets 7389import web_webview from '@ohos.web.webview'; 7390import business_error from '@ohos.base'; 7391 7392@Entry 7393@Component 7394struct WebComponent { 7395 controller: web_webview.WebviewController = new web_webview.WebviewController(); 7396 origin: string = "file:///"; 7397 7398 build() { 7399 Column() { 7400 Button('getAccessibleGeolocation') 7401 .onClick(() => { 7402 try { 7403 web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin) 7404 .then(result => { 7405 console.log('getAccessibleGeolocationPromise result: ' + result); 7406 }).catch((error : business_error.BusinessError) => { 7407 console.log('getAccessibleGeolocationPromise error: ' + JSON.stringify(error)); 7408 }); 7409 } catch (error) { 7410 let e: business_error.BusinessError = error as business_error.BusinessError; 7411 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 7412 } 7413 }) 7414 Web({ src: 'www.example.com', controller: this.controller }) 7415 } 7416 } 7417} 7418``` 7419 7420### getStoredGeolocation 7421 7422static getStoredGeolocation(callback: AsyncCallback\<Array\<string>>, incognito?: boolean): void 7423 7424Obtains the geolocation permission status of all origins. This API uses an asynchronous callback to return the result. 7425 7426**System capability**: SystemCapability.Web.Webview.Core 7427 7428**Parameters** 7429 7430| Name | Type | Mandatory| Description | 7431| -------- | ---------------------------- | ---- | ---------------------------------------- | 7432| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return the geolocation permission status of all origins.| 7433| incognito<sup>11+</sup> | boolean | No | Whether to obtain the geolocation permission status of all origins in incognito mode. The value **true** means to obtain the geolocation permission status of all origins in incognito mode, and **false** means the opposite.| 7434 7435**Example** 7436 7437```ts 7438// xxx.ets 7439import web_webview from '@ohos.web.webview'; 7440import business_error from '@ohos.base'; 7441 7442@Entry 7443@Component 7444struct WebComponent { 7445 controller: web_webview.WebviewController = new web_webview.WebviewController(); 7446 7447 build() { 7448 Column() { 7449 Button('getStoredGeolocation') 7450 .onClick(() => { 7451 try { 7452 web_webview.GeolocationPermissions.getStoredGeolocation((error, origins) => { 7453 if (error) { 7454 console.error(`getStoredGeolocationAsync error, ErrorCode: ${e.code}, Message: ${e.message}`); 7455 return; 7456 } 7457 let origins_str: string = origins.join(); 7458 console.log('getStoredGeolocationAsync origins: ' + origins_str); 7459 }); 7460 } catch (error) { 7461 let e: business_error.BusinessError = error as business_error.BusinessError; 7462 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 7463 } 7464 }) 7465 Web({ src: 'www.example.com', controller: this.controller }) 7466 } 7467 } 7468} 7469``` 7470 7471### getStoredGeolocation 7472 7473static getStoredGeolocation(incognito?: boolean): Promise\<Array\<string>> 7474 7475Obtains the geolocation permission status of all origins. This API uses a promise to return the result. 7476 7477**System capability**: SystemCapability.Web.Webview.Core 7478 7479**Parameters** 7480 7481| Name | Type | Mandatory| Description | 7482| -------- | ---------------------------- | ---- | ---------------------------------------- | 7483| incognito<sup>11+</sup> | boolean | No | Whether to obtain the geolocation permission status of all origins in incognito mode. The value **true** means to obtain the geolocation permission status of all origins in incognito mode, and **false** means the opposite.| 7484 7485**Return value** 7486 7487| Type | Description | 7488| ---------------------- | --------------------------------------------------------- | 7489| Promise\<Array\<string>> | Promise used to return the geolocation permission status of all origins.| 7490 7491**Example** 7492 7493```ts 7494// xxx.ets 7495import web_webview from '@ohos.web.webview'; 7496import business_error from '@ohos.base'; 7497 7498@Entry 7499@Component 7500struct WebComponent { 7501 controller: web_webview.WebviewController = new web_webview.WebviewController(); 7502 7503 build() { 7504 Column() { 7505 Button('getStoredGeolocation') 7506 .onClick(() => { 7507 try { 7508 web_webview.GeolocationPermissions.getStoredGeolocation() 7509 .then(origins => { 7510 let origins_str: string = origins.join(); 7511 console.log('getStoredGeolocationPromise origins: ' + origins_str); 7512 }).catch((error : business_error.BusinessError) => { 7513 console.error(`getStoredGeolocationPromise error, ErrorCode: ${e.code}, Message: ${e.message}`); 7514 }); 7515 } catch (error) { 7516 let e: business_error.BusinessError = error as business_error.BusinessError; 7517 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 7518 } 7519 }) 7520 Web({ src: 'www.example.com', controller: this.controller }) 7521 } 7522 } 7523} 7524``` 7525 7526### deleteAllGeolocation 7527 7528static deleteAllGeolocation(incognito?: boolean): void 7529 7530Clears the geolocation permission status of all sources. 7531 7532**System capability**: SystemCapability.Web.Webview.Core 7533 7534**Parameters** 7535 7536| Name | Type | Mandatory| Description | 7537| -------- | ---------------------------- | ---- | ---------------------------------------- | 7538| incognito<sup>11+</sup> | boolean | No | Whether to clear the geolocation permission status of all sources in incognito mode. The value **true** means to clear the geolocation permission status of all sources in incognito mode, and **false** means the opposite.| 7539 7540**Example** 7541 7542```ts 7543// xxx.ets 7544import web_webview from '@ohos.web.webview'; 7545import business_error from '@ohos.base'; 7546 7547@Entry 7548@Component 7549struct WebComponent { 7550 controller: web_webview.WebviewController = new web_webview.WebviewController(); 7551 7552 build() { 7553 Column() { 7554 Button('deleteAllGeolocation') 7555 .onClick(() => { 7556 try { 7557 web_webview.GeolocationPermissions.deleteAllGeolocation(); 7558 } catch (error) { 7559 let e: business_error.BusinessError = error as business_error.BusinessError; 7560 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 7561 } 7562 }) 7563 Web({ src: 'www.example.com', controller: this.controller }) 7564 } 7565 } 7566} 7567``` 7568## WebHeader 7569 7570Describes the request/response header returned by the **\<Web>** component. 7571 7572**System capability**: SystemCapability.Web.Webview.Core 7573 7574| Name | Type | Readable| Writable|Description | 7575| ----------- | ------ | -----|------|------------------- | 7576| headerKey | string | Yes| Yes| Key of the request/response header. | 7577| headerValue | string | Yes| Yes| Value of the request/response header.| 7578 7579## WebHitTestType 7580 7581The [getHitTest](#gethittest) API is used to indicate a cursor node. 7582 7583**System capability**: SystemCapability.Web.Webview.Core 7584 7585| Name | Value| Description | 7586| ------------- | -- |----------------------------------------- | 7587| EditText | 0 |Editable area. | 7588| Email | 1 |Email address. | 7589| HttpAnchor | 2 |Hyperlink, where **src** is **http**. | 7590| HttpAnchorImg | 3 |Image with a hyperlink, where **src** is http + HTML::img.| 7591| Img | 4 |HTML::img tag. | 7592| Map | 5 |Geographical address. | 7593| Phone | 6 |Phone number. | 7594| Unknown | 7 |Unknown content. | 7595 7596## SecurityLevel<sup>11+</sup> 7597 7598Defines the security level of the web page. 7599 7600**System capability**: SystemCapability.Web.Webview.Core 7601 7602| Name | Value| Description | 7603| ------------- | -- |----------------------------------------- | 7604| NONE | 0 |The web page is neither absolutely secure nor insecure, that is, neutral. A typical example is a web page whose URL scheme is not HTTP or HTTPS.| 7605| SECURE | 1 |The web page is secure, using the HTTPS protocol and a trusted certificate.| 7606| WARNING | 2 |The web page is possibly compromised. A typical example is a web page that uses the HTTP or HTTPS protocol but an outdated TLS version.| 7607| DANGEROUS | 3 |The web page is insecure. This means that the page may have attempted to load HTTPS scripts to no avail, have failed authentication, or contain insecure active content in HTTPS, malware, phishing, or any other sources of major threats.| 7608 7609## HitTestValue 7610 7611Provides the element information of the area being clicked. For details about the sample code, see [getHitTestValue](#gethittestvalue). 7612 7613**System capability**: SystemCapability.Web.Webview.Core 7614 7615| Name| Type| Readable| Writable| Description| 7616| ---- | ---- | ---- | ---- |---- | 7617| type | [WebHitTestType](#webhittesttype) | Yes| No| Element type of the area being clicked.| 7618| 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.| 7619 7620## WebMessage 7621 7622Describes the data types supported for [WebMessagePort](#webmessageport). 7623 7624**System capability**: SystemCapability.Web.Webview.Core 7625 7626| Type | Description | 7627| -------- | -------------------------------------- | 7628| string | String type.| 7629| ArrayBuffer | Binary type.| 7630 7631## JsMessageType<sup>10+</sup> 7632 7633Describes the type of the returned result of script execution using [runJavaScirptExt](#runjavascriptext10). 7634 7635**System capability**: SystemCapability.Web.Webview.Core 7636 7637| Name | Value| Description | 7638| ------------ | -- |--------------------------------- | 7639| NOT_SUPPORT | 0 |Unsupported data type.| 7640| STRING | 1 |String type.| 7641| NUMBER | 2 |Number type.| 7642| BOOLEAN | 3 |Boolean type.| 7643| ARRAY_BUFFER | 4 |Raw binary data buffer.| 7644| ARRAY | 5 |Array type.| 7645 7646## WebMessageType<sup>10+</sup> 7647 7648Describes the data type supported by the [webMessagePort](#webmessageport) API. 7649 7650**System capability**: SystemCapability.Web.Webview.Core 7651 7652| Name | Value| Description | 7653| ------------ | -- |------------------------------- | 7654| NOT_SUPPORT | 0 |Unsupported data type.| 7655| STRING | 1 |String type.| 7656| NUMBER | 2 |Number type.| 7657| BOOLEAN | 3 |Boolean type.| 7658| ARRAY_BUFFER | 4 |Raw binary data buffer.| 7659| ARRAY | 5 |Array type.| 7660| ERROR | 6 |Error object type.| 7661 7662## JsMessageExt<sup>10+</sup> 7663 7664Implements the **JsMessageExt** data object that is returned after script execution using the [runJavaScirptExt](#runjavascriptext10) API. 7665 7666### getType<sup>10+</sup> 7667 7668getType(): JsMessageType 7669 7670Obtains the type of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 7671 7672**System capability**: SystemCapability.Web.Webview.Core 7673 7674**Return value** 7675 7676| Type | Description | 7677| --------------| --------------------------------------------------------- | 7678| [JsMessageType](#jsmessagetype10) | Type of the data object that is returned after script execution using the [runJavaScirptExt](#runjavascriptext10) API.| 7679 7680### getString<sup>10+</sup> 7681 7682getString(): string 7683 7684Obtains string-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 7685 7686**System capability**: SystemCapability.Web.Webview.Core 7687 7688**Return value** 7689 7690| Type | Description | 7691| --------------| ------------- | 7692| string | Data of the string type.| 7693 7694**Error codes** 7695 7696For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 7697 7698| ID| Error Message | 7699| -------- | ------------------------------------- | 7700| 17100014 | The type does not match with the value of the result. | 7701 7702### getNumber<sup>10+</sup> 7703 7704getNumber(): number 7705 7706Obtains number-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 7707 7708**System capability**: SystemCapability.Web.Webview.Core 7709 7710**Return value** 7711 7712| Type | Description | 7713| --------------| ------------- | 7714| number | Data of the number type.| 7715 7716**Error codes** 7717 7718For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 7719 7720| ID| Error Message | 7721| -------- | ------------------------------------- | 7722| 17100014 | The type does not match with the value of the result. | 7723 7724### getBoolean<sup>10+</sup> 7725 7726getBoolean(): boolean 7727 7728Obtains Boolean-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 7729 7730**System capability**: SystemCapability.Web.Webview.Core 7731 7732**Return value** 7733 7734| Type | Description | 7735| --------------| ------------- | 7736| boolean | Data of the Boolean type.| 7737 7738**Error codes** 7739 7740For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 7741 7742| ID| Error Message | 7743| -------- | ------------------------------------- | 7744| 17100014 | The type does not match with the value of the result. | 7745 7746### getArrayBuffer<sup>10+</sup> 7747 7748getArrayBuffer(): ArrayBuffer 7749 7750Obtains raw binary data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 7751 7752**System capability**: SystemCapability.Web.Webview.Core 7753 7754**Return value** 7755 7756| Type | Description | 7757| --------------| ------------- | 7758| ArrayBuffer | Raw binary data.| 7759 7760**Error codes** 7761 7762For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 7763 7764| ID| Error Message | 7765| -------- | ------------------------------------- | 7766| 17100014 | The type does not match with the value of the result. | 7767 7768### getArray<sup>10+</sup> 7769 7770getArray(): Array\<string | number | boolean\> 7771 7772Obtains array-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 7773 7774**System capability**: SystemCapability.Web.Webview.Core 7775 7776**Return value** 7777 7778| Type | Description | 7779| --------------| ------------- | 7780| Array\<string \| number \| boolean\> | Data of the array type.| 7781 7782**Error codes** 7783 7784For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 7785 7786| ID| Error Message | 7787| -------- | ------------------------------------- | 7788| 17100014 | The type does not match with the value of the result. | 7789 7790## WebMessageExt<sup>10+</sup> 7791 7792Data object received and sent by the [webMessagePort](#webmessageport) interface. 7793 7794### getType<sup>10+</sup> 7795 7796getType(): WebMessageType 7797 7798Obtains the type of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 7799 7800**System capability**: SystemCapability.Web.Webview.Core 7801 7802**Return value** 7803 7804| Type | Description | 7805| --------------| --------------------------------------------------------- | 7806| [WebMessageType](#webmessagetype10) | Data type supported by the [webMessagePort](#webmessageport) API.| 7807 7808### getString<sup>10+</sup> 7809 7810getString(): string 7811 7812Obtains string-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 7813 7814**System capability**: SystemCapability.Web.Webview.Core 7815 7816**Return value** 7817 7818| Type | Description | 7819| --------------| ------------- | 7820| string | Data of the string type.| 7821 7822**Error codes** 7823 7824For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 7825 7826| ID| Error Message | 7827| -------- | ------------------------------------- | 7828| 17100014 | The type does not match with the value of the web message. | 7829 7830### getNumber<sup>10+</sup> 7831 7832getNumber(): number 7833 7834Obtains number-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 7835 7836**System capability**: SystemCapability.Web.Webview.Core 7837 7838**Return value** 7839 7840| Type | Description | 7841| --------------| ------------- | 7842| number | Data of the number type.| 7843 7844**Error codes** 7845 7846For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 7847 7848| ID| Error Message | 7849| -------- | ------------------------------------- | 7850| 17100014 | The type does not match with the value of the web message. | 7851 7852### getBoolean<sup>10+</sup> 7853 7854getBoolean(): boolean 7855 7856Obtains Boolean-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 7857 7858**System capability**: SystemCapability.Web.Webview.Core 7859 7860**Return value** 7861 7862| Type | Description | 7863| --------------| ------------- | 7864| boolean | Data of the Boolean type.| 7865 7866**Error codes** 7867 7868For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 7869 7870| ID| Error Message | 7871| -------- | ------------------------------------- | 7872| 17100014 | The type does not match with the value of the web message. | 7873 7874### getArrayBuffer<sup>10+</sup> 7875 7876getArrayBuffer(): ArrayBuffer 7877 7878Obtains raw binary data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 7879 7880**System capability**: SystemCapability.Web.Webview.Core 7881 7882**Return value** 7883 7884| Type | Description | 7885| --------------| ------------- | 7886| ArrayBuffer | Raw binary data.| 7887 7888**Error codes** 7889 7890For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 7891 7892| ID| Error Message | 7893| -------- | ------------------------------------- | 7894| 17100014 | The type does not match with the value of the web message. | 7895 7896### getArray<sup>10+</sup> 7897 7898getArray(): Array\<string | number | boolean\> 7899 7900Obtains array-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 7901 7902**System capability**: SystemCapability.Web.Webview.Core 7903 7904**Return value** 7905 7906| Type | Description | 7907| --------------| ------------- | 7908| Array\<string \| number \| boolean\> | Data of the array type.| 7909 7910**Error codes** 7911 7912For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 7913 7914| ID| Error Message | 7915| -------- | ------------------------------------- | 7916| 17100014 | The type does not match with the value of the web message. | 7917 7918### getError<sup>10+</sup> 7919 7920getError(): Error 7921 7922Obtains the error-object-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 7923 7924**System capability**: SystemCapability.Web.Webview.Core 7925 7926**Return value** 7927 7928| Type | Description | 7929| --------------| ------------- | 7930| Error | Data of the error object type.| 7931 7932**Error codes** 7933 7934For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 7935 7936| ID| Error Message | 7937| -------- | ------------------------------------- | 7938| 17100014 | The type does not match with the value of the web message. | 7939 7940### setType<sup>10+</sup> 7941 7942setType(type: WebMessageType): void 7943 7944Sets the type for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 7945 7946**System capability**: SystemCapability.Web.Webview.Core 7947 7948**Parameters** 7949 7950| Name| Type | Mandatory| Description | 7951| ------ | ------ | ---- | ---------------------- | 7952| type | [WebMessageType](#webmessagetype10) | Yes | Data type supported by the [webMessagePort](#webmessageport) API.| 7953 7954**Error codes** 7955 7956| ID| Error Message | 7957| -------- | ------------------------------------- | 7958| 17100014 | The type does not match with the value of the web message. | 7959 7960### setString<sup>10+</sup> 7961 7962setString(message: string): void 7963 7964Sets the string-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 7965 7966**System capability**: SystemCapability.Web.Webview.Core 7967 7968**Parameters** 7969 7970| Name| Type | Mandatory| Description | 7971| ------ | ------ | ---- | -------------------- | 7972| message | string | Yes | String type.| 7973 7974**Error codes** 7975 7976| ID| Error Message | 7977| -------- | ------------------------------------- | 7978| 17100014 | The type does not match with the value of the web message. | 7979 7980### setNumber<sup>10+</sup> 7981 7982setNumber(message: number): void 7983 7984Sets the number-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 7985 7986**System capability**: SystemCapability.Web.Webview.Core 7987 7988**Parameters** 7989 7990| Name| Type | Mandatory| Description | 7991| ------ | ------ | ---- | -------------------- | 7992| message | number | Yes | Data of the number type.| 7993 7994**Error codes** 7995 7996| ID| Error Message | 7997| -------- | ------------------------------------- | 7998| 17100014 | The type does not match with the value of the web message. | 7999 8000### setBoolean<sup>10+</sup> 8001 8002setBoolean(message: boolean): void 8003 8004Sets the Boolean-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 8005 8006**System capability**: SystemCapability.Web.Webview.Core 8007 8008**Parameters** 8009 8010| Name| Type | Mandatory| Description | 8011| ------ | ------ | ---- | -------------------- | 8012| message | boolean | Yes | Data of the Boolean type.| 8013 8014**Error codes** 8015 8016| ID| Error Message | 8017| -------- | ------------------------------------- | 8018| 17100014 | The type does not match with the value of the web message. | 8019 8020### setArrayBuffer<sup>10+</sup> 8021 8022setArrayBuffer(message: ArrayBuffer): void 8023 8024Sets the raw binary data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 8025 8026**System capability**: SystemCapability.Web.Webview.Core 8027 8028**Parameters** 8029 8030| Name| Type | Mandatory| Description | 8031| ------ | ------ | ---- | -------------------- | 8032| message | ArrayBuffer | Yes | Raw binary data.| 8033 8034**Error codes** 8035 8036For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 8037 8038| ID| Error Message | 8039| -------- | ------------------------------------- | 8040| 17100014 | The type does not match with the value of the web message. | 8041 8042### setArray<sup>10+</sup> 8043 8044setArray(message: Array\<string | number | boolean\>): void 8045 8046Sets the array-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 8047 8048**System capability**: SystemCapability.Web.Webview.Core 8049 8050**Parameters** 8051 8052| Name| Type | Mandatory| Description | 8053| ------ | ------ | ---- | -------------------- | 8054| message | Array\<string \| number \| boolean\> | Yes | Data of the array type.| 8055 8056**Error codes** 8057 8058For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 8059 8060| ID| Error Message | 8061| -------- | ------------------------------------- | 8062| 17100014 | The type does not match with the value of the web message. | 8063 8064### setError<sup>10+</sup> 8065 8066setError(message: Error): void 8067 8068Sets the error-object-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 8069 8070**System capability**: SystemCapability.Web.Webview.Core 8071 8072**Parameters** 8073 8074| Name| Type | Mandatory| Description | 8075| ------ | ------ | ---- | -------------------- | 8076| message | Error | Yes | Data of the error object type.| 8077 8078**Error codes** 8079 8080For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 8081 8082| ID| Error Message | 8083| -------- | ------------------------------------- | 8084| 17100014 | The type does not match with the value of the web message. | 8085 8086## WebStorageOrigin 8087 8088Provides usage information of the Web SQL Database. 8089 8090**System capability**: SystemCapability.Web.Webview.Core 8091 8092| Name | Type | Readable| Writable| Description| 8093| ------ | ------ | ---- | ---- | ---- | 8094| origin | string | Yes | No| Index of the origin.| 8095| usage | number | Yes | No| Storage usage of the origin. | 8096| quota | number | Yes | No| Storage quota of the origin. | 8097 8098## BackForwardList 8099 8100Provides the historical information list of the current webview. 8101 8102**System capability**: SystemCapability.Web.Webview.Core 8103 8104| Name | Type | Readable| Writable| Description | 8105| ------------ | ------ | ---- | ---- | ------------------------------------------------------------ | 8106| currentIndex | number | Yes | No | Index of the current page in the page history stack. | 8107| 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.| 8108 8109### getItemAtIndex 8110 8111getItemAtIndex(index: number): HistoryItem 8112 8113Obtains the page record with the specified index in the history stack. 8114 8115**System capability**: SystemCapability.Web.Webview.Core 8116 8117**Parameters** 8118 8119| Name| Type | Mandatory| Description | 8120| ------ | ------ | ---- | ---------------------- | 8121| index | number | Yes | Index of the target page record in the history stack.| 8122 8123**Return value** 8124 8125| Type | Description | 8126| --------------------------- | ------------ | 8127| [HistoryItem](#historyitem) | Historical page record.| 8128 8129**Example** 8130 8131```ts 8132// xxx.ets 8133import web_webview from '@ohos.web.webview'; 8134import image from "@ohos.multimedia.image"; 8135import business_error from '@ohos.base'; 8136 8137@Entry 8138@Component 8139struct WebComponent { 8140 controller: web_webview.WebviewController = new web_webview.WebviewController(); 8141 @State icon: image.PixelMap | undefined = undefined; 8142 8143 build() { 8144 Column() { 8145 Button('getBackForwardEntries') 8146 .onClick(() => { 8147 try { 8148 let list = this.controller.getBackForwardEntries(); 8149 let historyItem = list.getItemAtIndex(list.currentIndex); 8150 console.log("HistoryItem: " + JSON.stringify(historyItem)); 8151 this.icon = historyItem.icon; 8152 } catch (error) { 8153 let e: business_error.BusinessError = error as business_error.BusinessError; 8154 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8155 } 8156 }) 8157 Web({ src: 'www.example.com', controller: this.controller }) 8158 } 8159 } 8160} 8161``` 8162 8163## HistoryItem 8164 8165Describes a historical page record. 8166 8167**System capability**: SystemCapability.Web.Webview.Core 8168 8169| Name | Type | Readable| Writable| Description | 8170| ------------- | -------------------------------------- | ---- | ---- | ---------------------------- | 8171| icon | [PixelMap](js-apis-image.md#pixelmap7) | Yes | No | **PixelMap** object of the icon on the historical page.| 8172| historyUrl | string | Yes | No | URL of the historical page. | 8173| historyRawUrl | string | Yes | No | Original URL of the historical page. | 8174| title | string | Yes | No | Title of the historical page. | 8175 8176## WebCustomScheme 8177 8178Defines a custom URL scheme. 8179 8180**System capability**: SystemCapability.Web.Webview.Core 8181 8182| Name | Type | Readable| Writable| Description | 8183| -------------- | --------- | ---- | ---- | ---------------------------- | 8184| 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 (-). | 8185| isSupportCORS | boolean | Yes | Yes | Whether to support cross-origin resource sharing (CORS). | 8186| isSupportFetch | boolean | Yes | Yes | Whether to support fetch requests. | 8187 8188## SecureDnsMode<sup>10+</sup> 8189 8190Describes the mode in which the **\<Web>** component uses HTTPDNS. 8191 8192**System capability**: SystemCapability.Web.Webview.Core 8193 8194| Name | Value| Description | 8195| ------------- | -- |----------------------------------------- | 8196| OFF | 0 |HTTPDNS is not used. This value can be used to revoke the previously used HTTPDNS configuration.| 8197| 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.| 8198| SECURE_ONLY | 2 |The specified HTTPDNS server is forcibly used for DNS resolution.| 8199 8200## WebDownloadState<sup>11+</sup> 8201 8202Describes the state of a download task. 8203 8204**System capability**: SystemCapability.Web.Webview.Core 8205 8206| Name | Value| Description | 8207| ------------- | -- |----------------------------------------- | 8208| IN_PROGRESS | 0 |The download task is in progress.| 8209| COMPLETED | 1 |The download task is completed.| 8210| CANCELED | 2 |The download task has been canceled.| 8211| INTERRUPTED | 3 |The download task is interrupted.| 8212| PENDING | 4 |The download task is pending.| 8213| PAUSED | 5 |The download task is paused.| 8214| UNKNOWN | 6 |The state of the download task is unknown.| 8215 8216## WebDownloadErrorCode<sup>11+</sup> 8217 8218Describes the download task error code. 8219 8220**System capability**: SystemCapability.Web.Webview.Core 8221 8222| Name | Value| Description | 8223| ------------- | -- |----------------------------------------- | 8224| ERROR_UNKNOWN | 0 |Unknown error.| 8225| FILE_FAILED | 1 | Failed to operate the file.| 8226| FILE_ACCESS_DENIED | 2 | No permission to access the file.| 8227| FILE_NO_SPACE | 3 | The disk space is insufficient.| 8228| FILE_NAME_TOO_LONG | 5 | The file name is too long.| 8229| FILE_TOO_LARGE | 6 | The file is too large.| 8230| FILE_TRANSIENT_ERROR | 10 | Some temporary issues occur, such as insufficient memory, files in use, and too many files open at the same time.| 8231| FILE_BLOCKED | 11 | Access to the file is blocked due to certain local policies.| 8232| FILE_TOO_SHORT | 13 | The file to resume downloading is not long enough. It may not exist.| 8233| FILE_HASH_MISMATCH | 14 | Hash mismatch.| 8234| FILE_SAME_AS_SOURCE | 15 | The file already exists.| 8235| NETWORK_FAILED | 20 | Common network error.| 8236| NETWORK_TIMEOUT | 21 | Network connection timeout.| 8237| NETWORK_DISCONNECTED | 22 | Network disconnected.| 8238| NETWORK_SERVER_DOWN | 23 | The server is shut down.| 8239| NETWORK_INVALID_REQUEST | 24 | Invalid network request. The request may be redirected to an unsupported scheme or an invalid URL.| 8240| SERVER_FAILED | 30 | The server returns a general error.| 8241| SERVER_NO_RANGE | 31 | The server does not support the range request.| 8242| SERVER_BAD_CONTENT | 33 | The server does not have the requested data.| 8243| SERVER_UNAUTHORIZED | 34 | The file cannot be downloaded from the server.| 8244| SERVER_CERT_PROBLEM | 35 | The server certificate is incorrect.| 8245| SERVER_FORBIDDEN | 36 | The access to the server is forbidden.| 8246| SERVER_UNREACHABLE | 37 | The server cannot be accessed.| 8247| SERVER_CONTENT_LENGTH_MISMATCH | 38 | The received data does not match the content length.| 8248| SERVER_CROSS_ORIGIN_REDIRECT | 39 | An unexpected cross-site redirection occurs.| 8249| USER_CANCELED | 40 | The user cancels the download.| 8250| USER_SHUTDOWN | 41 | The user closes the application.| 8251| CRASH | 50 | The application crashes.| 8252 8253## WebDownloadItem<sup>11+</sup> 8254 8255 Implements a **WebDownloadItem** object. You can use this object to perform operations on the corresponding download task. 8256 8257> **NOTE** 8258> 8259> During the download, the download process is notified to the user through **WebDownloadDelegate**. The user can operate the download task through the **WebDownloadItem** parameter. 8260 8261### getGuid<sup>11+</sup> 8262 8263getGuid(): string 8264 8265Obtains the unique ID of this download task. 8266 8267**System capability**: SystemCapability.Web.Webview.Core 8268 8269**Return value** 8270 8271| Type | Description | 8272| ------ | ------------------------- | 8273| string | Unique ID of the download task.| 8274 8275**Example** 8276 8277```ts 8278// xxx.ets 8279import web_webview from '@ohos.web.webview' 8280import business_error from '@ohos.base' 8281 8282@Entry 8283@Component 8284struct WebComponent { 8285 controller: web_webview.WebviewController = new web_webview.WebviewController(); 8286 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 8287 8288 build() { 8289 Column() { 8290 Button('setDownloadDelegate') 8291 .onClick(() => { 8292 try { 8293 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 8294 console.log("will start a download."); 8295 // Pass in a download path and start the download. 8296 webDownloadItem.start("xxxxxxxx"); 8297 }) 8298 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 8299 console.log("download update guid: " + webDownloadItem.getGuid()); 8300 }) 8301 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 8302 console.log("download failed guid: " + webDownloadItem.getGuid()); 8303 }) 8304 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 8305 console.log("download finish guid: " + webDownloadItem.getGuid()); 8306 }) 8307 this.controller.setDownloadDelegate(this.delegate); 8308 } catch (error) { 8309 let e:business_error.BusinessError = error as business_error.BusinessError; 8310 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8311 } 8312 }) 8313 Button('startDownload') 8314 .onClick(() => { 8315 try { 8316 this.controller.startDownload('www.example.com'); 8317 } catch (error) { 8318 let e:business_error.BusinessError = error as business_error.BusinessError; 8319 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8320 } 8321 }) 8322 Web({ src: 'www.example.com', controller: this.controller }) 8323 } 8324 } 8325} 8326``` 8327 8328### getCurrentSpeed<sup>11+</sup> 8329 8330getCurrentSpeed(): number 8331 8332Obtains the download speed, in bytes per second. 8333 8334**System capability**: SystemCapability.Web.Webview.Core 8335 8336**Return value** 8337 8338| Type | Description | 8339| ------ | ------------------------- | 8340| number | Download speed, in bytes per second.| 8341 8342**Example** 8343 8344```ts 8345// xxx.ets 8346import web_webview from '@ohos.web.webview' 8347import business_error from '@ohos.base' 8348 8349@Entry 8350@Component 8351struct WebComponent { 8352 controller: web_webview.WebviewController = new web_webview.WebviewController(); 8353 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 8354 8355 build() { 8356 Column() { 8357 Button('setDownloadDelegate') 8358 .onClick(() => { 8359 try { 8360 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 8361 console.log("will start a download."); 8362 // Pass in a download path and start the download. 8363 webDownloadItem.start("xxxxxxxx"); 8364 }) 8365 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 8366 console.log("download update current speed: " + webDownloadItem.getCurrentSpeed()); 8367 }) 8368 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 8369 console.log("download failed guid: " + webDownloadItem.getGuid()); 8370 }) 8371 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 8372 console.log("download finish guid: " + webDownloadItem.getGuid()); 8373 }) 8374 this.controller.setDownloadDelegate(this.delegate); 8375 } catch (error) { 8376 let e:business_error.BusinessError = error as business_error.BusinessError; 8377 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8378 } 8379 }) 8380 Button('startDownload') 8381 .onClick(() => { 8382 try { 8383 this.controller.startDownload('www.example.com'); 8384 } catch (error) { 8385 let e:business_error.BusinessError = error as business_error.BusinessError; 8386 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8387 } 8388 }) 8389 Web({ src: 'www.example.com', controller: this.controller }) 8390 } 8391 } 8392} 8393``` 8394 8395### getPercentComplete<sup>11+</sup> 8396 8397getPercentComplete(): number 8398 8399Obtains the download progress. The value **100** indicates that the download is complete. 8400 8401**System capability**: SystemCapability.Web.Webview.Core 8402 8403**Return value** 8404 8405| Type | Description | 8406| ------ | ------------------------- | 8407| number | Download progress. The value **100** indicates that the download is complete.| 8408 8409**Example** 8410 8411```ts 8412// xxx.ets 8413import web_webview from '@ohos.web.webview' 8414import business_error from '@ohos.base' 8415 8416@Entry 8417@Component 8418struct WebComponent { 8419 controller: web_webview.WebviewController = new web_webview.WebviewController(); 8420 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 8421 8422 build() { 8423 Column() { 8424 Button('setDownloadDelegate') 8425 .onClick(() => { 8426 try { 8427 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 8428 console.log("will start a download."); 8429 // Pass in a download path and start the download. 8430 webDownloadItem.start("xxxxxxxx"); 8431 }) 8432 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 8433 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 8434 }) 8435 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 8436 console.log("download failed guid: " + webDownloadItem.getGuid()); 8437 }) 8438 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 8439 console.log("download finish guid: " + webDownloadItem.getGuid()); 8440 }) 8441 this.controller.setDownloadDelegate(this.delegate); 8442 } catch (error) { 8443 let e:business_error.BusinessError = error as business_error.BusinessError; 8444 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8445 } 8446 }) 8447 Button('startDownload') 8448 .onClick(() => { 8449 try { 8450 this.controller.startDownload('www.example.com'); 8451 } catch (error) { 8452 let e:business_error.BusinessError = error as business_error.BusinessError; 8453 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8454 } 8455 }) 8456 Web({ src: 'www.example.com', controller: this.controller }) 8457 } 8458 } 8459} 8460``` 8461 8462### getTotalBytes<sup>11+</sup> 8463 8464getTotalBytes(): number 8465 8466Obtains the total length of the file to be downloaded. 8467 8468**System capability**: SystemCapability.Web.Webview.Core 8469 8470**Return value** 8471 8472| Type | Description | 8473| ------ | ------------------------- | 8474| number | Total length of the file to be downloaded.| 8475 8476**Example** 8477 8478```ts 8479// xxx.ets 8480import web_webview from '@ohos.web.webview' 8481import business_error from '@ohos.base' 8482 8483@Entry 8484@Component 8485struct WebComponent { 8486 controller: web_webview.WebviewController = new web_webview.WebviewController(); 8487 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 8488 8489 build() { 8490 Column() { 8491 Button('setDownloadDelegate') 8492 .onClick(() => { 8493 try { 8494 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 8495 console.log("will start a download."); 8496 // Pass in a download path and start the download. 8497 webDownloadItem.start("xxxxxxxx"); 8498 }) 8499 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 8500 console.log("download update total bytes: " + webDownloadItem.getTotalBytes()); 8501 }) 8502 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 8503 console.log("download failed guid: " + webDownloadItem.getGuid()); 8504 }) 8505 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 8506 console.log("download finish guid: " + webDownloadItem.getGuid()); 8507 }) 8508 this.controller.setDownloadDelegate(this.delegate); 8509 } catch (error) { 8510 let e:business_error.BusinessError = error as business_error.BusinessError; 8511 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8512 } 8513 }) 8514 Button('startDownload') 8515 .onClick(() => { 8516 try { 8517 this.controller.startDownload('www.example.com'); 8518 } catch (error) { 8519 let e:business_error.BusinessError = error as business_error.BusinessError; 8520 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8521 } 8522 }) 8523 Web({ src: 'www.example.com', controller: this.controller }) 8524 } 8525 } 8526} 8527``` 8528 8529### getState<sup>11+</sup> 8530 8531getState(): WebDownloadState 8532 8533Obtains the download state. 8534 8535**System capability**: SystemCapability.Web.Webview.Core 8536 8537**Return value** 8538 8539| Type | Description | 8540| ------ | ------------------------- | 8541| [WebDownloadState](#webdownloadstate11) | Download state.| 8542 8543**Example** 8544 8545```ts 8546// xxx.ets 8547import web_webview from '@ohos.web.webview' 8548import business_error from '@ohos.base' 8549 8550@Entry 8551@Component 8552struct WebComponent { 8553 controller: web_webview.WebviewController = new web_webview.WebviewController(); 8554 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 8555 8556 build() { 8557 Column() { 8558 Button('setDownloadDelegate') 8559 .onClick(() => { 8560 try { 8561 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 8562 console.log("will start a download."); 8563 // Pass in a download path and start the download. 8564 webDownloadItem.start("xxxxxxxx"); 8565 }) 8566 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 8567 console.log("download update download state: " + webDownloadItem.getState()); 8568 }) 8569 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 8570 console.log("download failed guid: " + webDownloadItem.getGuid()); 8571 }) 8572 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 8573 console.log("download finish guid: " + webDownloadItem.getGuid()); 8574 }) 8575 this.controller.setDownloadDelegate(this.delegate); 8576 } catch (error) { 8577 let e:business_error.BusinessError = error as business_error.BusinessError; 8578 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8579 } 8580 }) 8581 Button('startDownload') 8582 .onClick(() => { 8583 try { 8584 this.controller.startDownload('www.example.com'); 8585 } catch (error) { 8586 let e:business_error.BusinessError = error as business_error.BusinessError; 8587 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8588 } 8589 }) 8590 Web({ src: 'www.example.com', controller: this.controller }) 8591 } 8592 } 8593} 8594``` 8595 8596### getLastErrorCode<sup>11+</sup> 8597 8598getLastErrorCode(): WebDownloadErrorCode 8599 8600Obtains the download error code. 8601 8602**System capability**: SystemCapability.Web.Webview.Core 8603 8604**Return value** 8605 8606| Type | Description | 8607| ------ | ------------------------- | 8608| number | Error code returned when the download error occurs.| 8609 8610**Example** 8611 8612```ts 8613// xxx.ets 8614import web_webview from '@ohos.web.webview' 8615import business_error from '@ohos.base' 8616 8617@Entry 8618@Component 8619struct WebComponent { 8620 controller: web_webview.WebviewController = new web_webview.WebviewController(); 8621 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 8622 8623 build() { 8624 Column() { 8625 Button('setDownloadDelegate') 8626 .onClick(() => { 8627 try { 8628 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 8629 console.log("will start a download."); 8630 // Pass in a download path and start the download. 8631 webDownloadItem.start("xxxxxxxx"); 8632 }) 8633 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 8634 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 8635 }) 8636 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 8637 console.log("download failed guid: " + webDownloadItem.getGuid()); 8638 console.log("download error code: " + webDownloadItem.getLastErrorCode()); 8639 }) 8640 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 8641 console.log("download finish guid: " + webDownloadItem.getGuid()); 8642 }) 8643 this.controller.setDownloadDelegate(this.delegate); 8644 } catch (error) { 8645 let e:business_error.BusinessError = error as business_error.BusinessError; 8646 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8647 } 8648 }) 8649 Button('startDownload') 8650 .onClick(() => { 8651 try { 8652 this.controller.startDownload('www.example.com'); 8653 } catch (error) { 8654 let e:business_error.BusinessError = error as business_error.BusinessError; 8655 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8656 } 8657 }) 8658 Web({ src: 'www.example.com', controller: this.controller }) 8659 } 8660 } 8661} 8662``` 8663 8664### getMethod<sup>11+</sup> 8665 8666getMethod(): string 8667 8668Obtains the request mode of this download task. 8669 8670**System capability**: SystemCapability.Web.Webview.Core 8671 8672**Return value** 8673 8674| Type | Description | 8675| ------ | ------------------------- | 8676| string | Request mode of the download task.| 8677 8678**Example** 8679 8680```ts 8681// xxx.ets 8682import web_webview from '@ohos.web.webview' 8683import business_error from '@ohos.base' 8684 8685@Entry 8686@Component 8687struct WebComponent { 8688 controller: web_webview.WebviewController = new web_webview.WebviewController(); 8689 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 8690 8691 build() { 8692 Column() { 8693 Button('setDownloadDelegate') 8694 .onClick(() => { 8695 try { 8696 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 8697 console.log("Download will start. Method:" + webDownloadItem.getMethod()); 8698 // Pass in a download path and start the download. 8699 webDownloadItem.start("xxxxxxxx"); 8700 }) 8701 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 8702 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 8703 }) 8704 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 8705 console.log("download failed guid: " + webDownloadItem.getGuid()); 8706 }) 8707 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 8708 console.log("download finish guid: " + webDownloadItem.getGuid()); 8709 }) 8710 this.controller.setDownloadDelegate(this.delegate); 8711 } catch (error) { 8712 let e:business_error.BusinessError = error as business_error.BusinessError; 8713 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8714 } 8715 }) 8716 Button('startDownload') 8717 .onClick(() => { 8718 try { 8719 this.controller.startDownload('www.example.com'); 8720 } catch (error) { 8721 let e:business_error.BusinessError = error as business_error.BusinessError; 8722 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8723 } 8724 }) 8725 Web({ src: 'www.example.com', controller: this.controller }) 8726 } 8727 } 8728} 8729``` 8730 8731### getMimeType<sup>11+</sup> 8732 8733getMimeType(): string 8734 8735Obtains the MIME type of this download task (for example, a sound file may be marked as audio/ogg, and an image file may be image/png). 8736 8737**System capability**: SystemCapability.Web.Webview.Core 8738 8739**Return value** 8740 8741| Type | Description | 8742| ------ | ------------------------- | 8743| string | MIME type (for example, audio/ogg for a sound file, and image/png for an image file).| 8744 8745**Example** 8746 8747```ts 8748// xxx.ets 8749import web_webview from '@ohos.web.webview' 8750import business_error from '@ohos.base' 8751 8752@Entry 8753@Component 8754struct WebComponent { 8755 controller: web_webview.WebviewController = new web_webview.WebviewController(); 8756 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 8757 8758 build() { 8759 Column() { 8760 Button('setDownloadDelegate') 8761 .onClick(() => { 8762 try { 8763 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 8764 console.log("Download will start. MIME type:" + webDownloadItem.getMimeType()); 8765 // Pass in a download path and start the download. 8766 webDownloadItem.start("xxxxxxxx"); 8767 }) 8768 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 8769 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 8770 }) 8771 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 8772 console.log("download failed guid: " + webDownloadItem.getGuid()); 8773 }) 8774 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 8775 console.log("download finish guid: " + webDownloadItem.getGuid()); 8776 }) 8777 this.controller.setDownloadDelegate(this.delegate); 8778 } catch (error) { 8779 let e:business_error.BusinessError = error as business_error.BusinessError; 8780 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8781 } 8782 }) 8783 Button('startDownload') 8784 .onClick(() => { 8785 try { 8786 this.controller.startDownload('www.example.com'); 8787 } catch (error) { 8788 let e:business_error.BusinessError = error as business_error.BusinessError; 8789 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8790 } 8791 }) 8792 Web({ src: 'www.example.com', controller: this.controller }) 8793 } 8794 } 8795} 8796``` 8797 8798### getUrl<sup>11+</sup> 8799 8800getUrl(): string 8801 8802Obtains the download request URL. 8803 8804**System capability**: SystemCapability.Web.Webview.Core 8805 8806**Return value** 8807 8808| Type | Description | 8809| ------ | ------------------------- | 8810| string | Download request URL.| 8811 8812**Example** 8813 8814```ts 8815// xxx.ets 8816import web_webview from '@ohos.web.webview' 8817import business_error from '@ohos.base' 8818 8819@Entry 8820@Component 8821struct WebComponent { 8822 controller: web_webview.WebviewController = new web_webview.WebviewController(); 8823 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 8824 8825 build() { 8826 Column() { 8827 Button('setDownloadDelegate') 8828 .onClick(() => { 8829 try { 8830 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 8831 console.log("will start a download, url:" + webDownloadItem.getUrl()); 8832 // Pass in a download path and start the download. 8833 webDownloadItem.start("xxxxxxxx"); 8834 }) 8835 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 8836 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 8837 }) 8838 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 8839 console.log("download failed guid: " + webDownloadItem.getGuid()); 8840 }) 8841 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 8842 console.log("download finish guid: " + webDownloadItem.getGuid()); 8843 }) 8844 this.controller.setDownloadDelegate(this.delegate); 8845 } catch (error) { 8846 let e:business_error.BusinessError = error as business_error.BusinessError; 8847 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8848 } 8849 }) 8850 Button('startDownload') 8851 .onClick(() => { 8852 try { 8853 this.controller.startDownload('www.example.com'); 8854 } catch (error) { 8855 let e:business_error.BusinessError = error as business_error.BusinessError; 8856 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8857 } 8858 }) 8859 Web({ src: 'www.example.com', controller: this.controller }) 8860 } 8861 } 8862} 8863``` 8864 8865### getSuggestedFileName<sup>11+</sup> 8866 8867getSuggestedFileName(): string 8868 8869Obtains the suggested file name for this download task. 8870 8871**System capability**: SystemCapability.Web.Webview.Core 8872 8873**Return value** 8874 8875| Type | Description | 8876| ------ | ------------------------- | 8877| string | Suggested file name.| 8878 8879**Example** 8880 8881```ts 8882// xxx.ets 8883import web_webview from '@ohos.web.webview' 8884import business_error from '@ohos.base' 8885 8886@Entry 8887@Component 8888struct WebComponent { 8889 controller: web_webview.WebviewController = new web_webview.WebviewController(); 8890 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 8891 8892 build() { 8893 Column() { 8894 Button('setDownloadDelegate') 8895 .onClick(() => { 8896 try { 8897 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 8898 console.log("will start a download, suggest name:" + webDownloadItem.getSuggestedFileName()); 8899 // Pass in a download path and start the download. 8900 webDownloadItem.start("xxxxxxxx"); 8901 }) 8902 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 8903 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 8904 }) 8905 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 8906 console.log("download failed guid: " + webDownloadItem.getGuid()); 8907 }) 8908 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 8909 console.log("download finish guid: " + webDownloadItem.getGuid()); 8910 }) 8911 this.controller.setDownloadDelegate(this.delegate); 8912 } catch (error) { 8913 let e:business_error.BusinessError = error as business_error.BusinessError; 8914 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8915 } 8916 }) 8917 Button('startDownload') 8918 .onClick(() => { 8919 try { 8920 this.controller.startDownload('www.example.com'); 8921 } catch (error) { 8922 let e:business_error.BusinessError = error as business_error.BusinessError; 8923 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8924 } 8925 }) 8926 Web({ src: 'www.example.com', controller: this.controller }) 8927 } 8928 } 8929} 8930``` 8931 8932### getReceivedBytes<sup>11+</sup> 8933 8934getReceivedBytes(): number 8935 8936Obtains the number of received bytes. 8937 8938**System capability**: SystemCapability.Web.Webview.Core 8939 8940**Return value** 8941 8942| Type | Description | 8943| ------ | ------------------------- | 8944| number | Number of received bytes.| 8945 8946**Example** 8947 8948```ts 8949// xxx.ets 8950import web_webview from '@ohos.web.webview' 8951import business_error from '@ohos.base' 8952 8953@Entry 8954@Component 8955struct WebComponent { 8956 controller: web_webview.WebviewController = new web_webview.WebviewController(); 8957 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 8958 8959 build() { 8960 Column() { 8961 Button('setDownloadDelegate') 8962 .onClick(() => { 8963 try { 8964 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 8965 console.log("will start a download."); 8966 // Pass in a download path and start the download. 8967 webDownloadItem.start("xxxxxxxx"); 8968 }) 8969 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 8970 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 8971 console.log("download update received bytes: " + webDownloadItem.getReceivedBytes()); 8972 }) 8973 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 8974 console.log("download failed guid: " + webDownloadItem.getGuid()); 8975 }) 8976 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 8977 console.log("download finish guid: " + webDownloadItem.getGuid()); 8978 }) 8979 this.controller.setDownloadDelegate(this.delegate); 8980 } catch (error) { 8981 let e:business_error.BusinessError = error as business_error.BusinessError; 8982 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8983 } 8984 }) 8985 Button('startDownload') 8986 .onClick(() => { 8987 try { 8988 this.controller.startDownload('www.example.com'); 8989 } catch (error) { 8990 let e:business_error.BusinessError = error as business_error.BusinessError; 8991 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 8992 } 8993 }) 8994 Web({ src: 'www.example.com', controller: this.controller }) 8995 } 8996 } 8997} 8998``` 8999 9000### getFullPath<sup>11+</sup> 9001 9002getFullPath(): string 9003 9004Obtains the full path of the downloaded file on the disk. 9005 9006**System capability**: SystemCapability.Web.Webview.Core 9007 9008**Return value** 9009 9010| Type | Description | 9011| ------ | ------------------------- | 9012| string | Full path of the downloaded file on the disk.| 9013 9014**Example** 9015 9016```ts 9017// xxx.ets 9018import web_webview from '@ohos.web.webview' 9019import business_error from '@ohos.base' 9020 9021@Entry 9022@Component 9023struct WebComponent { 9024 controller: web_webview.WebviewController = new web_webview.WebviewController(); 9025 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 9026 9027 build() { 9028 Column() { 9029 Button('setDownloadDelegate') 9030 .onClick(() => { 9031 try { 9032 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 9033 console.log("will start a download."); 9034 // Pass in a download path and start the download. 9035 webDownloadItem.start("xxxxxxxx"); 9036 }) 9037 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 9038 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 9039 }) 9040 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 9041 console.log("download failed guid: " + webDownloadItem.getGuid()); 9042 }) 9043 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 9044 console.log("download finish guid: " + webDownloadItem.getGuid()); 9045 console.log("download finish full path: " + webDownloadItem.getFullPath()); 9046 }) 9047 this.controller.setDownloadDelegate(this.delegate); 9048 } catch (error) { 9049 let e:business_error.BusinessError = error as business_error.BusinessError; 9050 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9051 } 9052 }) 9053 Button('startDownload') 9054 .onClick(() => { 9055 try { 9056 this.controller.startDownload('www.example.com'); 9057 } catch (error) { 9058 let e:business_error.BusinessError = error as business_error.BusinessError; 9059 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9060 } 9061 }) 9062 Web({ src: 'www.example.com', controller: this.controller }) 9063 } 9064 } 9065} 9066``` 9067 9068### serialize<sup>11+</sup> 9069 9070serialize(): Uint8Array 9071 9072Serializes the failed download to a byte array. 9073 9074**System capability**: SystemCapability.Web.Webview.Core 9075 9076**Return value** 9077 9078| Type | Description | 9079| ------ | ------------------------- | 9080| Uint8Array | Byte array into which the failed download is serialized.| 9081 9082**Example** 9083 9084```ts 9085// xxx.ets 9086import web_webview from '@ohos.web.webview' 9087import business_error from '@ohos.base' 9088 9089@Entry 9090@Component 9091struct WebComponent { 9092 controller: web_webview.WebviewController = new web_webview.WebviewController(); 9093 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 9094 failedData: Uint8Array = new Uint8Array(); 9095 9096 build() { 9097 Column() { 9098 Button('setDownloadDelegate') 9099 .onClick(() => { 9100 try { 9101 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 9102 console.log("will start a download."); 9103 // Pass in a download path and start the download. 9104 webDownloadItem.start("xxxxxxxx"); 9105 }) 9106 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 9107 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 9108 }) 9109 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 9110 console.log("download failed guid: " + webDownloadItem.getGuid()); 9111 // Serialize the failed download to a byte array. 9112 this.failedData = webDownloadItem.serialize(); 9113 }) 9114 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 9115 console.log("download finish guid: " + webDownloadItem.getGuid()); 9116 }) 9117 this.controller.setDownloadDelegate(this.delegate); 9118 } catch (error) { 9119 let e:business_error.BusinessError = error as business_error.BusinessError; 9120 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9121 } 9122 }) 9123 Button('startDownload') 9124 .onClick(() => { 9125 try { 9126 this.controller.startDownload('www.example.com'); 9127 } catch (error) { 9128 let e:business_error.BusinessError = error as business_error.BusinessError; 9129 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9130 } 9131 }) 9132 Web({ src: 'www.example.com', controller: this.controller }) 9133 } 9134 } 9135} 9136``` 9137 9138### deserialize<sup>11+</sup> 9139 9140static deserialize(serializedData: Uint8Array): WebDownloadItem 9141 9142Deserializes the serialized byte array into a **WebDownloadItem** object. 9143 9144**System capability**: SystemCapability.Web.Webview.Core 9145 9146**Parameters** 9147 9148| Name | Type | Mandatory | Description| 9149| ------------------ | ------- | ---- | ------------- | 9150| serializedData | Uint8Array | Yes | Byte array into which the download is serialized.| 9151 9152**Return value** 9153 9154| Type | Description | 9155| ------ | ------------------------- | 9156| [WebDownloadItem](#webdownloaditem11) | **WebDownloadItem** object.| 9157 9158**Example** 9159 9160```ts 9161// xxx.ets 9162import web_webview from '@ohos.web.webview' 9163import business_error from '@ohos.base' 9164 9165@Entry 9166@Component 9167struct WebComponent { 9168 controller: web_webview.WebviewController = new web_webview.WebviewController(); 9169 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 9170 failedData: Uint8Array = new Uint8Array(); 9171 9172 build() { 9173 Column() { 9174 Button('setDownloadDelegate') 9175 .onClick(() => { 9176 try { 9177 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 9178 console.log("will start a download."); 9179 // Pass in a download path and start the download. 9180 webDownloadItem.start("xxxxxxxx"); 9181 }) 9182 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 9183 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 9184 }) 9185 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 9186 console.log("download failed guid: " + webDownloadItem.getGuid()); 9187 // Serialize the failed download to a byte array. 9188 this.failedData = webDownloadItem.serialize(); 9189 }) 9190 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 9191 console.log("download finish guid: " + webDownloadItem.getGuid()); 9192 }) 9193 this.controller.setDownloadDelegate(this.delegate); 9194 } catch (error) { 9195 let e:business_error.BusinessError = error as business_error.BusinessError; 9196 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9197 } 9198 }) 9199 Button('startDownload') 9200 .onClick(() => { 9201 try { 9202 this.controller.startDownload('www.example.com'); 9203 } catch (error) { 9204 let e:business_error.BusinessError = error as business_error.BusinessError; 9205 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9206 } 9207 }) 9208 Button('resumeDownload') 9209 .onClick(() => { 9210 try { 9211 web_webview.WebDownloadManager.resumeDownload(web_webview.WebDownloadItem.deserialize(this.failedData)); 9212 } catch (error) { 9213 let e:business_error.BusinessError = error as business_error.BusinessError; 9214 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9215 } 9216 }) 9217 Web({ src: 'www.example.com', controller: this.controller }) 9218 } 9219 } 9220} 9221``` 9222 9223### start<sup>11+</sup> 9224 9225start(downloadPath: string): void 9226 9227Starts a download. This API must be used in the **onBeforeDownload** callback of **WebDownloadDelegate**. If it is not called in the callback, the download task remains in the PENDING state. 9228 9229**System capability**: SystemCapability.Web.Webview.Core 9230 9231**Parameters** 9232 9233| Name| Type | Mandatory| Description | 9234| ------ | ---------------------- | ---- | ------------------------------| 9235| downloadPath | string | Yes | Path (including the file name) of the file to download.| 9236 9237**Example** 9238 9239```ts 9240// xxx.ets 9241import web_webview from '@ohos.web.webview' 9242import business_error from '@ohos.base' 9243 9244@Entry 9245@Component 9246struct WebComponent { 9247 controller: web_webview.WebviewController = new web_webview.WebviewController(); 9248 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 9249 failedData: Uint8Array = new Uint8Array(); 9250 9251 build() { 9252 Column() { 9253 Button('setDownloadDelegate') 9254 .onClick(() => { 9255 try { 9256 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 9257 console.log("will start a download."); 9258 // Pass in a download path and start the download. 9259 webDownloadItem.start("xxxxxxxx"); 9260 }) 9261 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 9262 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 9263 }) 9264 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 9265 console.log("download failed guid: " + webDownloadItem.getGuid()); 9266 // Serialize the failed download to a byte array. 9267 this.failedData = webDownloadItem.serialize(); 9268 }) 9269 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 9270 console.log("download finish guid: " + webDownloadItem.getGuid()); 9271 }) 9272 this.controller.setDownloadDelegate(this.delegate); 9273 } catch (error) { 9274 let e:business_error.BusinessError = error as business_error.BusinessError; 9275 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9276 } 9277 }) 9278 Button('startDownload') 9279 .onClick(() => { 9280 try { 9281 this.controller.startDownload('www.example.com'); 9282 } catch (error) { 9283 let e:business_error.BusinessError = error as business_error.BusinessError; 9284 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9285 } 9286 }) 9287 Button('resumeDownload') 9288 .onClick(() => { 9289 try { 9290 web_webview.WebDownloadManager.resumeDownload(web_webview.WebDownloadItem.deserialize(this.failedData)); 9291 } catch (error) { 9292 let e:business_error.BusinessError = error as business_error.BusinessError; 9293 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9294 } 9295 }) 9296 Web({ src: 'www.example.com', controller: this.controller }) 9297 } 9298 } 9299} 9300``` 9301 9302### cancel<sup>11+</sup> 9303 9304cancel(): void 9305 9306Cancels a download task. 9307 9308**System capability**: SystemCapability.Web.Webview.Core 9309 9310**Example** 9311 9312```ts 9313// xxx.ets 9314import web_webview from '@ohos.web.webview' 9315import business_error from '@ohos.base' 9316 9317@Entry 9318@Component 9319struct WebComponent { 9320 controller: web_webview.WebviewController = new web_webview.WebviewController(); 9321 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 9322 download: web_webview.WebDownloadItem = new web_webview.WebDownloadItem(); 9323 failedData: Uint8Array = new Uint8Array(); 9324 9325 build() { 9326 Column() { 9327 Button('setDownloadDelegate') 9328 .onClick(() => { 9329 try { 9330 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 9331 console.log("will start a download."); 9332 // Pass in a download path and start the download. 9333 webDownloadItem.start("xxxxxxxx"); 9334 }) 9335 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 9336 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 9337 this.download = webDownloadItem; 9338 }) 9339 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 9340 console.log("download failed guid: " + webDownloadItem.getGuid()); 9341 // Serialize the failed download to a byte array. 9342 this.failedData = webDownloadItem.serialize(); 9343 }) 9344 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 9345 console.log("download finish guid: " + webDownloadItem.getGuid()); 9346 }) 9347 this.controller.setDownloadDelegate(this.delegate); 9348 } catch (error) { 9349 let e:business_error.BusinessError = error as business_error.BusinessError; 9350 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9351 } 9352 }) 9353 Button('startDownload') 9354 .onClick(() => { 9355 try { 9356 this.controller.startDownload('www.example.com'); 9357 } catch (error) { 9358 let e:business_error.BusinessError = error as business_error.BusinessError; 9359 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9360 } 9361 }) 9362 Button('resumeDownload') 9363 .onClick(() => { 9364 try { 9365 web_webview.WebDownloadManager.resumeDownload(web_webview.WebDownloadItem.deserialize(this.failedData)); 9366 } catch (error) { 9367 let e:business_error.BusinessError = error as business_error.BusinessError; 9368 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9369 } 9370 }) 9371 Button('cancel') 9372 .onClick(() => { 9373 try { 9374 this.download.cancel(); 9375 } catch (error) { 9376 let e:business_error.BusinessError = error as business_error.BusinessError; 9377 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9378 } 9379 }) 9380 Web({ src: 'www.example.com', controller: this.controller }) 9381 } 9382 } 9383} 9384``` 9385 9386### pause<sup>11+</sup> 9387 9388pause(): void 9389 9390Pauses a download task. 9391 9392**System capability**: SystemCapability.Web.Webview.Core 9393 9394**Error codes** 9395 9396For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 9397 9398| ID | Error Message | 9399| -------- | ------------------------------------------------------------ | 9400| 17100019 | The download has not been started yet. | 9401 9402**Example** 9403 9404```ts 9405// xxx.ets 9406import web_webview from '@ohos.web.webview' 9407import business_error from '@ohos.base' 9408 9409@Entry 9410@Component 9411struct WebComponent { 9412 controller: web_webview.WebviewController = new web_webview.WebviewController(); 9413 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 9414 download: web_webview.WebDownloadItem = new web_webview.WebDownloadItem(); 9415 failedData: Uint8Array = new Uint8Array(); 9416 9417 build() { 9418 Column() { 9419 Button('setDownloadDelegate') 9420 .onClick(() => { 9421 try { 9422 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 9423 console.log("will start a download."); 9424 // Pass in a download path and start the download. 9425 webDownloadItem.start("xxxxxxxx"); 9426 }) 9427 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 9428 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 9429 this.download = webDownloadItem; 9430 }) 9431 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 9432 console.log("download failed guid: " + webDownloadItem.getGuid()); 9433 // Serialize the failed download to a byte array. 9434 this.failedData = webDownloadItem.serialize(); 9435 }) 9436 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 9437 console.log("download finish guid: " + webDownloadItem.getGuid()); 9438 }) 9439 this.controller.setDownloadDelegate(this.delegate); 9440 } catch (error) { 9441 let e:business_error.BusinessError = error as business_error.BusinessError; 9442 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9443 } 9444 }) 9445 Button('startDownload') 9446 .onClick(() => { 9447 try { 9448 this.controller.startDownload('www.example.com'); 9449 } catch (error) { 9450 let e:business_error.BusinessError = error as business_error.BusinessError; 9451 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9452 } 9453 }) 9454 Button('resumeDownload') 9455 .onClick(() => { 9456 try { 9457 web_webview.WebDownloadManager.resumeDownload(web_webview.WebDownloadItem.deserialize(this.failedData)); 9458 } catch (error) { 9459 let e:business_error.BusinessError = error as business_error.BusinessError; 9460 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9461 } 9462 }) 9463 Button('cancel') 9464 .onClick(() => { 9465 try { 9466 this.download.cancel(); 9467 } catch (error) { 9468 let e:business_error.BusinessError = error as business_error.BusinessError; 9469 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9470 } 9471 }) 9472 Button('pause') 9473 .onClick(() => { 9474 try { 9475 this.download.pause(); 9476 } catch (error) { 9477 let e:business_error.BusinessError = error as business_error.BusinessError; 9478 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9479 } 9480 }) 9481 Web({ src: 'www.example.com', controller: this.controller }) 9482 } 9483 } 9484} 9485``` 9486 9487### resume<sup>11+</sup> 9488 9489resume(): void 9490 9491Resumes a download task. 9492 9493**System capability**: SystemCapability.Web.Webview.Core 9494 9495**Error codes** 9496 9497For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 9498 9499| ID | Error Message | 9500| -------- | ------------------------------------------------------------ | 9501| 17100016 | The download is not paused. | 9502 9503**Example** 9504 9505```ts 9506// xxx.ets 9507import web_webview from '@ohos.web.webview' 9508import business_error from '@ohos.base' 9509 9510@Entry 9511@Component 9512struct WebComponent { 9513 controller: web_webview.WebviewController = new web_webview.WebviewController(); 9514 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 9515 download: web_webview.WebDownloadItem = new web_webview.WebDownloadItem(); 9516 failedData: Uint8Array = new Uint8Array(); 9517 9518 build() { 9519 Column() { 9520 Button('setDownloadDelegate') 9521 .onClick(() => { 9522 try { 9523 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 9524 console.log("will start a download."); 9525 // Pass in a download path and start the download. 9526 webDownloadItem.start("xxxxxxxx"); 9527 }) 9528 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 9529 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 9530 this.download = webDownloadItem; 9531 }) 9532 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 9533 console.log("download failed guid: " + webDownloadItem.getGuid()); 9534 // Serialize the failed download to a byte array. 9535 this.failedData = webDownloadItem.serialize(); 9536 }) 9537 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 9538 console.log("download finish guid: " + webDownloadItem.getGuid()); 9539 }) 9540 this.controller.setDownloadDelegate(this.delegate); 9541 } catch (error) { 9542 let e:business_error.BusinessError = error as business_error.BusinessError; 9543 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9544 } 9545 }) 9546 Button('startDownload') 9547 .onClick(() => { 9548 try { 9549 this.controller.startDownload('www.example.com'); 9550 } catch (error) { 9551 let e:business_error.BusinessError = error as business_error.BusinessError; 9552 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9553 } 9554 }) 9555 Button('resumeDownload') 9556 .onClick(() => { 9557 try { 9558 web_webview.WebDownloadManager.resumeDownload(web_webview.WebDownloadItem.deserialize(this.failedData)); 9559 } catch (error) { 9560 let e:business_error.BusinessError = error as business_error.BusinessError; 9561 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9562 } 9563 }) 9564 Button('cancel') 9565 .onClick(() => { 9566 try { 9567 this.download.cancel(); 9568 } catch (error) { 9569 let e:business_error.BusinessError = error as business_error.BusinessError; 9570 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9571 } 9572 }) 9573 Button('pause') 9574 .onClick(() => { 9575 try { 9576 this.download.pause(); 9577 } catch (error) { 9578 let e:business_error.BusinessError = error as business_error.BusinessError; 9579 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9580 } 9581 }) 9582 Button('resume') 9583 .onClick(() => { 9584 try { 9585 this.download.resume(); 9586 } catch (error) { 9587 let e:business_error.BusinessError = error as business_error.BusinessError; 9588 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9589 } 9590 }) 9591 Web({ src: 'www.example.com', controller: this.controller }) 9592 } 9593 } 9594} 9595``` 9596 9597## WebDownloadDelegate<sup>11+</sup> 9598 9599 Implements a **WebDownloadDelegate** class. You can use the callbacks of this class to notify users of the download state. 9600 9601### onBeforeDownload<sup>11+</sup> 9602 9603onBeforeDownload(callback: Callback\<WebDownloadItem>): void 9604 9605Invoked to notify users before the download starts. **WebDownloadItem.start("xxx")** must be called in this API, with a download path provided. Otherwise, the download remains in the PENDING state. 9606 9607**System capability**: SystemCapability.Web.Webview.Core 9608 9609**Example** 9610 9611```ts 9612// xxx.ets 9613import web_webview from '@ohos.web.webview' 9614import business_error from '@ohos.base' 9615 9616@Entry 9617@Component 9618struct WebComponent { 9619 controller: web_webview.WebviewController = new web_webview.WebviewController(); 9620 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 9621 download: web_webview.WebDownloadItem = new web_webview.WebDownloadItem(); 9622 failedData: Uint8Array = new Uint8Array(); 9623 9624 build() { 9625 Column() { 9626 Button('setDownloadDelegate') 9627 .onClick(() => { 9628 try { 9629 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 9630 console.log("will start a download."); 9631 // Pass in a download path and start the download. 9632 webDownloadItem.start("xxxxxxxx"); 9633 }) 9634 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 9635 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 9636 this.download = webDownloadItem; 9637 }) 9638 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 9639 console.log("download failed guid: " + webDownloadItem.getGuid()); 9640 // Serialize the failed download to a byte array. 9641 this.failedData = webDownloadItem.serialize(); 9642 }) 9643 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 9644 console.log("download finish guid: " + webDownloadItem.getGuid()); 9645 }) 9646 this.controller.setDownloadDelegate(this.delegate); 9647 } catch (error) { 9648 let e:business_error.BusinessError = error as business_error.BusinessError; 9649 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9650 } 9651 }) 9652 Button('startDownload') 9653 .onClick(() => { 9654 try { 9655 this.controller.startDownload('www.example.com'); 9656 } catch (error) { 9657 let e:business_error.BusinessError = error as business_error.BusinessError; 9658 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9659 } 9660 }) 9661 Button('resumeDownload') 9662 .onClick(() => { 9663 try { 9664 web_webview.WebDownloadManager.resumeDownload(web_webview.WebDownloadItem.deserialize(this.failedData)); 9665 } catch (error) { 9666 let e:business_error.BusinessError = error as business_error.BusinessError; 9667 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9668 } 9669 }) 9670 Button('cancel') 9671 .onClick(() => { 9672 try { 9673 this.download.cancel(); 9674 } catch (error) { 9675 let e:business_error.BusinessError = error as business_error.BusinessError; 9676 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9677 } 9678 }) 9679 Button('pause') 9680 .onClick(() => { 9681 try { 9682 this.download.pause(); 9683 } catch (error) { 9684 let e:business_error.BusinessError = error as business_error.BusinessError; 9685 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9686 } 9687 }) 9688 Button('resume') 9689 .onClick(() => { 9690 try { 9691 this.download.resume(); 9692 } catch (error) { 9693 let e:business_error.BusinessError = error as business_error.BusinessError; 9694 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9695 } 9696 }) 9697 Web({ src: 'www.example.com', controller: this.controller }) 9698 } 9699 } 9700} 9701``` 9702 9703### onDownloadUpdated<sup>11+</sup> 9704 9705onDownloadUpdated(callback: Callback\<WebDownloadItem>): void 9706 9707Invoked when the download progress is updated. 9708 9709**System capability**: SystemCapability.Web.Webview.Core 9710 9711**Example** 9712 9713```ts 9714// xxx.ets 9715import web_webview from '@ohos.web.webview' 9716import business_error from '@ohos.base' 9717 9718@Entry 9719@Component 9720struct WebComponent { 9721 controller: web_webview.WebviewController = new web_webview.WebviewController(); 9722 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 9723 download: web_webview.WebDownloadItem = new web_webview.WebDownloadItem(); 9724 failedData: Uint8Array = new Uint8Array(); 9725 9726 build() { 9727 Column() { 9728 Button('setDownloadDelegate') 9729 .onClick(() => { 9730 try { 9731 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 9732 console.log("will start a download."); 9733 // Pass in a download path and start the download. 9734 webDownloadItem.start("xxxxxxxx"); 9735 }) 9736 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 9737 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 9738 this.download = webDownloadItem; 9739 }) 9740 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 9741 console.log("download failed guid: " + webDownloadItem.getGuid()); 9742 // Serialize the failed download to a byte array. 9743 this.failedData = webDownloadItem.serialize(); 9744 }) 9745 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 9746 console.log("download finish guid: " + webDownloadItem.getGuid()); 9747 }) 9748 this.controller.setDownloadDelegate(this.delegate); 9749 } catch (error) { 9750 let e:business_error.BusinessError = error as business_error.BusinessError; 9751 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9752 } 9753 }) 9754 Button('startDownload') 9755 .onClick(() => { 9756 try { 9757 this.controller.startDownload('www.example.com'); 9758 } catch (error) { 9759 let e:business_error.BusinessError = error as business_error.BusinessError; 9760 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9761 } 9762 }) 9763 Button('resumeDownload') 9764 .onClick(() => { 9765 try { 9766 web_webview.WebDownloadManager.resumeDownload(web_webview.WebDownloadItem.deserialize(this.failedData)); 9767 } catch (error) { 9768 let e:business_error.BusinessError = error as business_error.BusinessError; 9769 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9770 } 9771 }) 9772 Button('cancel') 9773 .onClick(() => { 9774 try { 9775 this.download.cancel(); 9776 } catch (error) { 9777 let e:business_error.BusinessError = error as business_error.BusinessError; 9778 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9779 } 9780 }) 9781 Button('pause') 9782 .onClick(() => { 9783 try { 9784 this.download.pause(); 9785 } catch (error) { 9786 let e:business_error.BusinessError = error as business_error.BusinessError; 9787 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9788 } 9789 }) 9790 Button('resume') 9791 .onClick(() => { 9792 try { 9793 this.download.resume(); 9794 } catch (error) { 9795 let e:business_error.BusinessError = error as business_error.BusinessError; 9796 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9797 } 9798 }) 9799 Web({ src: 'www.example.com', controller: this.controller }) 9800 } 9801 } 9802} 9803``` 9804 9805### onDownloadFinish<sup>11+</sup> 9806 9807onDownloadFinish(callback: Callback\<WebDownloadItem>): void 9808 9809Invoked when the download is complete. 9810 9811**System capability**: SystemCapability.Web.Webview.Core 9812 9813**Example** 9814 9815```ts 9816// xxx.ets 9817import web_webview from '@ohos.web.webview' 9818import business_error from '@ohos.base' 9819 9820@Entry 9821@Component 9822struct WebComponent { 9823 controller: web_webview.WebviewController = new web_webview.WebviewController(); 9824 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 9825 download: web_webview.WebDownloadItem = new web_webview.WebDownloadItem(); 9826 failedData: Uint8Array = new Uint8Array(); 9827 9828 build() { 9829 Column() { 9830 Button('setDownloadDelegate') 9831 .onClick(() => { 9832 try { 9833 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 9834 console.log("will start a download."); 9835 // Pass in a download path and start the download. 9836 webDownloadItem.start("xxxxxxxx"); 9837 }) 9838 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 9839 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 9840 this.download = webDownloadItem; 9841 }) 9842 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 9843 console.log("download failed guid: " + webDownloadItem.getGuid()); 9844 // Serialize the failed download to a byte array. 9845 this.failedData = webDownloadItem.serialize(); 9846 }) 9847 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 9848 console.log("download finish guid: " + webDownloadItem.getGuid()); 9849 }) 9850 this.controller.setDownloadDelegate(this.delegate); 9851 } catch (error) { 9852 let e:business_error.BusinessError = error as business_error.BusinessError; 9853 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9854 } 9855 }) 9856 Button('startDownload') 9857 .onClick(() => { 9858 try { 9859 this.controller.startDownload('www.example.com'); 9860 } catch (error) { 9861 let e:business_error.BusinessError = error as business_error.BusinessError; 9862 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9863 } 9864 }) 9865 Button('resumeDownload') 9866 .onClick(() => { 9867 try { 9868 web_webview.WebDownloadManager.resumeDownload(web_webview.WebDownloadItem.deserialize(this.failedData)); 9869 } catch (error) { 9870 let e:business_error.BusinessError = error as business_error.BusinessError; 9871 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9872 } 9873 }) 9874 Button('cancel') 9875 .onClick(() => { 9876 try { 9877 this.download.cancel(); 9878 } catch (error) { 9879 let e:business_error.BusinessError = error as business_error.BusinessError; 9880 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9881 } 9882 }) 9883 Button('pause') 9884 .onClick(() => { 9885 try { 9886 this.download.pause(); 9887 } catch (error) { 9888 let e:business_error.BusinessError = error as business_error.BusinessError; 9889 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9890 } 9891 }) 9892 Button('resume') 9893 .onClick(() => { 9894 try { 9895 this.download.resume(); 9896 } catch (error) { 9897 let e:business_error.BusinessError = error as business_error.BusinessError; 9898 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9899 } 9900 }) 9901 Web({ src: 'www.example.com', controller: this.controller }) 9902 } 9903 } 9904} 9905``` 9906 9907### onDownloadFailed<sup>11+</sup> 9908 9909onDownloadFailed(callback: Callback\<WebDownloadItem>): void 9910 9911Invoked when the download fails. 9912 9913**System capability**: SystemCapability.Web.Webview.Core 9914 9915**Example** 9916 9917```ts 9918// xxx.ets 9919import web_webview from '@ohos.web.webview' 9920import business_error from '@ohos.base' 9921 9922@Entry 9923@Component 9924struct WebComponent { 9925 controller: web_webview.WebviewController = new web_webview.WebviewController(); 9926 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 9927 download: web_webview.WebDownloadItem = new web_webview.WebDownloadItem(); 9928 failedData: Uint8Array = new Uint8Array(); 9929 9930 build() { 9931 Column() { 9932 Button('setDownloadDelegate') 9933 .onClick(() => { 9934 try { 9935 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 9936 console.log("will start a download."); 9937 // Pass in a download path and start the download. 9938 webDownloadItem.start("xxxxxxxx"); 9939 }) 9940 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 9941 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 9942 this.download = webDownloadItem; 9943 }) 9944 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 9945 console.log("download failed guid: " + webDownloadItem.getGuid()); 9946 // Serialize the failed download to a byte array. 9947 this.failedData = webDownloadItem.serialize(); 9948 }) 9949 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 9950 console.log("download finish guid: " + webDownloadItem.getGuid()); 9951 }) 9952 this.controller.setDownloadDelegate(this.delegate); 9953 } catch (error) { 9954 let e:business_error.BusinessError = error as business_error.BusinessError; 9955 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9956 } 9957 }) 9958 Button('startDownload') 9959 .onClick(() => { 9960 try { 9961 this.controller.startDownload('www.example.com'); 9962 } catch (error) { 9963 let e:business_error.BusinessError = error as business_error.BusinessError; 9964 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9965 } 9966 }) 9967 Button('resumeDownload') 9968 .onClick(() => { 9969 try { 9970 web_webview.WebDownloadManager.resumeDownload(web_webview.WebDownloadItem.deserialize(this.failedData)); 9971 } catch (error) { 9972 let e:business_error.BusinessError = error as business_error.BusinessError; 9973 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9974 } 9975 }) 9976 Button('cancel') 9977 .onClick(() => { 9978 try { 9979 this.download.cancel(); 9980 } catch (error) { 9981 let e:business_error.BusinessError = error as business_error.BusinessError; 9982 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9983 } 9984 }) 9985 Button('pause') 9986 .onClick(() => { 9987 try { 9988 this.download.pause(); 9989 } catch (error) { 9990 let e:business_error.BusinessError = error as business_error.BusinessError; 9991 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 9992 } 9993 }) 9994 Button('resume') 9995 .onClick(() => { 9996 try { 9997 this.download.resume(); 9998 } catch (error) { 9999 let e:business_error.BusinessError = error as business_error.BusinessError; 10000 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 10001 } 10002 }) 10003 Web({ src: 'www.example.com', controller: this.controller }) 10004 } 10005 } 10006} 10007``` 10008 10009## WebDownloadManager<sup>11+</sup> 10010 10011Implements a **WebDownloadManager** class. You can use the APIs of this class to resume failed download tasks. 10012 10013### setDownloadDelegate<sup>11+</sup> 10014 10015static setDownloadDelegate(delegate: WebDownloadDelegate): void 10016 10017Sets the delegate used to receive download progress triggered from **WebDownloadManager**. 10018 10019**System capability**: SystemCapability.Web.Webview.Core 10020 10021**Parameters** 10022 10023| Name | Type | Mandatory | Description | 10024| ---------------| ------- | ---- | ------------- | 10025| delegate | [WebDownloadDelegate](#webdownloaddelegate11) | Yes | Delegate used to receive the download progress.| 10026 10027**Example** 10028 10029```ts 10030// xxx.ets 10031import web_webview from '@ohos.web.webview' 10032import business_error from '@ohos.base' 10033 10034@Entry 10035@Component 10036struct WebComponent { 10037 controller: web_webview.WebviewController = new web_webview.WebviewController(); 10038 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 10039 download: web_webview.WebDownloadItem = new web_webview.WebDownloadItem(); 10040 failedData: Uint8Array = new Uint8Array(); 10041 10042 build() { 10043 Column() { 10044 Button('setDownloadDelegate') 10045 .onClick(() => { 10046 try { 10047 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 10048 console.log("will start a download."); 10049 // Pass in a download path and start the download. 10050 webDownloadItem.start("xxxxxxxx"); 10051 }) 10052 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 10053 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 10054 this.download = webDownloadItem; 10055 }) 10056 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 10057 console.log("download failed guid: " + webDownloadItem.getGuid()); 10058 // Serialize the failed download to a byte array. 10059 this.failedData = webDownloadItem.serialize(); 10060 }) 10061 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 10062 console.log("download finish guid: " + webDownloadItem.getGuid()); 10063 }) 10064 this.controller.setDownloadDelegate(this.delegate); 10065 } catch (error) { 10066 let e:business_error.BusinessError = error as business_error.BusinessError; 10067 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 10068 } 10069 }) 10070 Button('startDownload') 10071 .onClick(() => { 10072 try { 10073 this.controller.startDownload('www.example.com'); 10074 } catch (error) { 10075 let e:business_error.BusinessError = error as business_error.BusinessError; 10076 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 10077 } 10078 }) 10079 Button('resumeDownload') 10080 .onClick(() => { 10081 try { 10082 web_webview.WebDownloadManager.resumeDownload(web_webview.WebDownloadItem.deserialize(this.failedData)); 10083 } catch (error) { 10084 let e:business_error.BusinessError = error as business_error.BusinessError; 10085 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 10086 } 10087 }) 10088 Button('cancel') 10089 .onClick(() => { 10090 try { 10091 this.download.cancel(); 10092 } catch (error) { 10093 let e:business_error.BusinessError = error as business_error.BusinessError; 10094 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 10095 } 10096 }) 10097 Button('pause') 10098 .onClick(() => { 10099 try { 10100 this.download.pause(); 10101 } catch (error) { 10102 let e:business_error.BusinessError = error as business_error.BusinessError; 10103 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 10104 } 10105 }) 10106 Button('resume') 10107 .onClick(() => { 10108 try { 10109 this.download.resume(); 10110 } catch (error) { 10111 let e:business_error.BusinessError = error as business_error.BusinessError; 10112 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 10113 } 10114 }) 10115 Web({ src: 'www.example.com', controller: this.controller }) 10116 } 10117 } 10118} 10119``` 10120 10121### resumeDownload<sup>11+</sup> 10122 10123static resumeDownload(webDownloadItem: WebDownloadItem): void 10124 10125Resumes a download task. 10126 10127**System capability**: SystemCapability.Web.Webview.Core 10128 10129**Parameters** 10130 10131| Name | Type | Mandatory | Description | 10132| ---------------| ------- | ---- | ------------- | 10133| webDownloadItem | [WebDownloadItem](#webdownloaditem11) | Yes | Download task to resume.| 10134 10135**Error codes** 10136 10137For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). 10138 10139| ID| Error Message | 10140| -------- | ------------------------------------- | 10141| 17100018 | No WebDownloadDelegate has been set yet. | 10142 10143**Example** 10144 10145```ts 10146// xxx.ets 10147import web_webview from '@ohos.web.webview' 10148import business_error from '@ohos.base' 10149 10150@Entry 10151@Component 10152struct WebComponent { 10153 controller: web_webview.WebviewController = new web_webview.WebviewController(); 10154 delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); 10155 download: web_webview.WebDownloadItem = new web_webview.WebDownloadItem(); 10156 failedData: Uint8Array = new Uint8Array(); 10157 10158 build() { 10159 Column() { 10160 Button('setDownloadDelegate') 10161 .onClick(() => { 10162 try { 10163 this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { 10164 console.log("will start a download."); 10165 // Pass in a download path and start the download. 10166 webDownloadItem.start("xxxxxxxx"); 10167 }) 10168 this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { 10169 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 10170 this.download = webDownloadItem; 10171 }) 10172 this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { 10173 console.log("download failed guid: " + webDownloadItem.getGuid()); 10174 // Serialize the failed download to a byte array. 10175 this.failedData = webDownloadItem.serialize(); 10176 }) 10177 this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { 10178 console.log("download finish guid: " + webDownloadItem.getGuid()); 10179 }) 10180 this.controller.setDownloadDelegate(this.delegate); 10181 } catch (error) { 10182 let e:business_error.BusinessError = error as business_error.BusinessError; 10183 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 10184 } 10185 }) 10186 Button('startDownload') 10187 .onClick(() => { 10188 try { 10189 this.controller.startDownload('www.example.com'); 10190 } catch (error) { 10191 let e:business_error.BusinessError = error as business_error.BusinessError; 10192 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 10193 } 10194 }) 10195 Button('resumeDownload') 10196 .onClick(() => { 10197 try { 10198 web_webview.WebDownloadManager.resumeDownload(web_webview.WebDownloadItem.deserialize(this.failedData)); 10199 } catch (error) { 10200 let e:business_error.BusinessError = error as business_error.BusinessError; 10201 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 10202 } 10203 }) 10204 Button('cancel') 10205 .onClick(() => { 10206 try { 10207 this.download.cancel(); 10208 } catch (error) { 10209 let e:business_error.BusinessError = error as business_error.BusinessError; 10210 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 10211 } 10212 }) 10213 Button('pause') 10214 .onClick(() => { 10215 try { 10216 this.download.pause(); 10217 } catch (error) { 10218 let e:business_error.BusinessError = error as business_error.BusinessError; 10219 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 10220 } 10221 }) 10222 Button('resume') 10223 .onClick(() => { 10224 try { 10225 this.download.resume(); 10226 } catch (error) { 10227 let e:business_error.BusinessError = error as business_error.BusinessError; 10228 console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); 10229 } 10230 }) 10231 Web({ src: 'www.example.com', controller: this.controller }) 10232 } 10233 } 10234} 10235``` 10236 10237