1# @ohos.web.webview (Webview) 2 3The **Webview** module provides APIs for web control. It can work with the [Web](ts-basic-components-web.md) component, which is used to display web pages. 4 5> **NOTE** 6> 7> - 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. 8> 9> - You can preview how this component looks on a real device, but not in DevEco Studio Previewer. 10 11## Required Permissions 12 13**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). 14 15## Modules to Import 16 17```ts 18import { webview } from '@kit.ArkWeb'; 19``` 20 21## once 22 23once(type: string, callback: Callback\<void\>): void 24 25Registers a one-time callback for web events of the specified type. 26 27**System capability**: SystemCapability.Web.Webview.Core 28 29**Parameters** 30 31| Name | Type | Mandatory| Description | 32| ------- | ---------------- | ---- | -------------------- | 33| type | string | Yes | Web event type. The value can be **"webInited"**, indicating completion of web initialization. | 34| callback | Callback\<void\> | Yes | Callback to register.| 35 36**Error codes** 37 38For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 39 40| ID| Error Message | 41| -------- | ----------------------- | 42| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 43 44**Example** 45 46```ts 47// xxx.ets 48import { webview } from '@kit.ArkWeb'; 49 50webview.once("webInited", () => { 51 console.log("configCookieSync"); 52 webview.WebCookieManager.configCookieSync("https://www.example.com", "a=b"); 53}) 54 55@Entry 56@Component 57struct WebComponent { 58 controller: webview.WebviewController = new webview.WebviewController(); 59 60 build() { 61 Column() { 62 Web({ src: 'www.example.com', controller: this.controller }) 63 } 64 } 65} 66``` 67 68## WebMessagePort 69 70Implements a **WebMessagePort** object to send and receive messages. 71 72### postMessageEvent 73 74postMessageEvent(message: WebMessage): void 75 76Sends a message. You must call [onMessageEvent](#onmessageevent) at first. Otherwise, the message fails to be sent. For the complete sample code, see [postMessage](#postmessage). 77 78**System capability**: SystemCapability.Web.Webview.Core 79 80**Parameters** 81 82| Name | Type | Mandatory| Description | 83| ------- | ------ | ---- | :------------- | 84| message | [WebMessage](#webmessage) | Yes | Message to send.| 85 86**Error codes** 87 88For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 89 90| ID| Error Message | 91| -------- | ------------------------------------- | 92| 17100010 | Failed to post messages through the port. | 93| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 94 95**Example** 96 97```ts 98// xxx.ets 99import { webview } from '@kit.ArkWeb'; 100import { BusinessError } from '@kit.BasicServicesKit'; 101 102@Entry 103@Component 104struct WebComponent { 105 controller: webview.WebviewController = new webview.WebviewController(); 106 ports: webview.WebMessagePort[] = []; 107 108 build() { 109 Column() { 110 Button('postMessageEvent') 111 .onClick(() => { 112 try { 113 this.ports = this.controller.createWebMessagePorts(); 114 this.controller.postMessage('__init_port__', [this.ports[0]], '*'); 115 this.ports[1].postMessageEvent("post message from ets to html5"); 116 } catch (error) { 117 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 118 } 119 }) 120 Web({ src: 'www.example.com', controller: this.controller }) 121 } 122 } 123} 124``` 125 126### onMessageEvent 127 128onMessageEvent(callback: (result: WebMessage) => void): void 129 130Registers a callback to receive messages from the HTML side. For the complete sample code, see [postMessage](#postmessage). 131 132**System capability**: SystemCapability.Web.Webview.Core 133 134**Parameters** 135 136| Name | Type | Mandatory| Description | 137| -------- | -------- | ---- | :------------------- | 138| callback | (result: [WebMessage](#webmessage)) => void | Yes | Message received.| 139 140**Error codes** 141 142For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 143 144| ID| Error Message | 145| -------- | ----------------------------------------------- | 146| 17100006 | Failed to register a message event for the port.| 147| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.| 148 149**Example** 150 151```ts 152// xxx.ets 153import { webview } from '@kit.ArkWeb'; 154import { BusinessError } from '@kit.BasicServicesKit'; 155 156@Entry 157@Component 158struct WebComponent { 159 controller: webview.WebviewController = new webview.WebviewController(); 160 ports: webview.WebMessagePort[] = []; 161 162 build() { 163 Column() { 164 Button('onMessageEvent') 165 .onClick(() => { 166 try { 167 this.ports = this.controller.createWebMessagePorts(); 168 this.ports[1].onMessageEvent((msg) => { 169 if (typeof (msg) == "string") { 170 console.log("received string message from html5, string is:" + msg); 171 } else if (typeof (msg) == "object") { 172 if (msg instanceof ArrayBuffer) { 173 console.log("received arraybuffer from html5, length is:" + msg.byteLength); 174 } else { 175 console.log("not support"); 176 } 177 } else { 178 console.log("not support"); 179 } 180 }) 181 } catch (error) { 182 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 183 } 184 }) 185 Web({ src: 'www.example.com', controller: this.controller }) 186 } 187 } 188} 189``` 190 191### isExtentionType<sup>10+</sup> 192 193**System capability**: SystemCapability.Web.Webview.Core 194 195| Name | Type | Readable| Writable| Description | 196| ------------ | ------ | ---- | ---- | ------------------------------------------------| 197| isExtentionType | boolean | Yes | Yes| Whether to use the extended interface when creating a **WebMessagePort** instance. | 198 199### postMessageEventExt<sup>10+</sup> 200 201postMessageEventExt(message: WebMessageExt): void 202 203Sends a message. You must call [onMessageEventExt](#onmessageeventext10) at first. Otherwise, the message fails to be sent. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 204 205**System capability**: SystemCapability.Web.Webview.Core 206 207**Parameters** 208 209| Name | Type | Mandatory| Description | 210| ------- | ------ | ---- | :------------- | 211| message | [WebMessageExt](#webmessageext10) | Yes | Message to send.| 212 213**Error codes** 214 215For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 216 217| ID| Error Message | 218| -------- | ------------------------------------- | 219| 17100010 | Failed to post messages through the port. | 220| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 221 222### onMessageEventExt<sup>10+</sup> 223 224onMessageEventExt(callback: (result: WebMessageExt) => void): void 225 226Registers a callback to receive messages from the HTML5 side. 227 228**System capability**: SystemCapability.Web.Webview.Core 229 230**Parameters** 231 232| Name | Type | Mandatory| Description | 233| -------- | -------- | ---- | :------------------- | 234| callback | (result: [WebMessageExt](#webmessageext10)) => void | Yes | Message received.| 235 236**Error codes** 237 238For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 239 240| ID| Error Message | 241| -------- | ----------------------------------------------- | 242| 17100006 | Failed to register a message event for the port. | 243| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 244 245**Example** 246 247```ts 248// xxx.ets 249import { webview } from '@kit.ArkWeb'; 250import { BusinessError } from '@kit.BasicServicesKit'; 251 252class TestObj { 253 test(str: string): ArrayBuffer { 254 let buf = new ArrayBuffer(str.length); 255 let buff = new Uint8Array(buf); 256 257 for (let i = 0; i < str.length; i++) { 258 buff[i] = str.charCodeAt(i); 259 } 260 return buf; 261 } 262} 263 264// 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. 265@Entry 266@Component 267struct WebComponent { 268 controller: webview.WebviewController = new webview.WebviewController(); 269 ports: webview.WebMessagePort[] = []; 270 nativePort: webview.WebMessagePort | null = null; 271 @State msg1: string = ""; 272 @State msg2: string = ""; 273 message: webview.WebMessageExt = new webview.WebMessageExt(); 274 @State testObjtest: TestObj = new TestObj(); 275 276 build() { 277 Column() { 278 Text(this.msg1).fontSize(16) 279 Text(this.msg2).fontSize(16) 280 Button('SendToH5 setString').margin({ 281 right: 800, 282 }) 283 .onClick(() => { 284 // Use the local port to send messages to HTML5. 285 try { 286 console.log("In ArkTS side send true start"); 287 if (this.nativePort) { 288 this.message.setType(1); 289 this.message.setString("helloFromEts"); 290 this.nativePort.postMessageEventExt(this.message); 291 } 292 } 293 catch (error) { 294 console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 295 } 296 }) 297 Button('SendToH5 setNumber').margin({ 298 top: 10, 299 right: 800, 300 }) 301 .onClick(() => { 302 // Use the local port to send messages to HTML5. 303 try { 304 console.log("In ArkTS side send true start"); 305 if (this.nativePort) { 306 this.message.setType(2); 307 this.message.setNumber(12345); 308 this.nativePort.postMessageEventExt(this.message); 309 } 310 } 311 catch (error) { 312 console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 313 } 314 }) 315 Button('SendToH5 setBoolean').margin({ 316 top: -90, 317 }) 318 .onClick(() => { 319 // Use the local port to send messages to HTML5. 320 try { 321 console.log("In ArkTS side send true start"); 322 if (this.nativePort) { 323 this.message.setType(3); 324 this.message.setBoolean(true); 325 this.nativePort.postMessageEventExt(this.message); 326 } 327 } 328 catch (error) { 329 console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 330 } 331 }) 332 Button('SendToH5 setArrayBuffer').margin({ 333 top: 10, 334 }) 335 .onClick(() => { 336 // Use the local port to send messages to HTML5. 337 try { 338 console.log("In ArkTS side send true start"); 339 if (this.nativePort) { 340 this.message.setType(4); 341 this.message.setArrayBuffer(this.testObjtest.test("Name=test&Password=test")); 342 this.nativePort.postMessageEventExt(this.message); 343 } 344 } 345 catch (error) { 346 console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 347 } 348 }) 349 Button('SendToH5 setArray').margin({ 350 top: -90, 351 left: 800, 352 }) 353 .onClick(() => { 354 // Use the local port to send messages to HTML5. 355 try { 356 console.log("In ArkTS side send true start"); 357 if (this.nativePort) { 358 this.message.setType(5); 359 this.message.setArray([1, 2, 3]); 360 this.nativePort.postMessageEventExt(this.message); 361 } 362 } 363 catch (error) { 364 console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 365 } 366 }) 367 Button('SendToH5 setError').margin({ 368 top: 10, 369 left: 800, 370 }) 371 .onClick(() => { 372 // Use the local port to send messages to HTML5. 373 try { 374 console.log("In ArkTS side send true start"); 375 throw new ReferenceError("ReferenceError"); 376 } 377 catch (error) { 378 if (this.nativePort) { 379 this.message.setType(6); 380 this.message.setError(error); 381 this.nativePort.postMessageEventExt(this.message); 382 } 383 console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 384 } 385 }) 386 387 Web({ src: $rawfile('index.html'), controller: this.controller }) 388 .onPageEnd(() => { 389 console.log("In ArkTS side message onPageEnd init message channel"); 390 // 1. Create a message port. 391 this.ports = this.controller.createWebMessagePorts(true); 392 // 2. Send port 1 to HTML5. 393 this.controller.postMessage("init_web_messageport", [this.ports[1]], "*"); 394 // 3. Save port 0 to the local host. 395 this.nativePort = this.ports[0]; 396 // 4. Set the callback. 397 this.nativePort.onMessageEventExt((result) => { 398 console.log("In ArkTS side got message"); 399 try { 400 let type = result.getType(); 401 console.log("In ArkTS side getType:" + type); 402 switch (type) { 403 case webview.WebMessageType.STRING: { 404 this.msg1 = "result type:" + typeof (result.getString()); 405 this.msg2 = "result getString:" + ((result.getString())); 406 break; 407 } 408 case webview.WebMessageType.NUMBER: { 409 this.msg1 = "result type:" + typeof (result.getNumber()); 410 this.msg2 = "result getNumber:" + ((result.getNumber())); 411 break; 412 } 413 case webview.WebMessageType.BOOLEAN: { 414 this.msg1 = "result type:" + typeof (result.getBoolean()); 415 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 416 break; 417 } 418 case webview.WebMessageType.ARRAY_BUFFER: { 419 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 420 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 421 break; 422 } 423 case webview.WebMessageType.ARRAY: { 424 this.msg1 = "result type:" + typeof (result.getArray()); 425 this.msg2 = "result getArray:" + result.getArray(); 426 break; 427 } 428 case webview.WebMessageType.ERROR: { 429 this.msg1 = "result type:" + typeof (result.getError()); 430 this.msg2 = "result getError:" + result.getError(); 431 break; 432 } 433 default: { 434 this.msg1 = "default break, type:" + type; 435 break; 436 } 437 } 438 } 439 catch (error) { 440 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 441 } 442 }); 443 }) 444 } 445 } 446} 447``` 448 449HTML file to be loaded: 450```html 451<!--index.html--> 452<!DOCTYPE html> 453<html lang="en-gb"> 454<head> 455 <title>WebView MessagePort Demo</title> 456</head> 457 458<body> 459<h1>Html5 Send and Receive Message</h1> 460<h3 id="msg">Receive string:</h3> 461<h3 id="msg2">Receive arraybuffer:</h3> 462<div style="font-size: 10pt; text-align: center;"> 463 <input type="button" value="Send String" onclick="postStringToApp();" /><br/> 464</div> 465</body> 466<script src="index.js"></script> 467</html> 468``` 469 470```js 471//index.js 472var h5Port; 473window.addEventListener('message', function(event) { 474 if (event.data == 'init_web_messageport') { 475 if(event.ports[0] != null) { 476 h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side. 477 h5Port.onmessage = function(event) { 478 console.log("hwd In html got message"); 479 // 2. Receive the message sent from the eTS side. 480 var result = event.data; 481 console.log("In html got message, typeof: ", typeof(result)); 482 console.log("In html got message, result: ", (result)); 483 if (typeof(result) == "string") { 484 console.log("In html got message, String: ", result); 485 document.getElementById("msg").innerHTML = "String:" + result; 486 } else if (typeof(result) == "number") { 487 console.log("In html side got message, number: ", result); 488 document.getElementById("msg").innerHTML = "Number:" + result; 489 } else if (typeof(result) == "boolean") { 490 console.log("In html side got message, boolean: ", result); 491 document.getElementById("msg").innerHTML = "Boolean:" + result; 492 } else if (typeof(result) == "object") { 493 if (result instanceof ArrayBuffer) { 494 document.getElementById("msg2").innerHTML = "ArrayBuffer:" + result.byteLength; 495 console.log("In html got message, byteLength: ", result.byteLength); 496 } else if (result instanceof Error) { 497 console.log("In html error message, err:" + (result)); 498 console.log("In html error message, typeof err:" + typeof(result)); 499 document.getElementById("msg2").innerHTML = "Error:" + result.name + ", msg:" + result.message; 500 } else if (result instanceof Array) { 501 console.log("In html got message, Array"); 502 console.log("In html got message, Array length:" + result.length); 503 console.log("In html got message, Array[0]:" + (result[0])); 504 console.log("In html got message, typeof Array[0]:" + typeof(result[0])); 505 document.getElementById("msg2").innerHTML = "Array len:" + result.length + ", value:" + result; 506 } else { 507 console.log("In html got message, not any instance of support type"); 508 document.getElementById("msg").innerHTML = "not any instance of support type"; 509 } 510 } else { 511 console.log("In html got message, not support type"); 512 document.getElementById("msg").innerHTML = "not support type"; 513 } 514 } 515 h5Port.onmessageerror = (event) => { 516 console.error(`hwd In html Error receiving message: ${event}`); 517 }; 518 } 519 } 520}) 521 522// Use h5Port to send a message of the string type to the ets side. 523function postStringToApp() { 524 if (h5Port) { 525 console.log("In html send string message"); 526 h5Port.postMessage("hello"); 527 console.log("In html send string message end"); 528 } else { 529 console.error("In html h5port is null, please init first"); 530 } 531} 532``` 533 534### close 535 536close(): void 537 538Closes this message port. To use this API, a message port must first be created using [createWebMessagePorts](#createwebmessageports). 539 540**System capability**: SystemCapability.Web.Webview.Core 541 542**Example** 543 544```ts 545// xxx.ets 546import { webview } from '@kit.ArkWeb'; 547import { BusinessError } from '@kit.BasicServicesKit'; 548 549@Entry 550@Component 551struct WebComponent { 552 controller: webview.WebviewController = new webview.WebviewController(); 553 msgPort: webview.WebMessagePort[] = []; 554 555 build() { 556 Column() { 557 // Use createWebMessagePorts to create a message port. 558 Button('createWebMessagePorts') 559 .onClick(() => { 560 try { 561 this.msgPort = this.controller.createWebMessagePorts(); 562 console.log("createWebMessagePorts size:" + this.msgPort.length) 563 } catch (error) { 564 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 565 } 566 }) 567 Button('close') 568 .onClick(() => { 569 try { 570 if (this.msgPort && this.msgPort.length == 2) { 571 this.msgPort[1].close(); 572 } else { 573 console.error("msgPort is null, Please initialize first"); 574 } 575 } catch (error) { 576 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 577 } 578 }) 579 Web({ src: 'www.example.com', controller: this.controller }) 580 } 581 } 582} 583``` 584 585## WebviewController 586 587Implements 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. 588 589### constructor<sup>11+</sup> 590 591constructor(webTag?: string) 592 593Constructor used to create a **WebviewController** object. 594 595> **NOTE** 596> 597> **webTag** represents a tag that you define and pass to the **Web** component as a parameter of string type. 598 599**System capability**: SystemCapability.Web.Webview.Core 600 601**Parameters** 602 603| Name | Type | Mandatory| Description | 604| ---------- | ------ | ---- | -------------------------------- | 605| webTag | string | No | Name of the **Web** component. The default value is **Empty**.| 606 607**Example** 608 609```ts 610// xxx.ets 611import { webview } from '@kit.ArkWeb'; 612import { BusinessError } from '@kit.BasicServicesKit'; 613 614class WebObj { 615 constructor() { 616 } 617 618 webTest(): string { 619 console.log('Web test'); 620 return "Web test"; 621 } 622 623 webString(): void { 624 console.log('Web test toString'); 625 } 626} 627 628@Entry 629@Component 630struct WebComponent { 631 controller: webview.WebviewController = new webview.WebviewController() 632 @State webTestObj: WebObj = new WebObj(); 633 634 build() { 635 Column() { 636 Button('refresh') 637 .onClick(() => { 638 try { 639 this.controller.refresh(); 640 } catch (error) { 641 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 642 } 643 }) 644 Web({ src: '', controller: this.controller }) 645 .javaScriptAccess(true) 646 .onControllerAttached(() => { 647 this.controller.loadUrl($rawfile("index.html")); 648 this.controller.registerJavaScriptProxy(this.webTestObj, "objTestName", ["webTest", "webString"]); 649 }) 650 } 651 } 652} 653``` 654 655HTML file to be loaded: 656```html 657<!-- index.html --> 658<!DOCTYPE html> 659<html> 660 <meta charset="utf-8"> 661 <body> 662 <button type="button" onclick="htmlTest()">Click Me!</button> 663 <p id="demo"></p> 664 <p id="webDemo"></p> 665 </body> 666 <script type="text/javascript"> 667 function htmlTest() { 668 // This function call expects to return "Web test" 669 let webStr = objTestName.webTest(); 670 document.getElementById("webDemo").innerHTML=webStr; 671 console.log('objTestName.webTest result:'+ webStr) 672 } 673</script> 674</html> 675``` 676 677### initializeWebEngine 678 679static initializeWebEngine(): void 680 681Loads 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. 682 683> **NOTE** 684> 685> - **initializeWebEngine** cannot be called in an asynchronous thread. Otherwise, the system breaks down. 686> - **initializeWebEngine** takes effect globally and needs to be called only once in an application lifecycle. 687 688**System capability**: SystemCapability.Web.Webview.Core 689 690**Example** 691 692The following code snippet exemplifies calling this API after the EntryAbility is created. 693 694```ts 695// xxx.ets 696import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 697import { webview } from '@kit.ArkWeb'; 698 699export default class EntryAbility extends UIAbility { 700 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 701 console.log("EntryAbility onCreate") 702 webview.WebviewController.initializeWebEngine() 703 console.log("EntryAbility onCreate done") 704 } 705} 706``` 707 708### setHttpDns<sup>10+</sup> 709 710static setHttpDns(secureDnsMode:SecureDnsMode, secureDnsConfig:string): void 711 712Sets how the Web component uses HTTPDNS for DNS resolution. 713 714**System capability**: SystemCapability.Web.Webview.Core 715 716**Parameters** 717 718| Name | Type | Mandatory | Description| 719| ------------------ | ------- | ---- | ------------- | 720| secureDnsMode | [SecureDnsMode](#securednsmode10) | Yes | Mode in which HTTPDNS is used.| 721| secureDnsConfig | string | Yes| Information about the HTTPDNS server to use, which must use HTTPS. Only one HTTPDNS server can be configured.| 722 723**Error codes** 724 725For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 726 727| ID| Error Message | 728| -------- | ----------------------- | 729| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 730 731**Example** 732 733```ts 734// xxx.ets 735import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 736import { webview } from '@kit.ArkWeb'; 737import { BusinessError } from '@kit.BasicServicesKit'; 738 739export default class EntryAbility extends UIAbility { 740 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 741 console.log("EntryAbility onCreate") 742 try { 743 webview.WebviewController.setHttpDns(webview.SecureDnsMode.AUTO, "https://example1.test") 744 } catch (error) { 745 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 746 } 747 748 AppStorage.setOrCreate("abilityWant", want); 749 console.log("EntryAbility onCreate done") 750 } 751} 752``` 753 754### setWebDebuggingAccess 755 756static setWebDebuggingAccess(webDebuggingAccess: boolean): void 757 758Sets whether to enable web debugging. By default, web debugging is disabled. For details, see [Debugging Frontend Pages by Using DevTools](../../web/web-debugging-with-devtools.md). 759 760NOTE: Enabling web debugging allows users to check and modify the internal status of the web page, which poses security risks. Therefore, you are advised not to enable this function in the officially released version of the app. 761 762**System capability**: SystemCapability.Web.Webview.Core 763 764**Parameters** 765 766| Name | Type | Mandatory | Description| 767| ------------------ | ------- | ---- | ------------- | 768| webDebuggingAccess | boolean | Yes | Sets whether to enable web debugging.| 769 770**Error codes** 771 772For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 773 774| ID | Error Message | 775| -------- | ------------------------------------------------------------ | 776| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 777 778**Example** 779 780```ts 781// xxx.ets 782import { webview } from '@kit.ArkWeb'; 783import { BusinessError } from '@kit.BasicServicesKit'; 784 785@Entry 786@Component 787struct WebComponent { 788 controller: webview.WebviewController = new webview.WebviewController(); 789 790 aboutToAppear(): void { 791 try { 792 webview.WebviewController.setWebDebuggingAccess(true); 793 } catch (error) { 794 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 795 } 796 } 797 798 build() { 799 Column() { 800 Web({ src: 'www.example.com', controller: this.controller }) 801 } 802 } 803} 804``` 805 806### loadUrl 807 808loadUrl(url: string | Resource, headers?: Array\<WebHeader>): void 809 810Loads a specified URL. 811 812**System capability**: SystemCapability.Web.Webview.Core 813 814**Parameters** 815 816| Name | Type | Mandatory| Description | 817| ------- | ---------------- | ---- | :-------------------- | 818| url | string \| Resource | Yes | URL to load. | 819| headers | Array\<[WebHeader](#webheader)> | No | Additional HTTP request header of the URL.| 820 821**Error codes** 822 823For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 824 825| ID| Error Message | 826| -------- | ------------------------------------------------------------ | 827| 17100001 | Init error. The WebviewController must be associated with a Web component. | 828| 17100002 | Invalid url. | 829| 17100003 | Invalid resource path or file type. | 830| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 831 832**Example** 833 834```ts 835// xxx.ets 836import { webview } from '@kit.ArkWeb'; 837import { BusinessError } from '@kit.BasicServicesKit'; 838 839@Entry 840@Component 841struct WebComponent { 842 controller: webview.WebviewController = new webview.WebviewController(); 843 844 build() { 845 Column() { 846 Button('loadUrl') 847 .onClick(() => { 848 try { 849 // The URL to be loaded is of the string type. 850 this.controller.loadUrl('www.example.com'); 851 } catch (error) { 852 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 853 } 854 }) 855 Web({ src: 'www.example.com', controller: this.controller }) 856 } 857 } 858} 859``` 860 861```ts 862// xxx.ets 863import { webview } from '@kit.ArkWeb'; 864import { BusinessError } from '@kit.BasicServicesKit'; 865 866@Entry 867@Component 868struct WebComponent { 869 controller: webview.WebviewController = new webview.WebviewController(); 870 871 build() { 872 Column() { 873 Button('loadUrl') 874 .onClick(() => { 875 try { 876 // The headers parameter is passed. 877 this.controller.loadUrl('www.example.com', [{ headerKey: "headerKey", headerValue: "headerValue" }]); 878 } catch (error) { 879 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 880 } 881 }) 882 Web({ src: 'www.example.com', controller: this.controller }) 883 } 884 } 885} 886``` 887 888There are three methods for loading local resource files: 889 8901. Using $rawfile 891```ts 892// xxx.ets 893import { webview } from '@kit.ArkWeb'; 894import { BusinessError } from '@kit.BasicServicesKit'; 895 896@Entry 897@Component 898struct WebComponent { 899 controller: webview.WebviewController = new webview.WebviewController(); 900 901 build() { 902 Column() { 903 Button('loadUrl') 904 .onClick(() => { 905 try { 906 // Load a local resource file through $rawfile. 907 this.controller.loadUrl($rawfile('index.html')); 908 } catch (error) { 909 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 910 } 911 }) 912 Web({ src: 'www.example.com', controller: this.controller }) 913 } 914 } 915} 916``` 917 9182. Using the resources protocol, which can be used by WebView to load links with a hash (#). 919```ts 920// xxx.ets 921import { webview } from '@kit.ArkWeb'; 922import { BusinessError } from '@kit.BasicServicesKit'; 923 924@Entry 925@Component 926struct WebComponent { 927 controller: webview.WebviewController = new webview.WebviewController(); 928 929 build() { 930 Column() { 931 Button('loadUrl') 932 .onClick(() => { 933 try { 934 // Load local resource files through the resource protocol. 935 this.controller.loadUrl("resource://rawfile/index.html"); 936 } catch (error) { 937 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 938 } 939 }) 940 Web({ src: 'www.example.com', controller: this.controller }) 941 } 942 } 943} 944``` 945 9463. Using a sandbox path. For details, see the example of loading local resource files in the sandbox in [Web](ts-basic-components-web.md#web). 947 948HTML file to be loaded: 949```html 950<!-- index.html --> 951<!DOCTYPE html> 952<html> 953 <body> 954 <p>Hello World</p> 955 </body> 956</html> 957``` 958 959### loadData 960 961loadData(data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string): void 962 963Loads specified data. 964 965**System capability**: SystemCapability.Web.Webview.Core 966 967**Parameters** 968 969| Name | Type | Mandatory| Description | 970| ---------- | ------ | ---- | ------------------------------------------------------------ | 971| data | string | Yes | Character string obtained after being Base64 or URL encoded. | 972| mimeType | string | Yes | Media type (MIME). | 973| encoding | string | Yes | Encoding type, which can be Base64 or URL. | 974| baseUrl | string | No | URL (HTTP/HTTPS/data compliant), which is assigned by the **Web** component to **window.origin**.| 975| 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.| 976 977> **NOTE** 978> 979> To load a local image, you can assign a space to either **baseUrl** or **historyUrl**. For details, see the sample code. 980> In the scenario of loading a local image, **baseUrl** and **historyUrl** cannot be both empty. Otherwise, the image cannot be loaded. 981> If the rich text in HTML contains special characters such as hash (#), you are advised to set the values of **baseUrl** and **historyUrl** to spaces. 982 983**Error codes** 984 985For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 986 987| ID| Error Message | 988| -------- | ------------------------------------------------------------ | 989| 17100001 | Init error. The WebviewController must be associated with a Web component. | 990| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 991 992**Example** 993 994```ts 995// xxx.ets 996import { webview } from '@kit.ArkWeb'; 997import { BusinessError } from '@kit.BasicServicesKit'; 998 999@Entry 1000@Component 1001struct WebComponent { 1002 controller: webview.WebviewController = new webview.WebviewController(); 1003 1004 build() { 1005 Column() { 1006 Button('loadData') 1007 .onClick(() => { 1008 try { 1009 this.controller.loadData( 1010 "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>", 1011 "text/html", 1012 "UTF-8" 1013 ); 1014 } catch (error) { 1015 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1016 } 1017 }) 1018 Web({ src: 'www.example.com', controller: this.controller }) 1019 } 1020 } 1021} 1022``` 1023 1024Example of loading local resource: 1025```ts 1026// xxx.ets 1027import { webview } from '@kit.ArkWeb'; 1028import { BusinessError } from '@kit.BasicServicesKit'; 1029 1030@Entry 1031@Component 1032struct WebComponent { 1033 controller: webview.WebviewController = new webview.WebviewController(); 1034 updataContent: string = '<body><div><image src=resource://rawfile/xxx.png alt="image -- end" width="500" height="250"></image></div></body>' 1035 1036 build() { 1037 Column() { 1038 Button('loadData') 1039 .onClick(() => { 1040 try { 1041 this.controller.loadData(this.updataContent, "text/html", "UTF-8", " ", " "); 1042 } catch (error) { 1043 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1044 } 1045 }) 1046 Web({ src: 'www.example.com', controller: this.controller }) 1047 } 1048 } 1049} 1050``` 1051 1052### accessForward 1053 1054accessForward(): boolean 1055 1056Checks whether going to the next page can be performed on the current page. 1057 1058**System capability**: SystemCapability.Web.Webview.Core 1059 1060**Return value** 1061 1062| Type | Description | 1063| ------- | --------------------------------- | 1064| boolean | Returns **true** if going to the next page can be performed on the current page; returns **false** otherwise.| 1065 1066**Error codes** 1067 1068For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1069 1070| ID| Error Message | 1071| -------- | ------------------------------------------------------------ | 1072| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1073 1074**Example** 1075 1076```ts 1077// xxx.ets 1078import { webview } from '@kit.ArkWeb'; 1079import { BusinessError } from '@kit.BasicServicesKit'; 1080 1081@Entry 1082@Component 1083struct WebComponent { 1084 controller: webview.WebviewController = new webview.WebviewController(); 1085 1086 build() { 1087 Column() { 1088 Button('accessForward') 1089 .onClick(() => { 1090 try { 1091 let result = this.controller.accessForward(); 1092 console.log('result:' + result); 1093 } catch (error) { 1094 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1095 } 1096 }) 1097 Web({ src: 'www.example.com', controller: this.controller }) 1098 } 1099 } 1100} 1101``` 1102 1103### forward 1104 1105forward(): void 1106 1107Moves to the next page based on the history stack. This API is generally used together with **accessForward**. 1108 1109**System capability**: SystemCapability.Web.Webview.Core 1110 1111**Error codes** 1112 1113For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1114 1115| ID| Error Message | 1116| -------- | ------------------------------------------------------------ | 1117| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1118 1119**Example** 1120 1121```ts 1122// xxx.ets 1123import { webview } from '@kit.ArkWeb'; 1124import { BusinessError } from '@kit.BasicServicesKit'; 1125 1126@Entry 1127@Component 1128struct WebComponent { 1129 controller: webview.WebviewController = new webview.WebviewController(); 1130 1131 build() { 1132 Column() { 1133 Button('forward') 1134 .onClick(() => { 1135 try { 1136 this.controller.forward(); 1137 } catch (error) { 1138 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1139 } 1140 }) 1141 Web({ src: 'www.example.com', controller: this.controller }) 1142 } 1143 } 1144} 1145``` 1146 1147### accessBackward 1148 1149accessBackward(): boolean 1150 1151Checks whether going to the previous page can be performed on the current page. 1152 1153**System capability**: SystemCapability.Web.Webview.Core 1154 1155**Return value** 1156 1157| Type | Description | 1158| ------- | -------------------------------- | 1159| boolean | Returns **true** if going to the previous page can be performed on the current page; returns **false** otherwise.| 1160 1161**Error codes** 1162 1163For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1164 1165| ID| Error Message | 1166| -------- | ------------------------------------------------------------ | 1167| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1168 1169**Example** 1170 1171```ts 1172// xxx.ets 1173import { webview } from '@kit.ArkWeb'; 1174import { BusinessError } from '@kit.BasicServicesKit'; 1175 1176@Entry 1177@Component 1178struct WebComponent { 1179 controller: webview.WebviewController = new webview.WebviewController(); 1180 1181 build() { 1182 Column() { 1183 Button('accessBackward') 1184 .onClick(() => { 1185 try { 1186 let result = this.controller.accessBackward(); 1187 console.log('result:' + result); 1188 } catch (error) { 1189 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1190 } 1191 }) 1192 Web({ src: 'www.example.com', controller: this.controller }) 1193 } 1194 } 1195} 1196``` 1197 1198### backward 1199 1200backward(): void 1201 1202Moves to the previous page based on the history stack. This API is generally used together with **accessBackward**. 1203 1204**System capability**: SystemCapability.Web.Webview.Core 1205 1206**Error codes** 1207 1208For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1209 1210| ID| Error Message | 1211| -------- | ------------------------------------------------------------ | 1212| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1213 1214**Example** 1215 1216```ts 1217// xxx.ets 1218import { webview } from '@kit.ArkWeb'; 1219import { BusinessError } from '@kit.BasicServicesKit'; 1220 1221@Entry 1222@Component 1223struct WebComponent { 1224 controller: webview.WebviewController = new webview.WebviewController(); 1225 1226 build() { 1227 Column() { 1228 Button('backward') 1229 .onClick(() => { 1230 try { 1231 this.controller.backward(); 1232 } catch (error) { 1233 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1234 } 1235 }) 1236 Web({ src: 'www.example.com', controller: this.controller }) 1237 } 1238 } 1239} 1240``` 1241 1242### onActive 1243 1244onActive(): void 1245 1246Called when the **Web** component enters the active state. 1247<br>The application can interact with the user while in the active foreground state, and it remains in this state until the focus is moved away from it due to some event (for example, an incoming call is received or the device screen is turned off). 1248 1249**System capability**: SystemCapability.Web.Webview.Core 1250 1251**Error codes** 1252 1253For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1254 1255| ID| Error Message | 1256| -------- | ------------------------------------------------------------ | 1257| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1258 1259**Example** 1260 1261```ts 1262// xxx.ets 1263import { webview } from '@kit.ArkWeb'; 1264import { BusinessError } from '@kit.BasicServicesKit'; 1265 1266@Entry 1267@Component 1268struct WebComponent { 1269 controller: webview.WebviewController = new webview.WebviewController(); 1270 1271 build() { 1272 Column() { 1273 Button('onActive') 1274 .onClick(() => { 1275 try { 1276 this.controller.onActive(); 1277 } catch (error) { 1278 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1279 } 1280 }) 1281 Web({ src: 'www.example.com', controller: this.controller }) 1282 } 1283 } 1284} 1285``` 1286 1287### onInactive 1288 1289onInactive(): void 1290 1291Called when the **Web** component enters the inactive state. You can implement the behavior to perform after the application loses focus. 1292 1293When this API is called, any content that can be safely paused, such as animations and geographical locations, is paused as much as possible. However, the JavaScript is not paused. To pause the JavaScript globally, use [pauseAllTimers](#pausealltimers12). To reactivate the **Web** component, use [onActive](#onactive). 1294 1295**System capability**: SystemCapability.Web.Webview.Core 1296 1297**Error codes** 1298 1299For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1300 1301| ID| Error Message | 1302| -------- | ------------------------------------------------------------ | 1303| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1304 1305**Example** 1306 1307```ts 1308// xxx.ets 1309import { webview } from '@kit.ArkWeb'; 1310import { BusinessError } from '@kit.BasicServicesKit'; 1311 1312@Entry 1313@Component 1314struct WebComponent { 1315 controller: webview.WebviewController = new webview.WebviewController(); 1316 1317 build() { 1318 Column() { 1319 Button('onInactive') 1320 .onClick(() => { 1321 try { 1322 this.controller.onInactive(); 1323 } catch (error) { 1324 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1325 } 1326 }) 1327 Web({ src: 'www.example.com', controller: this.controller }) 1328 } 1329 } 1330} 1331``` 1332 1333### refresh 1334refresh(): void 1335 1336Called when the **Web** component refreshes the web page. 1337 1338**System capability**: SystemCapability.Web.Webview.Core 1339 1340**Error codes** 1341 1342For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1343 1344| ID| Error Message | 1345| -------- | ------------------------------------------------------------ | 1346| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1347 1348**Example** 1349 1350```ts 1351// xxx.ets 1352import { webview } from '@kit.ArkWeb'; 1353import { BusinessError } from '@kit.BasicServicesKit'; 1354 1355@Entry 1356@Component 1357struct WebComponent { 1358 controller: webview.WebviewController = new webview.WebviewController(); 1359 1360 build() { 1361 Column() { 1362 Button('refresh') 1363 .onClick(() => { 1364 try { 1365 this.controller.refresh(); 1366 } catch (error) { 1367 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1368 } 1369 }) 1370 Web({ src: 'www.example.com', controller: this.controller }) 1371 } 1372 } 1373} 1374``` 1375 1376### accessStep 1377 1378accessStep(step: number): boolean 1379 1380Checks whether a specific number of steps forward or backward can be performed on the current page. 1381 1382**System capability**: SystemCapability.Web.Webview.Core 1383 1384**Parameters** 1385 1386| Name| Type| Mandatory| Description | 1387| ------ | -------- | ---- | ------------------------------------------ | 1388| step | number | Yes | Number of the steps to take. A positive number means to move forward, and a negative number means to move backward.| 1389 1390**Return value** 1391 1392| Type | Description | 1393| ------- | ------------------ | 1394| boolean | Whether moving forward or backward is performed on the current page.| 1395 1396**Error codes** 1397 1398For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1399 1400| ID| Error Message | 1401| -------- | ------------------------------------------------------------ | 1402| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1403| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1404 1405**Example** 1406 1407```ts 1408// xxx.ets 1409import { webview } from '@kit.ArkWeb'; 1410import { BusinessError } from '@kit.BasicServicesKit'; 1411 1412@Entry 1413@Component 1414struct WebComponent { 1415 controller: webview.WebviewController = new webview.WebviewController(); 1416 @State steps: number = 2; 1417 1418 build() { 1419 Column() { 1420 Button('accessStep') 1421 .onClick(() => { 1422 try { 1423 let result = this.controller.accessStep(this.steps); 1424 console.log('result:' + result); 1425 } catch (error) { 1426 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1427 } 1428 }) 1429 Web({ src: 'www.example.com', controller: this.controller }) 1430 } 1431 } 1432} 1433``` 1434 1435### clearHistory 1436 1437clearHistory(): void 1438 1439Clears the browsing history. 1440 1441**System capability**: SystemCapability.Web.Webview.Core 1442 1443**Error codes** 1444 1445For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1446 1447| ID| Error Message | 1448| -------- | ------------------------------------------------------------ | 1449| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1450 1451**Example** 1452 1453```ts 1454// xxx.ets 1455import { webview } from '@kit.ArkWeb'; 1456import { BusinessError } from '@kit.BasicServicesKit'; 1457 1458@Entry 1459@Component 1460struct WebComponent { 1461 controller: webview.WebviewController = new webview.WebviewController(); 1462 1463 build() { 1464 Column() { 1465 Button('clearHistory') 1466 .onClick(() => { 1467 try { 1468 this.controller.clearHistory(); 1469 } catch (error) { 1470 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1471 } 1472 }) 1473 Web({ src: 'www.example.com', controller: this.controller }) 1474 } 1475 } 1476} 1477``` 1478 1479### getHitTest 1480 1481getHitTest(): WebHitTestType 1482 1483Obtains the element type of the area being clicked. 1484 1485**System capability**: SystemCapability.Web.Webview.Core 1486 1487**Return value** 1488 1489| Type | Description | 1490| ------------------------------------------------------------ | ---------------------- | 1491| [WebHitTestType](#webhittesttype)| Element type of the area being clicked.| 1492 1493**Error codes** 1494 1495For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1496 1497| ID| Error Message | 1498| -------- | ------------------------------------------------------------ | 1499| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1500 1501**Example** 1502 1503```ts 1504// xxx.ets 1505import { webview } from '@kit.ArkWeb'; 1506import { BusinessError } from '@kit.BasicServicesKit'; 1507 1508@Entry 1509@Component 1510struct WebComponent { 1511 controller: webview.WebviewController = new webview.WebviewController(); 1512 1513 build() { 1514 Column() { 1515 Button('getHitTest') 1516 .onClick(() => { 1517 try { 1518 let hitTestType = this.controller.getHitTest(); 1519 console.log("hitTestType: " + hitTestType); 1520 } catch (error) { 1521 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1522 } 1523 }) 1524 Web({ src: 'www.example.com', controller: this.controller }) 1525 } 1526 } 1527} 1528``` 1529 1530### registerJavaScriptProxy 1531 1532registerJavaScriptProxy(object: object, name: string, methodList: Array\<string>, asyncMethodList?: Array\<string>, permission?: string): void 1533 1534Registers a proxy for interaction between the application and web pages loaded by the **Web** component. 1535<br>Registers 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. 1536 1537> **NOTE** 1538> 1539> - It is recommended that **registerJavaScriptProxy** be used only with trusted URLs and over secure HTTPS connections. Injecting JavaScript objects into untrusted web components can expose your application to malicious attacks. 1540> - After **registerJavaScriptProxy** is called, the application exposes the registered JavaScript object to all page frames. 1541> - If a **registerJavaScriptProxy** is both registered in the synchronous and asynchronous lists, it is called asynchronously by default. 1542> - You should register **registerJavaScriptProxy** either in synchronous list or in asynchronous list. Otherwise, this API fails to be registered. 1543 1544**System capability**: SystemCapability.Web.Webview.Core 1545 1546**Parameters** 1547 1548| Name | Type | Mandatory| Description | 1549| ---------- | -------------- | ---- | ------------------------------------------------------------ | 1550| object | object | Yes | Application-side JavaScript object to be registered. Methods and attributes can be declared, but cannot be directly called on HTML5.<br>The parameter and return value can be any of the following types:<br>string, number, boolean.<br>Dictionary or Array, with a maximum of 10 nested layers and 10,000 data records per layer.<br>Object, which must contain the **methodNameListForJsProxy:[fun1, fun2]** attribute, where **fun1** and **fun2** are methods that can be called.<br>The parameter also supports Function and Promise. Their callback cannot have return values.<br>The return value supports Promise. Its callback cannot have a return value.<br>For the example, see [Invoking Application Functions on the Frontend Page](../../web/web-in-page-app-function-invoking.md).| 1551| 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.| 1552| methodList | Array\<string> | Yes | Synchronous methods of the JavaScript object to be registered at the application side. | 1553| asyncMethodList<sup>12+</sup> | Array\<string> | No | Asynchronous methods of the JavaScript object to be registered at the application side. The default value is null. Asynchronous methods cannot obtain return values. | 1554| permission<sup>12+</sup> | string | No | JSON string, which is empty by default. This string is used to configure JSBridge permission control and define the URL trustlist at the object and method levels.<br>For the example, see [Invoking Application Functions on the Frontend Page](../../web/web-in-page-app-function-invoking.md).| 1555 1556**Error codes** 1557 1558For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1559 1560| ID| Error Message | 1561| -------- | ------------------------------------------------------------ | 1562| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1563| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1564 1565**Example** 1566 1567```ts 1568// xxx.ets 1569import { webview } from '@kit.ArkWeb'; 1570import { BusinessError } from '@kit.BasicServicesKit'; 1571 1572class TestObj { 1573 constructor() { 1574 } 1575 1576 test(testStr:string): string { 1577 console.log('Web Component str' + testStr); 1578 return testStr; 1579 } 1580 1581 toString(): void { 1582 console.log('Web Component toString'); 1583 } 1584 1585 testNumber(testNum:number): number { 1586 console.log('Web Component number' + testNum); 1587 return testNum; 1588 } 1589 1590 asyncTestBool(testBol:boolean): void { 1591 console.log('Web Component boolean' + testBol); 1592 } 1593} 1594 1595class WebObj { 1596 constructor() { 1597 } 1598 1599 webTest(): string { 1600 console.log('Web test'); 1601 return "Web test"; 1602 } 1603 1604 webString(): void { 1605 console.log('Web test toString'); 1606 } 1607} 1608 1609class AsyncObj { 1610 constructor() { 1611 } 1612 1613 asyncTest(): void { 1614 console.log('Async test'); 1615 } 1616 1617 asyncString(testStr:string): void { 1618 console.log('Web async string' + testStr); 1619 } 1620} 1621 1622@Entry 1623@Component 1624struct Index { 1625 controller: webview.WebviewController = new webview.WebviewController(); 1626 @State testObjtest: TestObj = new TestObj(); 1627 @State webTestObj: WebObj = new WebObj(); 1628 @State asyncTestObj: AsyncObj = new AsyncObj(); 1629 1630 build() { 1631 Column() { 1632 Button('refresh') 1633 .onClick(() => { 1634 try { 1635 this.controller.refresh(); 1636 } catch (error) { 1637 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1638 } 1639 }) 1640 Button('Register JavaScript To Window') 1641 .onClick(() => { 1642 try { 1643 this.controller.registerJavaScriptProxy(this.testObjtest, "objName", ["test", "toString", "testNumber"], ["asyncTestBool"]); 1644 this.controller.registerJavaScriptProxy(this.webTestObj, "objTestName", ["webTest", "webString"]); 1645 this.controller.registerJavaScriptProxy(this.asyncTestObj, "objAsyncName", [], ["asyncTest", "asyncString"]); 1646 } catch (error) { 1647 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1648 } 1649 }) 1650 Web({ src: $rawfile('index.html'), controller: this.controller }) 1651 .javaScriptAccess(true) 1652 } 1653 } 1654} 1655``` 1656 1657HTML file to be loaded: 1658```html 1659<!-- index.html --> 1660<!DOCTYPE html> 1661<html> 1662 <meta charset="utf-8"> 1663 <body> 1664 <button type="button" onclick="htmlTest()">Click Me!</button> 1665 <p id="demo"></p> 1666 <p id="webDemo"></p> 1667 <p id="asyncDemo"></p> 1668 </body> 1669 <script type="text/javascript"> 1670 function htmlTest() { 1671 // This function call expects to return "ArkUI Web Component" 1672 let str=objName.test("webtest data"); 1673 objName.testNumber(1); 1674 objName.asyncTestBool(true); 1675 document.getElementById("demo").innerHTML=str; 1676 console.log('objName.test result:'+ str) 1677 1678 // This function call expects to return "Web test" 1679 let webStr = objTestName.webTest(); 1680 document.getElementById("webDemo").innerHTML=webStr; 1681 console.log('objTestName.webTest result:'+ webStr) 1682 1683 objAsyncName.asyncTest(); 1684 objAsyncName.asyncString("async test data"); 1685 } 1686</script> 1687</html> 1688``` 1689For more examples, see [Invoking Application Functions on the Frontend Page](../../web/web-in-page-app-function-invoking.md). 1690 1691### runJavaScript 1692 1693runJavaScript(script: string, callback : AsyncCallback\<string>): void 1694 1695Executes 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**. 1696 1697**System capability**: SystemCapability.Web.Webview.Core 1698 1699**Parameters** 1700 1701| Name | Type | Mandatory| Description | 1702| -------- | -------------------- | ---- | ---------------------------- | 1703| script | string | Yes | JavaScript script. | 1704| 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.| 1705 1706**Error codes** 1707 1708For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1709 1710| ID| Error Message | 1711| -------- | ------------------------------------------------------------ | 1712| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1713| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1714 1715**Example** 1716 1717```ts 1718import { webview } from '@kit.ArkWeb'; 1719import { BusinessError } from '@kit.BasicServicesKit'; 1720 1721@Entry 1722@Component 1723struct WebComponent { 1724 controller: webview.WebviewController = new webview.WebviewController(); 1725 @State webResult: string = ''; 1726 1727 build() { 1728 Column() { 1729 Text(this.webResult).fontSize(20) 1730 Web({ src: $rawfile('index.html'), controller: this.controller }) 1731 .javaScriptAccess(true) 1732 .onPageEnd(e => { 1733 try { 1734 this.controller.runJavaScript( 1735 'test()', 1736 (error, result) => { 1737 if (error) { 1738 console.error(`run JavaScript error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1739 return; 1740 } 1741 if (result) { 1742 this.webResult = result; 1743 console.info(`The test() return value is: ${result}`); 1744 } 1745 }); 1746 if (e) { 1747 console.info('url: ', e.url); 1748 } 1749 } catch (error) { 1750 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1751 } 1752 }) 1753 } 1754 } 1755} 1756``` 1757 1758HTML file to be loaded: 1759```html 1760<!-- index.html --> 1761<!DOCTYPE html> 1762<html> 1763 <meta charset="utf-8"> 1764 <body> 1765 Hello world! 1766 </body> 1767 <script type="text/javascript"> 1768 function test() { 1769 console.log('Ark WebComponent') 1770 return "This value is from index.html" 1771 } 1772 </script> 1773</html> 1774``` 1775 1776### runJavaScript 1777 1778runJavaScript(script: string): Promise\<string> 1779 1780Executes 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**. 1781 1782**System capability**: SystemCapability.Web.Webview.Core 1783 1784**Parameters** 1785 1786| Name| Type| Mandatory| Description | 1787| ------ | -------- | ---- | ---------------- | 1788| script | string | Yes | JavaScript script.| 1789 1790**Return value** 1791 1792| Type | Description | 1793| --------------- | --------------------------------------------------- | 1794| Promise\<string> | Promise used to return the result if the operation is successful and null otherwise.| 1795| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1796 1797**Error codes** 1798 1799For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1800 1801| ID| Error Message | 1802| -------- | ------------------------------------------------------------ | 1803| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1804| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1805 1806**Example** 1807 1808```ts 1809// xxx.ets 1810import { webview } from '@kit.ArkWeb'; 1811import { BusinessError } from '@kit.BasicServicesKit'; 1812 1813@Entry 1814@Component 1815struct WebComponent { 1816 controller: webview.WebviewController = new webview.WebviewController(); 1817 1818 build() { 1819 Column() { 1820 Web({ src: $rawfile('index.html'), controller: this.controller }) 1821 .javaScriptAccess(true) 1822 .onPageEnd(e => { 1823 try { 1824 this.controller.runJavaScript('test()') 1825 .then((result) => { 1826 console.log('result: ' + result); 1827 }) 1828 .catch((error: BusinessError) => { 1829 console.error("error: " + error); 1830 }) 1831 if (e) { 1832 console.info('url: ', e.url); 1833 } 1834 } catch (error) { 1835 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1836 } 1837 }) 1838 } 1839 } 1840} 1841``` 1842 1843HTML file to be loaded: 1844```html 1845<!-- index.html --> 1846<!DOCTYPE html> 1847<html> 1848 <meta charset="utf-8"> 1849 <body> 1850 Hello world! 1851 </body> 1852 <script type="text/javascript"> 1853 function test() { 1854 console.log('Ark WebComponent') 1855 return "This value is from index.html" 1856 } 1857 </script> 1858</html> 1859``` 1860 1861### runJavaScriptExt<sup>10+</sup> 1862 1863runJavaScriptExt(script: string | ArrayBuffer, callback : AsyncCallback\<JsMessageExt>): void 1864 1865Executes 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**. 1866 1867**System capability**: SystemCapability.Web.Webview.Core 1868 1869**Parameters** 1870 1871| Name | Type | Mandatory| Description | 1872| -------- | -------------------- | ---- | ---------------------------- | 1873| script | string \| ArrayBuffer<sup>12+</sup> | Yes | JavaScript script.| 1874| callback | AsyncCallback\<[JsMessageExt](#jsmessageext10)\> | Yes | Callback used to return the result.| 1875 1876**Error codes** 1877 1878For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1879 1880| ID| Error Message | 1881| -------- | ------------------------------------------------------------ | 1882| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1883| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1884 1885**Example** 1886 1887```ts 1888import { webview } from '@kit.ArkWeb'; 1889import { BusinessError } from '@kit.BasicServicesKit'; 1890 1891@Entry 1892@Component 1893struct WebComponent { 1894 controller: webview.WebviewController = new webview.WebviewController(); 1895 @State msg1: string = ''; 1896 @State msg2: string = ''; 1897 1898 build() { 1899 Column() { 1900 Text(this.msg1).fontSize(20) 1901 Text(this.msg2).fontSize(20) 1902 Web({ src: $rawfile('index.html'), controller: this.controller }) 1903 .javaScriptAccess(true) 1904 .onPageEnd(e => { 1905 try { 1906 this.controller.runJavaScriptExt( 1907 'test()', 1908 (error, result) => { 1909 if (error) { 1910 console.error(`run JavaScript error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`) 1911 return; 1912 } 1913 if (result) { 1914 try { 1915 let type = result.getType(); 1916 switch (type) { 1917 case webview.JsMessageType.STRING: { 1918 this.msg1 = "result type:" + typeof (result.getString()); 1919 this.msg2 = "result getString:" + ((result.getString())); 1920 break; 1921 } 1922 case webview.JsMessageType.NUMBER: { 1923 this.msg1 = "result type:" + typeof (result.getNumber()); 1924 this.msg2 = "result getNumber:" + ((result.getNumber())); 1925 break; 1926 } 1927 case webview.JsMessageType.BOOLEAN: { 1928 this.msg1 = "result type:" + typeof (result.getBoolean()); 1929 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 1930 break; 1931 } 1932 case webview.JsMessageType.ARRAY_BUFFER: { 1933 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 1934 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 1935 break; 1936 } 1937 case webview.JsMessageType.ARRAY: { 1938 this.msg1 = "result type:" + typeof (result.getArray()); 1939 this.msg2 = "result getArray:" + result.getArray(); 1940 break; 1941 } 1942 default: { 1943 this.msg1 = "default break, type:" + type; 1944 break; 1945 } 1946 } 1947 } 1948 catch (resError) { 1949 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1950 } 1951 } 1952 }); 1953 if (e) { 1954 console.info('url: ', e.url); 1955 } 1956 } catch (error) { 1957 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1958 } 1959 }) 1960 } 1961 } 1962} 1963``` 1964 1965```ts 1966// Use the ArrayBuffer input parameter to obtain the JavaScript script data from the file. 1967import { webview } from '@kit.ArkWeb'; 1968import { BusinessError } from '@kit.BasicServicesKit'; 1969import { fileIo } from '@kit.CoreFileKit'; 1970import { common } from '@kit.AbilityKit'; 1971 1972@Entry 1973@Component 1974struct WebComponent { 1975 controller: webview.WebviewController = new webview.WebviewController(); 1976 @State msg1: string = '' 1977 @State msg2: string = '' 1978 1979 build() { 1980 Column() { 1981 Text(this.msg1).fontSize(20) 1982 Text(this.msg2).fontSize(20) 1983 Button('runJavaScriptExt') 1984 .onClick(() => { 1985 try { 1986 let context = getContext(this) as common.UIAbilityContext; 1987 let filePath = context.filesDir + 'test.txt'; 1988 // Create a file and open it. 1989 let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); 1990 // Write data to the file. 1991 fileIo.writeSync(file.fd, "test()"); 1992 // Read data from the file. 1993 let arrayBuffer: ArrayBuffer = new ArrayBuffer(6); 1994 fileIo.readSync(file.fd, arrayBuffer, { offset: 0, length: arrayBuffer.byteLength }); 1995 // Close the file. 1996 fileIo.closeSync(file); 1997 this.controller.runJavaScriptExt( 1998 arrayBuffer, 1999 (error, result) => { 2000 if (error) { 2001 console.error(`run JavaScript error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`) 2002 return; 2003 } 2004 if (result) { 2005 try { 2006 let type = result.getType(); 2007 switch (type) { 2008 case webview.JsMessageType.STRING: { 2009 this.msg1 = "result type:" + typeof (result.getString()); 2010 this.msg2 = "result getString:" + ((result.getString())); 2011 break; 2012 } 2013 case webview.JsMessageType.NUMBER: { 2014 this.msg1 = "result type:" + typeof (result.getNumber()); 2015 this.msg2 = "result getNumber:" + ((result.getNumber())); 2016 break; 2017 } 2018 case webview.JsMessageType.BOOLEAN: { 2019 this.msg1 = "result type:" + typeof (result.getBoolean()); 2020 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 2021 break; 2022 } 2023 case webview.JsMessageType.ARRAY_BUFFER: { 2024 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 2025 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 2026 break; 2027 } 2028 case webview.JsMessageType.ARRAY: { 2029 this.msg1 = "result type:" + typeof (result.getArray()); 2030 this.msg2 = "result getArray:" + result.getArray(); 2031 break; 2032 } 2033 default: { 2034 this.msg1 = "default break, type:" + type; 2035 break; 2036 } 2037 } 2038 } 2039 catch (resError) { 2040 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2041 } 2042 } 2043 }); 2044 } catch (error) { 2045 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).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 lang="en-gb"> 2060<body> 2061<h1>run JavaScript Ext demo</h1> 2062</body> 2063<script type="text/javascript"> 2064function test() { 2065 return "hello, world"; 2066} 2067</script> 2068</html> 2069``` 2070 2071### runJavaScriptExt<sup>10+</sup> 2072 2073runJavaScriptExt(script: string | ArrayBuffer): Promise\<JsMessageExt> 2074 2075Executes 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**. 2076 2077**System capability**: SystemCapability.Web.Webview.Core 2078 2079**Parameters** 2080 2081| Name| Type| Mandatory| Description | 2082| ------ | -------- | ---- | ---------------- | 2083| script | string \| ArrayBuffer<sup>12+</sup> | Yes | JavaScript script.| 2084 2085**Return value** 2086 2087| Type | Description | 2088| --------------- | --------------------------------------------------- | 2089| Promise\<[JsMessageExt](#jsmessageext10)> | Promise used to return the script execution result.| 2090 2091**Error codes** 2092 2093For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2094 2095| ID| Error Message | 2096| -------- | ------------------------------------------------------------ | 2097| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2098| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2099 2100**Example** 2101 2102```ts 2103// xxx.ets 2104import { webview } from '@kit.ArkWeb'; 2105import { BusinessError } from '@kit.BasicServicesKit'; 2106 2107@Entry 2108@Component 2109struct WebComponent { 2110 controller: webview.WebviewController = new webview.WebviewController(); 2111 @State webResult: string = ''; 2112 @State msg1: string = ''; 2113 @State msg2: string = ''; 2114 2115 build() { 2116 Column() { 2117 Text(this.webResult).fontSize(20) 2118 Text(this.msg1).fontSize(20) 2119 Text(this.msg2).fontSize(20) 2120 Web({ src: $rawfile('index.html'), controller: this.controller }) 2121 .javaScriptAccess(true) 2122 .onPageEnd(() => { 2123 this.controller.runJavaScriptExt('test()') 2124 .then((result) => { 2125 try { 2126 let type = result.getType(); 2127 switch (type) { 2128 case webview.JsMessageType.STRING: { 2129 this.msg1 = "result type:" + typeof (result.getString()); 2130 this.msg2 = "result getString:" + ((result.getString())); 2131 break; 2132 } 2133 case webview.JsMessageType.NUMBER: { 2134 this.msg1 = "result type:" + typeof (result.getNumber()); 2135 this.msg2 = "result getNumber:" + ((result.getNumber())); 2136 break; 2137 } 2138 case webview.JsMessageType.BOOLEAN: { 2139 this.msg1 = "result type:" + typeof (result.getBoolean()); 2140 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 2141 break; 2142 } 2143 case webview.JsMessageType.ARRAY_BUFFER: { 2144 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 2145 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 2146 break; 2147 } 2148 case webview.JsMessageType.ARRAY: { 2149 this.msg1 = "result type:" + typeof (result.getArray()); 2150 this.msg2 = "result getArray:" + result.getArray(); 2151 break; 2152 } 2153 default: { 2154 this.msg1 = "default break, type:" + type; 2155 break; 2156 } 2157 } 2158 } 2159 catch (resError) { 2160 console.error(`ErrorCode: ${(resError as BusinessError).code}, Message: ${(resError as BusinessError).message}`); 2161 } 2162 }).catch((error: BusinessError) => { 2163 console.error("error: " + error); 2164 }) 2165 }) 2166 } 2167 } 2168} 2169``` 2170 2171```ts 2172// Use the ArrayBuffer input parameter to obtain the JavaScript script data from the file. 2173import { webview } from '@kit.ArkWeb'; 2174import { BusinessError } from '@kit.BasicServicesKit'; 2175import { fileIo } from '@kit.CoreFileKit'; 2176import { common } from '@kit.AbilityKit'; 2177 2178@Entry 2179@Component 2180struct WebComponent { 2181 controller: webview.WebviewController = new webview.WebviewController(); 2182 @State msg1: string = ''; 2183 @State msg2: string = ''; 2184 2185 build() { 2186 Column() { 2187 Text(this.msg1).fontSize(20) 2188 Text(this.msg2).fontSize(20) 2189 Button('runJavaScriptExt') 2190 .onClick(() => { 2191 try { 2192 let context = getContext(this) as common.UIAbilityContext; 2193 let filePath = context.filesDir + 'test.txt'; 2194 // Create a file and open it. 2195 let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); 2196 // Write data to the file. 2197 fileIo.writeSync(file.fd, "test()"); 2198 // Read data from the file. 2199 let arrayBuffer: ArrayBuffer = new ArrayBuffer(6); 2200 fileIo.readSync(file.fd, arrayBuffer, { offset: 0, length: arrayBuffer.byteLength }); 2201 // Close the file. 2202 fileIo.closeSync(file); 2203 this.controller.runJavaScriptExt(arrayBuffer) 2204 .then((result) => { 2205 try { 2206 let type = result.getType(); 2207 switch (type) { 2208 case webview.JsMessageType.STRING: { 2209 this.msg1 = "result type:" + typeof (result.getString()); 2210 this.msg2 = "result getString:" + ((result.getString())); 2211 break; 2212 } 2213 case webview.JsMessageType.NUMBER: { 2214 this.msg1 = "result type:" + typeof (result.getNumber()); 2215 this.msg2 = "result getNumber:" + ((result.getNumber())); 2216 break; 2217 } 2218 case webview.JsMessageType.BOOLEAN: { 2219 this.msg1 = "result type:" + typeof (result.getBoolean()); 2220 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 2221 break; 2222 } 2223 case webview.JsMessageType.ARRAY_BUFFER: { 2224 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 2225 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 2226 break; 2227 } 2228 case webview.JsMessageType.ARRAY: { 2229 this.msg1 = "result type:" + typeof (result.getArray()); 2230 this.msg2 = "result getArray:" + result.getArray(); 2231 break; 2232 } 2233 default: { 2234 this.msg1 = "default break, type:" + type; 2235 break; 2236 } 2237 } 2238 } 2239 catch (resError) { 2240 console.error(`ErrorCode: ${(resError as BusinessError).code}, Message: ${(resError as BusinessError).message}`); 2241 } 2242 }) 2243 .catch((error: BusinessError) => { 2244 console.error("error: " + error); 2245 }) 2246 } catch (error) { 2247 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2248 } 2249 }) 2250 Web({ src: $rawfile('index.html'), controller: this.controller }) 2251 .javaScriptAccess(true) 2252 } 2253 } 2254} 2255``` 2256 2257HTML file to be loaded: 2258```html 2259<!-- index.html --> 2260<!DOCTYPE html> 2261<html lang="en-gb"> 2262<body> 2263<h1>run JavaScript Ext demo</h1> 2264</body> 2265<script type="text/javascript"> 2266function test() { 2267 return "hello, world"; 2268} 2269</script> 2270</html> 2271``` 2272 2273### deleteJavaScriptRegister 2274 2275deleteJavaScriptRegister(name: string): void 2276 2277Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. After the deletion, the [refresh](#refresh) API must be called. 2278 2279**System capability**: SystemCapability.Web.Webview.Core 2280 2281**Parameters** 2282 2283| Name| Type| Mandatory| Description | 2284| ------ | -------- | ---- | ---- | 2285| 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.| 2286 2287**Error codes** 2288 2289For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2290 2291| ID| Error Message | 2292| -------- | ------------------------------------------------------------ | 2293| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2294| 17100008 | Failed to delete JavaScriptProxy because it does not exist. | 2295| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2296 2297**Example** 2298 2299```ts 2300// xxx.ets 2301import { webview } from '@kit.ArkWeb'; 2302import { BusinessError } from '@kit.BasicServicesKit'; 2303 2304class TestObj { 2305 constructor() { 2306 } 2307 2308 test(): string { 2309 return "ArkUI Web Component"; 2310 } 2311 2312 toString(): void { 2313 console.log('Web Component toString'); 2314 } 2315} 2316 2317@Entry 2318@Component 2319struct WebComponent { 2320 controller: webview.WebviewController = new webview.WebviewController(); 2321 @State testObjtest: TestObj = new TestObj(); 2322 @State name: string = 'objName'; 2323 build() { 2324 Column() { 2325 Button('refresh') 2326 .onClick(() => { 2327 try { 2328 this.controller.refresh(); 2329 } catch (error) { 2330 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2331 } 2332 }) 2333 Button('Register JavaScript To Window') 2334 .onClick(() => { 2335 try { 2336 this.controller.registerJavaScriptProxy(this.testObjtest, this.name, ["test", "toString"]); 2337 } catch (error) { 2338 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2339 } 2340 }) 2341 Button('deleteJavaScriptRegister') 2342 .onClick(() => { 2343 try { 2344 this.controller.deleteJavaScriptRegister(this.name); 2345 } catch (error) { 2346 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2347 } 2348 }) 2349 Web({ src: $rawfile('index.html'), controller: this.controller }) 2350 .javaScriptAccess(true) 2351 } 2352 } 2353} 2354``` 2355 2356HTML file to be loaded: 2357```html 2358<!-- index.html --> 2359<!DOCTYPE html> 2360<html> 2361 <meta charset="utf-8"> 2362 <body> 2363 <button type="button" onclick="htmlTest()">Click Me!</button> 2364 <p id="demo"></p> 2365 </body> 2366 <script type="text/javascript"> 2367 function htmlTest() { 2368 let str=objName.test(); 2369 document.getElementById("demo").innerHTML=str; 2370 console.log('objName.test result:'+ str) 2371 } 2372</script> 2373</html> 2374``` 2375 2376### zoom 2377 2378zoom(factor: number): void 2379 2380Zooms in or out of this web page. This API is effective only when [zoomAccess](ts-basic-components-web.md#zoomaccess) is **true**. 2381 2382**System capability**: SystemCapability.Web.Webview.Core 2383 2384**Parameters** 2385 2386| Name| Type| Mandatory| Description| 2387| ------ | -------- | ---- | ------------------------------------------------------------ | 2388| 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.| 2389 2390**Error codes** 2391 2392For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2393 2394| ID| Error Message | 2395| -------- | ------------------------------------------------------------ | 2396| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2397| 17100004 | Function not enabled. | 2398| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2399 2400**Example** 2401 2402```ts 2403// xxx.ets 2404import { webview } from '@kit.ArkWeb'; 2405import { BusinessError } from '@kit.BasicServicesKit'; 2406 2407@Entry 2408@Component 2409struct WebComponent { 2410 controller: webview.WebviewController = new webview.WebviewController(); 2411 @State factor: number = 1; 2412 2413 build() { 2414 Column() { 2415 Button('zoom') 2416 .onClick(() => { 2417 try { 2418 this.controller.zoom(this.factor); 2419 } catch (error) { 2420 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2421 } 2422 }) 2423 Web({ src: 'www.example.com', controller: this.controller }) 2424 .zoomAccess(true) 2425 } 2426 } 2427} 2428``` 2429 2430### searchAllAsync 2431 2432searchAllAsync(searchString: string): void 2433 2434Searches 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](ts-basic-components-web.md#onsearchresultreceive9). 2435 2436**System capability**: SystemCapability.Web.Webview.Core 2437 2438**Parameters** 2439 2440| Name | Type| Mandatory| Description | 2441| ------------ | -------- | ---- | -------------- | 2442| searchString | string | Yes | Search keyword.| 2443 2444**Error codes** 2445 2446For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2447 2448| ID| Error Message | 2449| -------- | ------------------------------------------------------------ | 2450| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2451| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2452 2453**Example** 2454 2455```ts 2456// xxx.ets 2457import { webview } from '@kit.ArkWeb'; 2458import { BusinessError } from '@kit.BasicServicesKit'; 2459 2460@Entry 2461@Component 2462struct WebComponent { 2463 controller: webview.WebviewController = new webview.WebviewController(); 2464 @State searchString: string = "Hello World"; 2465 2466 build() { 2467 Column() { 2468 Button('searchString') 2469 .onClick(() => { 2470 try { 2471 this.controller.searchAllAsync(this.searchString); 2472 } catch (error) { 2473 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2474 } 2475 }) 2476 Web({ src: $rawfile('index.html'), controller: this.controller }) 2477 .onSearchResultReceive(ret => { 2478 if (ret) { 2479 console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal + 2480 "[total]" + ret.numberOfMatches + "[isDone]" + ret.isDoneCounting); 2481 } 2482 }) 2483 } 2484 } 2485} 2486``` 2487 2488HTML file to be loaded: 2489```html 2490<!-- index.html --> 2491<!DOCTYPE html> 2492<html> 2493 <body> 2494 <p>Hello World Highlight Hello World</p> 2495 </body> 2496</html> 2497``` 2498 2499### clearMatches 2500 2501clearMatches(): void 2502 2503Clears the matches found through [searchAllAsync](#searchallasync). 2504 2505**System capability**: SystemCapability.Web.Webview.Core 2506 2507**Error codes** 2508 2509For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2510 2511| ID| Error Message | 2512| -------- | ------------------------------------------------------------ | 2513| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2514 2515**Example** 2516 2517```ts 2518// xxx.ets 2519import { webview } from '@kit.ArkWeb'; 2520import { BusinessError } from '@kit.BasicServicesKit'; 2521 2522@Entry 2523@Component 2524struct WebComponent { 2525 controller: webview.WebviewController = new webview.WebviewController(); 2526 2527 build() { 2528 Column() { 2529 Button('clearMatches') 2530 .onClick(() => { 2531 try { 2532 this.controller.clearMatches(); 2533 } catch (error) { 2534 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2535 } 2536 }) 2537 Web({ src: $rawfile('index.html'), controller: this.controller }) 2538 } 2539 } 2540} 2541``` 2542 2543For details about the HTML file loaded, see the HMTL file loaded using [searchAllAsync](#searchallasync). 2544 2545### searchNext 2546 2547searchNext(forward: boolean): void 2548 2549Searches for and highlights the next match. 2550 2551**System capability**: SystemCapability.Web.Webview.Core 2552 2553**Parameters** 2554 2555| Name | Type| Mandatory| Description | 2556| ------- | -------- | ---- | ---------------------- | 2557| forward | boolean | Yes | Whether to search forward.| 2558 2559**Error codes** 2560 2561For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2562 2563| ID| Error Message | 2564| -------- | ------------------------------------------------------------ | 2565| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2566| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2567 2568**Example** 2569 2570```ts 2571// xxx.ets 2572import { webview } from '@kit.ArkWeb'; 2573import { BusinessError } from '@kit.BasicServicesKit'; 2574 2575@Entry 2576@Component 2577struct WebComponent { 2578 controller: webview.WebviewController = new webview.WebviewController(); 2579 2580 build() { 2581 Column() { 2582 Button('searchNext') 2583 .onClick(() => { 2584 try { 2585 this.controller.searchNext(true); 2586 } catch (error) { 2587 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2588 } 2589 }) 2590 Web({ src: $rawfile('index.html'), controller: this.controller }) 2591 } 2592 } 2593} 2594``` 2595 2596For details about the HTML file loaded, see the HMTL file loaded using [searchAllAsync](#searchallasync). 2597 2598### clearSslCache 2599 2600clearSslCache(): void 2601 2602Clears the user operation corresponding to the SSL certificate error event recorded by the **Web** component. 2603 2604**System capability**: SystemCapability.Web.Webview.Core 2605 2606**Error codes** 2607 2608For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2609 2610| ID| Error Message | 2611| -------- | ------------------------------------------------------------ | 2612| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2613 2614**Example** 2615 2616```ts 2617// xxx.ets 2618import { webview } from '@kit.ArkWeb'; 2619import { BusinessError } from '@kit.BasicServicesKit'; 2620 2621@Entry 2622@Component 2623struct WebComponent { 2624 controller: webview.WebviewController = new webview.WebviewController(); 2625 2626 build() { 2627 Column() { 2628 Button('clearSslCache') 2629 .onClick(() => { 2630 try { 2631 this.controller.clearSslCache(); 2632 } catch (error) { 2633 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2634 } 2635 }) 2636 Web({ src: 'www.example.com', controller: this.controller }) 2637 } 2638 } 2639} 2640``` 2641 2642### clearClientAuthenticationCache 2643 2644clearClientAuthenticationCache(): void 2645 2646Clears the user operation corresponding to the client certificate request event recorded by the **Web** component. 2647 2648**System capability**: SystemCapability.Web.Webview.Core 2649 2650**Error codes** 2651 2652For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2653 2654| ID| Error Message | 2655| -------- | ------------------------------------------------------------ | 2656| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2657 2658**Example** 2659 2660```ts 2661// xxx.ets 2662import { webview } from '@kit.ArkWeb'; 2663import { BusinessError } from '@kit.BasicServicesKit'; 2664 2665@Entry 2666@Component 2667struct WebComponent { 2668 controller: webview.WebviewController = new webview.WebviewController(); 2669 2670 build() { 2671 Column() { 2672 Button('clearClientAuthenticationCache') 2673 .onClick(() => { 2674 try { 2675 this.controller.clearClientAuthenticationCache(); 2676 } catch (error) { 2677 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2678 } 2679 }) 2680 Web({ src: 'www.example.com', controller: this.controller }) 2681 } 2682 } 2683} 2684``` 2685 2686### createWebMessagePorts 2687 2688createWebMessagePorts(isExtentionType?: boolean): Array\<WebMessagePort> 2689 2690Creates web message ports. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 2691 2692**System capability**: SystemCapability.Web.Webview.Core 2693 2694**Parameters** 2695 2696| Name| Type | Mandatory| Description | 2697| ------ | ---------------------- | ---- | :------------------------------| 2698| 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.| 2699 2700**Return value** 2701 2702| Type | Description | 2703| ---------------------- | ----------------- | 2704| Array\<[WebMessagePort](#webmessageport)> | List of web message ports.| 2705 2706**Error codes** 2707 2708For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2709 2710| ID| Error Message | 2711| -------- | ------------------------------------------------------------ | 2712| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2713| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2714 2715**Example** 2716 2717```ts 2718// xxx.ets 2719import { webview } from '@kit.ArkWeb'; 2720import { BusinessError } from '@kit.BasicServicesKit'; 2721 2722@Entry 2723@Component 2724struct WebComponent { 2725 controller: webview.WebviewController = new webview.WebviewController(); 2726 ports: webview.WebMessagePort[] = []; 2727 2728 build() { 2729 Column() { 2730 Button('createWebMessagePorts') 2731 .onClick(() => { 2732 try { 2733 this.ports = this.controller.createWebMessagePorts(); 2734 console.log("createWebMessagePorts size:" + this.ports.length); 2735 } catch (error) { 2736 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2737 } 2738 }) 2739 Web({ src: 'www.example.com', controller: this.controller }) 2740 } 2741 } 2742} 2743``` 2744 2745### postMessage 2746 2747postMessage(name: string, ports: Array\<WebMessagePort>, uri: string): void 2748 2749Sends a web message to an HTML window. 2750 2751**System capability**: SystemCapability.Web.Webview.Core 2752 2753**Parameters** 2754 2755| Name| Type | Mandatory| Description | 2756| ------ | ---------------------- | ---- | :------------------------------- | 2757| name | string | Yes | Name of the message to send. | 2758| ports | Array\<[WebMessagePort](#webmessageport)> | Yes | Message ports for sending the message. | 2759| uri | string | Yes | URI for receiving the message. | 2760 2761**Error codes** 2762 2763For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2764 2765| ID| Error Message | 2766| -------- | ------------------------------------------------------------ | 2767| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2768| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2769 2770**Example** 2771 2772```ts 2773// xxx.ets 2774import { webview } from '@kit.ArkWeb'; 2775import { BusinessError } from '@kit.BasicServicesKit'; 2776 2777@Entry 2778@Component 2779struct WebComponent { 2780 controller: webview.WebviewController = new webview.WebviewController(); 2781 ports: webview.WebMessagePort[] = []; 2782 @State sendFromEts: string = 'Send this message from ets to HTML'; 2783 @State receivedFromHtml: string = 'Display received message send from HTML'; 2784 2785 build() { 2786 Column() { 2787 // Display the received HTML content. 2788 Text(this.receivedFromHtml) 2789 // Send the content in the text box to an HTML window. 2790 TextInput({ placeholder: 'Send this message from ets to HTML' }) 2791 .onChange((value: string) => { 2792 this.sendFromEts = value; 2793 }) 2794 2795 Button('postMessage') 2796 .onClick(() => { 2797 try { 2798 // 1. Create two message ports. 2799 this.ports = this.controller.createWebMessagePorts(); 2800 // 2. Register a callback on a message port (for example, port 1) on the application side. 2801 this.ports[1].onMessageEvent((result: webview.WebMessage) => { 2802 let msg = 'Got msg from HTML:'; 2803 if (typeof (result) == "string") { 2804 console.log("received string message from html5, string is:" + result); 2805 msg = msg + result; 2806 } else if (typeof (result) == "object") { 2807 if (result instanceof ArrayBuffer) { 2808 console.log("received arraybuffer from html5, length is:" + result.byteLength); 2809 msg = msg + "length is " + result.byteLength; 2810 } else { 2811 console.log("not support"); 2812 } 2813 } else { 2814 console.log("not support"); 2815 } 2816 this.receivedFromHtml = msg; 2817 }) 2818 // 3. Send another message port (for example, port 0) to the HTML side, which can then save the port for future use. 2819 this.controller.postMessage('__init_port__', [this.ports[0]], '*'); 2820 } catch (error) { 2821 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2822 } 2823 }) 2824 2825 // 4. Use the port on the application side to send messages to the port that has been sent to the HTML side. 2826 Button('SendDataToHTML') 2827 .onClick(() => { 2828 try { 2829 if (this.ports && this.ports[1]) { 2830 this.ports[1].postMessageEvent(this.sendFromEts); 2831 } else { 2832 console.error(`ports is null, Please initialize first`); 2833 } 2834 } catch (error) { 2835 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2836 } 2837 }) 2838 Web({ src: $rawfile('index.html'), controller: this.controller }) 2839 } 2840 } 2841} 2842``` 2843 2844HTML file to be loaded: 2845```html 2846<!--index.html--> 2847<!DOCTYPE html> 2848<html> 2849<head> 2850 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 2851 <title>WebView Message Port Demo</title> 2852</head> 2853 2854 <body> 2855 <h1>WebView Message Port Demo</h1> 2856 <div> 2857 <input type="button" value="SendToEts" onclick="PostMsgToEts(msgFromJS.value);"/><br/> 2858 <input id="msgFromJS" type="text" value="send this message from HTML to ets"/><br/> 2859 </div> 2860 <p class="output">display received message send from ets</p> 2861 </body> 2862 <script src="xxx.js"></script> 2863</html> 2864``` 2865 2866```js 2867//xxx.js 2868var h5Port; 2869var output = document.querySelector('.output'); 2870window.addEventListener('message', function (event) { 2871 if (event.data == '__init_port__') { 2872 if (event.ports[0] != null) { 2873 h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side. 2874 h5Port.onmessage = function (event) { 2875 // 2. Receive the message sent from the eTS side. 2876 var msg = 'Got message from ets:'; 2877 var result = event.data; 2878 if (typeof(result) == "string") { 2879 console.log("received string message from html5, string is:" + result); 2880 msg = msg + result; 2881 } else if (typeof(result) == "object") { 2882 if (result instanceof ArrayBuffer) { 2883 console.log("received arraybuffer from html5, length is:" + result.byteLength); 2884 msg = msg + "length is " + result.byteLength; 2885 } else { 2886 console.log("not support"); 2887 } 2888 } else { 2889 console.log("not support"); 2890 } 2891 output.innerHTML = msg; 2892 } 2893 } 2894 } 2895}) 2896 2897// 3. Use h5Port to send messages to the eTS side. 2898function PostMsgToEts(data) { 2899 if (h5Port) { 2900 h5Port.postMessage(data); 2901 } else { 2902 console.error("h5Port is null, Please initialize first"); 2903 } 2904} 2905``` 2906 2907### requestFocus 2908 2909requestFocus(): void 2910 2911Requests focus for this web page. 2912 2913**System capability**: SystemCapability.Web.Webview.Core 2914 2915**Error codes** 2916 2917For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2918 2919| ID| Error Message | 2920| -------- | ------------------------------------------------------------ | 2921| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2922 2923**Example** 2924 2925```ts 2926// xxx.ets 2927import { webview } from '@kit.ArkWeb'; 2928import { BusinessError } from '@kit.BasicServicesKit'; 2929 2930@Entry 2931@Component 2932struct WebComponent { 2933 controller: webview.WebviewController = new webview.WebviewController(); 2934 2935 build() { 2936 Column() { 2937 Button('requestFocus') 2938 .onClick(() => { 2939 try { 2940 this.controller.requestFocus(); 2941 } catch (error) { 2942 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2943 } 2944 }); 2945 Web({ src: 'www.example.com', controller: this.controller }) 2946 } 2947 } 2948} 2949``` 2950 2951### zoomIn 2952 2953zoomIn(): void 2954 2955Zooms in on this web page by 20%. 2956 2957**System capability**: SystemCapability.Web.Webview.Core 2958 2959**Error codes** 2960 2961For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2962 2963| ID| Error Message | 2964| -------- | ------------------------------------------------------------ | 2965| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2966| 17100004 | Function not enabled. | 2967 2968**Example** 2969 2970```ts 2971// xxx.ets 2972import { webview } from '@kit.ArkWeb'; 2973import { BusinessError } from '@kit.BasicServicesKit'; 2974 2975@Entry 2976@Component 2977struct WebComponent { 2978 controller: webview.WebviewController = new webview.WebviewController(); 2979 2980 build() { 2981 Column() { 2982 Button('zoomIn') 2983 .onClick(() => { 2984 try { 2985 this.controller.zoomIn(); 2986 } catch (error) { 2987 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2988 } 2989 }) 2990 Web({ src: 'www.example.com', controller: this.controller }) 2991 } 2992 } 2993} 2994``` 2995 2996### zoomOut 2997 2998zoomOut(): void 2999 3000Zooms out of this web page by 20%. 3001 3002**System capability**: SystemCapability.Web.Webview.Core 3003 3004**Error codes** 3005 3006For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3007 3008| ID| Error Message | 3009| -------- | ------------------------------------------------------------ | 3010| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3011| 17100004 | Function not enabled. | 3012 3013**Example** 3014 3015```ts 3016// xxx.ets 3017import { webview } from '@kit.ArkWeb'; 3018import { BusinessError } from '@kit.BasicServicesKit'; 3019 3020@Entry 3021@Component 3022struct WebComponent { 3023 controller: webview.WebviewController = new webview.WebviewController(); 3024 3025 build() { 3026 Column() { 3027 Button('zoomOut') 3028 .onClick(() => { 3029 try { 3030 this.controller.zoomOut(); 3031 } catch (error) { 3032 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3033 } 3034 }) 3035 Web({ src: 'www.example.com', controller: this.controller }) 3036 } 3037 } 3038} 3039``` 3040 3041### getHitTestValue 3042 3043getHitTestValue(): HitTestValue 3044 3045Obtains the element information of the area being clicked. 3046 3047**System capability**: SystemCapability.Web.Webview.Core 3048 3049**Return value** 3050 3051| Type | Description | 3052| ------------ | -------------------- | 3053| [HitTestValue](#hittestvalue) | Element information of the area being clicked.| 3054 3055**Error codes** 3056 3057For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3058 3059| ID| Error Message | 3060| -------- | ------------------------------------------------------------ | 3061| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3062 3063**Example** 3064 3065```ts 3066// xxx.ets 3067import { webview } from '@kit.ArkWeb'; 3068import { BusinessError } from '@kit.BasicServicesKit'; 3069 3070@Entry 3071@Component 3072struct WebComponent { 3073 controller: webview.WebviewController = new webview.WebviewController(); 3074 3075 build() { 3076 Column() { 3077 Button('getHitTestValue') 3078 .onClick(() => { 3079 try { 3080 let hitValue = this.controller.getHitTestValue(); 3081 console.log("hitType: " + hitValue.type); 3082 console.log("extra: " + hitValue.extra); 3083 } catch (error) { 3084 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3085 } 3086 }) 3087 Web({ src: 'www.example.com', controller: this.controller }) 3088 } 3089 } 3090} 3091``` 3092 3093### getWebId 3094 3095getWebId(): number 3096 3097Obtains the index value of this **Web** component, which can be used for **Web** component management. 3098 3099**System capability**: SystemCapability.Web.Webview.Core 3100 3101**Return value** 3102 3103| Type | Description | 3104| ------ | --------------------- | 3105| number | Index value of the current **Web** component.| 3106 3107**Error codes** 3108 3109For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3110 3111| ID| Error Message | 3112| -------- | ------------------------------------------------------------ | 3113| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3114 3115**Example** 3116 3117```ts 3118// xxx.ets 3119import { webview } from '@kit.ArkWeb'; 3120import { BusinessError } from '@kit.BasicServicesKit'; 3121 3122@Entry 3123@Component 3124struct WebComponent { 3125 controller: webview.WebviewController = new webview.WebviewController(); 3126 3127 build() { 3128 Column() { 3129 Button('getWebId') 3130 .onClick(() => { 3131 try { 3132 let id = this.controller.getWebId(); 3133 console.log("id: " + id); 3134 } catch (error) { 3135 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3136 } 3137 }) 3138 Web({ src: 'www.example.com', controller: this.controller }) 3139 } 3140 } 3141} 3142``` 3143 3144### getUserAgent 3145 3146getUserAgent(): string 3147 3148Obtains the default user agent of this web page. 3149 3150For details about the default **UserAgent**, see [Default User Agent String](../../web/web-default-userAgent.md). 3151 3152**System capability**: SystemCapability.Web.Webview.Core 3153 3154**Return value** 3155 3156| Type | Description | 3157| ------ | -------------- | 3158| string | Default user agent.| 3159 3160**Error codes** 3161 3162For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3163 3164| ID| Error Message | 3165| -------- | ------------------------------------------------------------ | 3166| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3167 3168**Example** 3169 3170```ts 3171// xxx.ets 3172import { webview } from '@kit.ArkWeb'; 3173import { BusinessError } from '@kit.BasicServicesKit'; 3174 3175@Entry 3176@Component 3177struct WebComponent { 3178 controller: webview.WebviewController = new webview.WebviewController(); 3179 3180 build() { 3181 Column() { 3182 Button('getUserAgent') 3183 .onClick(() => { 3184 try { 3185 let userAgent = this.controller.getUserAgent(); 3186 console.log("userAgent: " + userAgent); 3187 } catch (error) { 3188 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3189 } 3190 }) 3191 Web({ src: 'www.example.com', controller: this.controller }) 3192 } 3193 } 3194} 3195``` 3196 3197You can define a custom user agent based on the default user agent. 3198```ts 3199// xxx.ets 3200import { webview } from '@kit.ArkWeb'; 3201import { BusinessError } from '@kit.BasicServicesKit'; 3202 3203@Entry 3204@Component 3205struct WebComponent { 3206 controller: webview.WebviewController = new webview.WebviewController(); 3207 @State ua: string = ""; 3208 3209 aboutToAppear(): void { 3210 webview.once('webInited', () => { 3211 try { 3212 // Define a custom user agent on the application side. 3213 this.ua = this.controller.getUserAgent() + 'xxx'; 3214 this.controller.setCustomUserAgent(this.ua); 3215 } catch (error) { 3216 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3217 } 3218 }) 3219 } 3220 3221 build() { 3222 Column() { 3223 Web({ src: 'www.example.com', controller: this.controller }) 3224 } 3225 } 3226} 3227``` 3228 3229### getTitle 3230 3231getTitle(): string 3232 3233Obtains the title of the current web page. 3234 3235**System capability**: SystemCapability.Web.Webview.Core 3236 3237**Return value** 3238 3239| Type | Description | 3240| ------ | -------------------- | 3241| string | Title of the current web page.| 3242 3243**Error codes** 3244 3245For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3246 3247| ID| Error Message | 3248| -------- | ------------------------------------------------------------ | 3249| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3250 3251**Example** 3252 3253```ts 3254// xxx.ets 3255import { webview } from '@kit.ArkWeb'; 3256import { BusinessError } from '@kit.BasicServicesKit'; 3257 3258@Entry 3259@Component 3260struct WebComponent { 3261 controller: webview.WebviewController = new webview.WebviewController(); 3262 3263 build() { 3264 Column() { 3265 Button('getTitle') 3266 .onClick(() => { 3267 try { 3268 let title = this.controller.getTitle(); 3269 console.log("title: " + title); 3270 } catch (error) { 3271 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3272 } 3273 }) 3274 Web({ src: 'www.example.com', controller: this.controller }) 3275 } 3276 } 3277} 3278``` 3279 3280### getPageHeight 3281 3282getPageHeight(): number 3283 3284Obtains the height of this web page. 3285 3286**System capability**: SystemCapability.Web.Webview.Core 3287 3288**Return value** 3289 3290| Type | Description | 3291| ------ | -------------------- | 3292| number | Height of the current web page. Unit: px| 3293 3294**Error codes** 3295 3296For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3297 3298| ID| Error Message | 3299| -------- | ------------------------------------------------------------ | 3300| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3301 3302**Example** 3303 3304```ts 3305// xxx.ets 3306import { webview } from '@kit.ArkWeb'; 3307import { BusinessError } from '@kit.BasicServicesKit'; 3308 3309@Entry 3310@Component 3311struct WebComponent { 3312 controller: webview.WebviewController = new webview.WebviewController(); 3313 3314 build() { 3315 Column() { 3316 Button('getPageHeight') 3317 .onClick(() => { 3318 try { 3319 let pageHeight = this.controller.getPageHeight(); 3320 console.log("pageHeight : " + pageHeight); 3321 } catch (error) { 3322 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3323 } 3324 }) 3325 Web({ src: 'www.example.com', controller: this.controller }) 3326 } 3327 } 3328} 3329``` 3330 3331### storeWebArchive 3332 3333storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback\<string>): void 3334 3335Stores this web page. This API uses an asynchronous callback to return the result. 3336 3337**System capability**: SystemCapability.Web.Webview.Core 3338 3339**Parameters** 3340 3341| Name | Type | Mandatory| Description | 3342| -------- | --------------------- | ---- | ------------------------------------------------------------ | 3343| baseName | string | Yes | Save path of the web page. The value cannot be null. | 3344| 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.| 3345| callback | AsyncCallback\<string> | Yes | Callback used to return the save path if the operation is successful and null otherwise. | 3346 3347**Error codes** 3348 3349For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3350 3351| ID| Error Message | 3352| -------- | ------------------------------------------------------------ | 3353| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3354| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3355| 17100003 | Invalid resource path or file type. | 3356 3357**Example** 3358 3359```ts 3360// xxx.ets 3361import { webview } from '@kit.ArkWeb'; 3362import { BusinessError } from '@kit.BasicServicesKit'; 3363 3364@Entry 3365@Component 3366struct WebComponent { 3367 controller: webview.WebviewController = new webview.WebviewController(); 3368 3369 build() { 3370 Column() { 3371 Button('storeWebArchive') 3372 .onClick(() => { 3373 try { 3374 this.controller.storeWebArchive("/data/storage/el2/base/", true, (error, filename) => { 3375 if (error) { 3376 console.error(`save web archive error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3377 return; 3378 } 3379 if (filename != null) { 3380 console.info(`save web archive success: ${filename}`); 3381 } 3382 }); 3383 } catch (error) { 3384 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3385 } 3386 }) 3387 Web({ src: 'www.example.com', controller: this.controller }) 3388 } 3389 } 3390} 3391``` 3392 3393### storeWebArchive 3394 3395storeWebArchive(baseName: string, autoName: boolean): Promise\<string> 3396 3397Stores this web page. This API uses a promise to return the result. 3398 3399**System capability**: SystemCapability.Web.Webview.Core 3400 3401**Parameters** 3402 3403| Name | Type| Mandatory| Description | 3404| -------- | -------- | ---- | ------------------------------------------------------------ | 3405| baseName | string | Yes | Save path of the web page. The value cannot be null. | 3406| 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.| 3407 3408**Return value** 3409 3410| Type | Description | 3411| --------------- | ----------------------------------------------------- | 3412| Promise\<string> | Promise used to return the save path if the operation is successful and null otherwise.| 3413 3414**Error codes** 3415 3416For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3417 3418| ID| Error Message | 3419| -------- | ------------------------------------------------------------ | 3420| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3421| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3422| 17100003 | Invalid resource path or file type. | 3423 3424**Example** 3425 3426```ts 3427// xxx.ets 3428import { webview } from '@kit.ArkWeb'; 3429import { BusinessError } from '@kit.BasicServicesKit'; 3430 3431@Entry 3432@Component 3433struct WebComponent { 3434 controller: webview.WebviewController = new webview.WebviewController(); 3435 3436 build() { 3437 Column() { 3438 Button('storeWebArchive') 3439 .onClick(() => { 3440 try { 3441 this.controller.storeWebArchive("/data/storage/el2/base/", true) 3442 .then(filename => { 3443 if (filename != null) { 3444 console.info(`save web archive success: ${filename}`) 3445 } 3446 }) 3447 .catch((error: BusinessError) => { 3448 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 3449 }) 3450 } catch (error) { 3451 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3452 } 3453 }) 3454 Web({ src: 'www.example.com', controller: this.controller }) 3455 } 3456 } 3457} 3458``` 3459 3460### getUrl 3461 3462getUrl(): string 3463 3464Obtains the URL of this page. 3465 3466**System capability**: SystemCapability.Web.Webview.Core 3467 3468**Return value** 3469 3470| Type | Description | 3471| ------ | ------------------- | 3472| string | URL of the current page.| 3473 3474**Error codes** 3475 3476For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3477 3478| ID| Error Message | 3479| -------- | ------------------------------------------------------------ | 3480| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3481 3482**Example** 3483 3484```ts 3485// xxx.ets 3486import { webview } from '@kit.ArkWeb'; 3487import { BusinessError } from '@kit.BasicServicesKit'; 3488 3489@Entry 3490@Component 3491struct WebComponent { 3492 controller: webview.WebviewController = new webview.WebviewController(); 3493 3494 build() { 3495 Column() { 3496 Button('getUrl') 3497 .onClick(() => { 3498 try { 3499 let url = this.controller.getUrl(); 3500 console.log("url: " + url); 3501 } catch (error) { 3502 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3503 } 3504 }) 3505 Web({ src: 'www.example.com', controller: this.controller }) 3506 } 3507 } 3508} 3509``` 3510 3511### stop 3512 3513stop(): void 3514 3515Stops page loading. 3516 3517**System capability**: SystemCapability.Web.Webview.Core 3518 3519**Error codes** 3520 3521For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3522 3523| ID| Error Message | 3524| -------- | ------------------------------------------------------------ | 3525| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3526 3527**Example** 3528 3529```ts 3530// xxx.ets 3531import { webview } from '@kit.ArkWeb'; 3532import { BusinessError } from '@kit.BasicServicesKit'; 3533 3534@Entry 3535@Component 3536struct WebComponent { 3537 controller: webview.WebviewController = new webview.WebviewController(); 3538 3539 build() { 3540 Column() { 3541 Button('stop') 3542 .onClick(() => { 3543 try { 3544 this.controller.stop(); 3545 } catch (error) { 3546 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3547 } 3548 }); 3549 Web({ src: 'www.example.com', controller: this.controller }) 3550 } 3551 } 3552} 3553``` 3554 3555### backOrForward 3556 3557backOrForward(step: number): void 3558 3559Performs 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. 3560 3561Because the previously loaded web pages are used for the operation, no page reloading is involved. 3562 3563**System capability**: SystemCapability.Web.Webview.Core 3564 3565**Parameters** 3566 3567| Name| Type| Mandatory| Description | 3568| ------ | -------- | ---- | ---------------------- | 3569| step | number | Yes | Number of the steps to take.| 3570 3571**Error codes** 3572 3573For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3574 3575| ID| Error Message | 3576| -------- | ------------------------------------------------------------ | 3577| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3578| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3579 3580**Example** 3581 3582```ts 3583// xxx.ets 3584import { webview } from '@kit.ArkWeb'; 3585import { BusinessError } from '@kit.BasicServicesKit'; 3586 3587@Entry 3588@Component 3589struct WebComponent { 3590 controller: webview.WebviewController = new webview.WebviewController(); 3591 @State step: number = -2; 3592 3593 build() { 3594 Column() { 3595 Button('backOrForward') 3596 .onClick(() => { 3597 try { 3598 this.controller.backOrForward(this.step); 3599 } catch (error) { 3600 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3601 } 3602 }) 3603 Web({ src: 'www.example.com', controller: this.controller }) 3604 } 3605 } 3606} 3607``` 3608 3609### scrollTo 3610 3611scrollTo(x:number, y:number, duration?:number): void 3612 3613Scrolls the page to the specified absolute position within a specified period. 3614 3615**System capability**: SystemCapability.Web.Webview.Core 3616 3617**Parameters** 3618 3619| Name| Type| Mandatory| Description | 3620| ------ | -------- | ---- | ---------------------- | 3621| x | number | Yes | X coordinate of the absolute position. If the value is a negative number, the value 0 is used.| 3622| y | number | Yes | Y coordinate of the absolute position. If the value is a negative number, the value 0 is used.| 3623| duration<sup>13+</sup> | number | No| Scrolling animation duration,<br>in milliseconds.<br>If no value is input or the input value is a negative number or 0, the animation is disabled.| 3624 3625**Error codes** 3626 3627For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3628 3629| ID| Error Message | 3630| -------- | ------------------------------------------------------------ | 3631| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3632| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3633 3634**Example** 3635 3636```ts 3637// xxx.ets 3638import { webview } from '@kit.ArkWeb'; 3639import { BusinessError } from '@kit.BasicServicesKit'; 3640 3641@Entry 3642@Component 3643struct WebComponent { 3644 controller: webview.WebviewController = new webview.WebviewController(); 3645 3646 build() { 3647 Column() { 3648 Button('scrollTo') 3649 .onClick(() => { 3650 try { 3651 this.controller.scrollTo(50, 50, 500); 3652 } catch (error) { 3653 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3654 } 3655 }) 3656 Button('stopScroll') 3657 .onClick(() => { 3658 try { 3659 this.controller.scrollBy(0, 0, 1); // If you want to stop the animation generated by the current scroll, you can generate another 1ms animation to interrupt the animation. 3660 } catch (error) { 3661 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3662 } 3663 }) 3664 Web({ src: $rawfile('index.html'), controller: this.controller }) 3665 } 3666 } 3667} 3668``` 3669 3670HTML file to be loaded: 3671```html 3672<!--index.html--> 3673<!DOCTYPE html> 3674<html> 3675<head> 3676 <title>Demo</title> 3677 <style> 3678 body { 3679 width:2000px; 3680 height:2000px; 3681 padding-right:170px; 3682 padding-left:170px; 3683 border:5px solid blueviolet 3684 } 3685 </style> 3686</head> 3687<body> 3688Scroll Test 3689</body> 3690</html> 3691``` 3692 3693### scrollBy 3694 3695scrollBy(deltaX:number, deltaY:number,duration?:number): void 3696 3697Scrolls the page by the specified amount within a specified period. 3698 3699**System capability**: SystemCapability.Web.Webview.Core 3700 3701**Parameters** 3702 3703| Name| Type| Mandatory| Description | 3704| ------ | -------- | ---- | ---------------------- | 3705| deltaX | number | Yes | Amount to scroll by along the x-axis. The positive direction is rightward.| 3706| deltaY | number | Yes | Amount to scroll by along the y-axis. The positive direction is downward.| 3707| duration<sup>13+</sup> | number | No| Scrolling animation duration,<br>in milliseconds.<br>If no value is input or the input value is a negative number or 0, the animation is disabled.| 3708**Error codes** 3709 3710For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3711 3712| ID| Error Message | 3713| -------- | ------------------------------------------------------------ | 3714| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3715| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3716 3717> **NOTE** 3718> 3719> Calling **scrollBy** does not trigger the nested scrolling of the parent component. 3720 3721**Example** 3722 3723```ts 3724// xxx.ets 3725import { webview } from '@kit.ArkWeb'; 3726import { BusinessError } from '@kit.BasicServicesKit'; 3727 3728@Entry 3729@Component 3730struct WebComponent { 3731 controller: webview.WebviewController = new webview.WebviewController(); 3732 3733 build() { 3734 Column() { 3735 Button('scrollBy') 3736 .onClick(() => { 3737 try { 3738 this.controller.scrollBy(50, 50, 500); 3739 } catch (error) { 3740 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3741 } 3742 }) 3743 Button('stopScroll') 3744 .onClick(() => { 3745 try { 3746 this.controller.scrollBy(0, 0, 1); // If you want to stop the animation generated by the current scroll, you can generate another 1ms animation to interrupt the animation. 3747 } catch (error) { 3748 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3749 } 3750 Web({ src: $rawfile('index.html'), controller: this.controller }) 3751 } 3752 } 3753} 3754``` 3755 3756HTML file to be loaded: 3757```html 3758<!--index.html--> 3759<!DOCTYPE html> 3760<html> 3761<head> 3762 <title>Demo</title> 3763 <style> 3764 body { 3765 width:2000px; 3766 height:2000px; 3767 padding-right:170px; 3768 padding-left:170px; 3769 border:5px solid blueviolet 3770 } 3771 </style> 3772</head> 3773<body> 3774Scroll Test 3775</body> 3776</html> 3777``` 3778### scrollByWithResult<sup>12+</sup> 3779 3780scrollByWithResult(deltaX:number, deltaY:number): boolean 3781 3782Scrolls the page by the specified amount and returns value to indicate whether the scrolling is successful. 3783 3784**System capability**: SystemCapability.Web.Webview.Core 3785 3786**Parameters** 3787 3788| Name| Type| Mandatory| Description | 3789| ------ | -------- | ---- | ---------------------- | 3790| deltaX | number | Yes | Amount to scroll by along the x-axis. The positive direction is rightward.| 3791| deltaY | number | Yes | Amount to scroll by along the y-axis. The positive direction is downward.| 3792 3793**Return value** 3794 3795| Type | Description | 3796| ------- | --------------------------------------- | 3797| boolean | Whether the current web page can be scrolled. The default value is **false**.| 3798 3799**Error codes** 3800 3801For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3802 3803| ID| Error Message | 3804| -------- | ------------------------------------------------------------ | 3805| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3806 3807> **NOTE** 3808> 3809> - If the web page is being touched, **false** is returned. Otherwise, **true** is returned. 3810> - If the rendering area at the same layer of the web page is being touched, **true** is returned. 3811> - Calling **scrollByWithResult** does not trigger the nested scrolling of the parent component. 3812> - This API does not support the high frame rate of scrolling performance. 3813 3814**Example** 3815 3816```ts 3817// xxx.ets 3818import { webview } from '@kit.ArkWeb'; 3819import { BusinessError } from '@kit.BasicServicesKit'; 3820 3821@Entry 3822@Component 3823struct WebComponent { 3824 controller: webview.WebviewController = new webview.WebviewController(); 3825 3826 build() { 3827 Column() { 3828 Button('scrollByWithResult') 3829 .onClick(() => { 3830 try { 3831 let result = this.controller.scrollByWithResult(50, 50); 3832 console.log("original result: " + result); 3833 } catch (error) { 3834 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3835 } 3836 }) 3837 Web({ src: $rawfile('index.html'), controller: this.controller }) 3838 } 3839 } 3840} 3841``` 3842 3843HTML file to be loaded: 3844```html 3845<!--index.html--> 3846<!DOCTYPE html> 3847<html> 3848<head> 3849 <title>Demo</title> 3850 <style> 3851 body { 3852 width:2000px; 3853 height:2000px; 3854 padding-right:170px; 3855 padding-left:170px; 3856 border:5px solid blueviolet 3857 } 3858 </style> 3859</head> 3860<body> 3861Scroll Test 3862</body> 3863</html> 3864``` 3865### slideScroll 3866 3867slideScroll(vx:number, vy:number): void 3868 3869Simulates a slide-to-scroll action on the page at the specified velocity. 3870 3871**System capability**: SystemCapability.Web.Webview.Core 3872 3873**Parameters** 3874 3875| Name| Type| Mandatory| Description | 3876| ------ | -------- | ---- | ---------------------- | 3877| vx | number | Yes | Horizontal velocity component of the slide-to-scroll action, where the positive direction is rightward.| 3878| vy | number | Yes | Vertical velocity component of the slide-to-scroll action, where the positive direction is downward.| 3879 3880**Error codes** 3881 3882For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3883 3884| ID| Error Message | 3885| -------- | ------------------------------------------------------------ | 3886| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3887| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3888 3889**Example** 3890 3891```ts 3892// xxx.ets 3893import { webview } from '@kit.ArkWeb'; 3894import { BusinessError } from '@kit.BasicServicesKit'; 3895 3896@Entry 3897@Component 3898struct WebComponent { 3899 controller: webview.WebviewController = new webview.WebviewController(); 3900 3901 build() { 3902 Column() { 3903 Button('slideScroll') 3904 .onClick(() => { 3905 try { 3906 this.controller.slideScroll(500, 500); 3907 } catch (error) { 3908 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3909 } 3910 }) 3911 Web({ src: $rawfile('index.html'), controller: this.controller }) 3912 } 3913 } 3914} 3915``` 3916 3917HTML file to be loaded: 3918```html 3919<!--index.html--> 3920<!DOCTYPE html> 3921<html> 3922<head> 3923 <title>Demo</title> 3924 <style> 3925 body { 3926 width:3000px; 3927 height:3000px; 3928 padding-right:170px; 3929 padding-left:170px; 3930 border:5px solid blueviolet 3931 } 3932 </style> 3933</head> 3934<body> 3935Scroll Test 3936</body> 3937</html> 3938``` 3939 3940### getOriginalUrl 3941 3942getOriginalUrl(): string 3943 3944Obtains the original URL of this page. 3945Risk warning: If you want to obtain the URL for JavaScriptProxy communication API authentication, use [getLastJavascriptProxyCallingFrameUrl<sup>12+</sup>](#getlastjavascriptproxycallingframeurl12). 3946 3947**System capability**: SystemCapability.Web.Webview.Core 3948 3949**Return value** 3950 3951| Type | Description | 3952| ------ | ----------------------- | 3953| string | Original URL of the current page.| 3954 3955**Error codes** 3956 3957For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3958 3959| ID| Error Message | 3960| -------- | ------------------------------------------------------------ | 3961| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3962 3963**Example** 3964 3965```ts 3966// xxx.ets 3967import { webview } from '@kit.ArkWeb'; 3968import { BusinessError } from '@kit.BasicServicesKit'; 3969 3970@Entry 3971@Component 3972struct WebComponent { 3973 controller: webview.WebviewController = new webview.WebviewController(); 3974 3975 build() { 3976 Column() { 3977 Button('getOrgUrl') 3978 .onClick(() => { 3979 try { 3980 let url = this.controller.getOriginalUrl(); 3981 console.log("original url: " + url); 3982 } catch (error) { 3983 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3984 } 3985 }) 3986 Web({ src: 'www.example.com', controller: this.controller }) 3987 } 3988 } 3989} 3990``` 3991 3992### getFavicon 3993 3994getFavicon(): image.PixelMap 3995 3996Obtains the favicon of this page. 3997 3998**System capability**: SystemCapability.Web.Webview.Core 3999 4000**Return value** 4001 4002| Type | Description | 4003| -------------------------------------- | ------------------------------- | 4004| [PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | **PixelMap** object of the favicon of the page.| 4005 4006**Error codes** 4007 4008For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4009 4010| ID| Error Message | 4011| -------- | ------------------------------------------------------------ | 4012| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4013 4014**Example** 4015 4016```ts 4017// xxx.ets 4018import { webview } from '@kit.ArkWeb'; 4019import { BusinessError } from '@kit.BasicServicesKit'; 4020import { image } from '@kit.ImageKit'; 4021 4022@Entry 4023@Component 4024struct WebComponent { 4025 controller: webview.WebviewController = new webview.WebviewController(); 4026 @State pixelmap: image.PixelMap | undefined = undefined; 4027 4028 build() { 4029 Column() { 4030 Button('getFavicon') 4031 .onClick(() => { 4032 try { 4033 this.pixelmap = this.controller.getFavicon(); 4034 } catch (error) { 4035 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4036 } 4037 }) 4038 Web({ src: 'www.example.com', controller: this.controller }) 4039 } 4040 } 4041} 4042``` 4043 4044### setNetworkAvailable 4045 4046setNetworkAvailable(enable: boolean): void 4047 4048Sets the **window.navigator.onLine** attribute in JavaScript. 4049 4050**System capability**: SystemCapability.Web.Webview.Core 4051 4052**Parameters** 4053 4054| Name| Type | Mandatory| Description | 4055| ------ | ------- | ---- | --------------------------------- | 4056| enable | boolean | Yes | Whether to enable **window.navigator.onLine**.| 4057 4058**Error codes** 4059 4060For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4061 4062| ID| Error Message | 4063| -------- | ------------------------------------------------------------ | 4064| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4065| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4066 4067**Example** 4068 4069```ts 4070// xxx.ets 4071import { webview } from '@kit.ArkWeb'; 4072import { BusinessError } from '@kit.BasicServicesKit'; 4073 4074@Entry 4075@Component 4076struct WebComponent { 4077 controller: webview.WebviewController = new webview.WebviewController(); 4078 4079 build() { 4080 Column() { 4081 Button('setNetworkAvailable') 4082 .onClick(() => { 4083 try { 4084 this.controller.setNetworkAvailable(true); 4085 } catch (error) { 4086 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4087 } 4088 }) 4089 Web({ src: $rawfile('index.html'), controller: this.controller }) 4090 } 4091 } 4092} 4093``` 4094 4095HTML file to be loaded: 4096```html 4097<!-- index.html --> 4098<!DOCTYPE html> 4099<html> 4100<body> 4101<h1>online attribute </h1> 4102<p id="demo"></p> 4103<button onclick="func()">click</button> 4104<script> 4105 let online = navigator.onLine; 4106 document.getElementById ("demo").innerHTML = "Browser online:" + online; 4107 4108 function func(){ 4109 var online = navigator.onLine; 4110 document.getElementById ("demo").innerHTML = "Browser online:" + online; 4111 } 4112</script> 4113</body> 4114</html> 4115``` 4116 4117### hasImage 4118 4119hasImage(callback: AsyncCallback\<boolean>): void 4120 4121Checks whether this page contains images. This API uses an asynchronous callback to return the result. 4122 4123**System capability**: SystemCapability.Web.Webview.Core 4124 4125**Parameters** 4126 4127| Name | Type | Mandatory| Description | 4128| -------- | ----------------------- | ---- | -------------------------- | 4129| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result.| 4130 4131**Error codes** 4132 4133For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4134 4135| ID| Error Message | 4136| -------- | ------------------------------------------------------------ | 4137| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4138| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4139 4140**Example** 4141 4142```ts 4143// xxx.ets 4144import { webview } from '@kit.ArkWeb'; 4145import { BusinessError } from '@kit.BasicServicesKit'; 4146 4147@Entry 4148@Component 4149struct WebComponent { 4150 controller: webview.WebviewController = new webview.WebviewController(); 4151 4152 build() { 4153 Column() { 4154 Button('hasImageCb') 4155 .onClick(() => { 4156 try { 4157 this.controller.hasImage((error, data) => { 4158 if (error) { 4159 console.error(`hasImage error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4160 return; 4161 } 4162 console.info("hasImage: " + data); 4163 }); 4164 } catch (error) { 4165 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4166 } 4167 }) 4168 Web({ src: 'www.example.com', controller: this.controller }) 4169 } 4170 } 4171} 4172``` 4173 4174### hasImage 4175 4176hasImage(): Promise\<boolean> 4177 4178Checks whether this page contains images. This API uses a promise to return the result. 4179 4180**System capability**: SystemCapability.Web.Webview.Core 4181 4182**Return value** 4183 4184| Type | Description | 4185| ----------------- | --------------------------------------- | 4186| Promise\<boolean> | Promise used to return the result.| 4187 4188**Error codes** 4189 4190For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4191 4192| ID| Error Message | 4193| -------- | ------------------------------------------------------------ | 4194| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4195| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 4196 4197**Example** 4198 4199```ts 4200// xxx.ets 4201import { webview } from '@kit.ArkWeb'; 4202import { BusinessError } from '@kit.BasicServicesKit'; 4203 4204@Entry 4205@Component 4206struct WebComponent { 4207 controller: webview.WebviewController = new webview.WebviewController(); 4208 4209 build() { 4210 Column() { 4211 Button('hasImagePm') 4212 .onClick(() => { 4213 try { 4214 this.controller.hasImage().then((data) => { 4215 console.info('hasImage: ' + data); 4216 }).catch((error: BusinessError) => { 4217 console.error("error: " + error); 4218 }) 4219 } catch (error) { 4220 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4221 } 4222 }) 4223 Web({ src: 'www.example.com', controller: this.controller }) 4224 } 4225 } 4226} 4227``` 4228 4229### removeCache 4230 4231removeCache(clearRom: boolean): void 4232 4233Clears the cache in the application. This API will clear the cache for all webviews in the same application. 4234 4235**System capability**: SystemCapability.Web.Webview.Core 4236 4237**Parameters** 4238 4239| Name | Type | Mandatory| Description | 4240| -------- | ------- | ---- | -------------------------------------------------------- | 4241| 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.| 4242 4243**Error codes** 4244 4245For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4246 4247| ID| Error Message | 4248| -------- | ------------------------------------------------------------ | 4249| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4250| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4251 4252**Example** 4253 4254```ts 4255// xxx.ets 4256import { webview } from '@kit.ArkWeb'; 4257import { BusinessError } from '@kit.BasicServicesKit'; 4258 4259@Entry 4260@Component 4261struct WebComponent { 4262 controller: webview.WebviewController = new webview.WebviewController(); 4263 4264 build() { 4265 Column() { 4266 Button('removeCache') 4267 .onClick(() => { 4268 try { 4269 this.controller.removeCache(false); 4270 } catch (error) { 4271 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4272 } 4273 }) 4274 Web({ src: 'www.example.com', controller: this.controller }) 4275 } 4276 } 4277} 4278``` 4279 4280### pageUp 4281 4282pageUp(top: boolean): void 4283 4284Scrolls the page up by half the viewport or jumps to the top of the page. 4285 4286**System capability**: SystemCapability.Web.Webview.Core 4287 4288**Parameters** 4289 4290| Name| Type | Mandatory| Description | 4291| ------ | ------- | ---- | ------------------------------------------------------------ | 4292| 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.| 4293 4294**Error codes** 4295 4296For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4297 4298| ID| Error Message | 4299| -------- | ------------------------------------------------------------ | 4300| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4301| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4302 4303**Example** 4304 4305```ts 4306// xxx.ets 4307import { webview } from '@kit.ArkWeb'; 4308import { BusinessError } from '@kit.BasicServicesKit'; 4309 4310@Entry 4311@Component 4312struct WebComponent { 4313 controller: webview.WebviewController = new webview.WebviewController(); 4314 4315 build() { 4316 Column() { 4317 Button('pageUp') 4318 .onClick(() => { 4319 try { 4320 this.controller.pageUp(false); 4321 } catch (error) { 4322 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4323 } 4324 }) 4325 Web({ src: 'www.example.com', controller: this.controller }) 4326 } 4327 } 4328} 4329``` 4330 4331### pageDown 4332 4333pageDown(bottom: boolean): void 4334 4335Scrolls the page down by half the viewport or jumps to the bottom of the page. 4336 4337**System capability**: SystemCapability.Web.Webview.Core 4338 4339**Parameters** 4340 4341| Name| Type | Mandatory| Description | 4342| ------ | ------- | ---- | ------------------------------------------------------------ | 4343| 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.| 4344 4345**Error codes** 4346 4347For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4348 4349| ID| Error Message | 4350| -------- | ------------------------------------------------------------ | 4351| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4352| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4353 4354**Example** 4355 4356```ts 4357// xxx.ets 4358import { webview } from '@kit.ArkWeb'; 4359import { BusinessError } from '@kit.BasicServicesKit'; 4360 4361@Entry 4362@Component 4363struct WebComponent { 4364 controller: webview.WebviewController = new webview.WebviewController(); 4365 4366 build() { 4367 Column() { 4368 Button('pageDown') 4369 .onClick(() => { 4370 try { 4371 this.controller.pageDown(false); 4372 } catch (error) { 4373 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4374 } 4375 }) 4376 Web({ src: 'www.example.com', controller: this.controller }) 4377 } 4378 } 4379} 4380``` 4381 4382### getBackForwardEntries 4383 4384getBackForwardEntries(): BackForwardList 4385 4386Obtains the historical information list of the current webview. 4387 4388**System capability**: SystemCapability.Web.Webview.Core 4389 4390**Return value** 4391 4392| Type | Description | 4393| ----------------------------------- | --------------------------- | 4394| [BackForwardList](#backforwardlist) | The historical information list of the current webview.| 4395 4396**Error codes** 4397 4398For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4399 4400| ID| Error Message | 4401| -------- | ------------------------------------------------------------ | 4402| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4403 4404**Example** 4405 4406```ts 4407// xxx.ets 4408import { webview } from '@kit.ArkWeb'; 4409import { BusinessError } from '@kit.BasicServicesKit'; 4410 4411@Entry 4412@Component 4413struct WebComponent { 4414 controller: webview.WebviewController = new webview.WebviewController(); 4415 4416 build() { 4417 Column() { 4418 Button('getBackForwardEntries') 4419 .onClick(() => { 4420 try { 4421 let list = this.controller.getBackForwardEntries() 4422 } catch (error) { 4423 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4424 } 4425 }) 4426 Web({ src: 'www.example.com', controller: this.controller }) 4427 } 4428 } 4429} 4430``` 4431 4432### serializeWebState 4433 4434serializeWebState(): Uint8Array 4435 4436Serializes the page status history of the current Webview. 4437 4438**System capability**: SystemCapability.Web.Webview.Core 4439 4440**Return value** 4441 4442| Type | Description | 4443| ---------- | --------------------------------------------- | 4444| Uint8Array | Serialized data of the page status history of the current WebView.| 4445 4446**Error codes** 4447 4448For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4449 4450| ID| Error Message | 4451| -------- | ------------------------------------------------------------ | 4452| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4453 4454**Example** 4455 44561. To perform operations on files, you must first import the **fs** module. For details, see [File Management](../apis-core-file-kit/js-apis-file-fs.md). 4457```ts 4458// xxx.ets 4459import { webview } from '@kit.ArkWeb'; 4460import { BusinessError } from '@kit.BasicServicesKit'; 4461import { fileIo } from '@kit.CoreFileKit'; 4462 4463@Entry 4464@Component 4465struct WebComponent { 4466 controller: webview.WebviewController = new webview.WebviewController(); 4467 4468 build() { 4469 Column() { 4470 Button('serializeWebState') 4471 .onClick(() => { 4472 try { 4473 let state = this.controller.serializeWebState(); 4474 let path:string | undefined = AppStorage.get("cacheDir"); 4475 if (path) { 4476 path += '/WebState'; 4477 // Synchronously open a file. 4478 let file = fileIo.openSync(path, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); 4479 fileIo.writeSync(file.fd, state.buffer); 4480 fileIo.closeSync(file.fd); 4481 } 4482 } catch (error) { 4483 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4484 } 4485 }) 4486 Web({ src: 'www.example.com', controller: this.controller }) 4487 } 4488 } 4489} 4490``` 4491 44922. Modify the **EntryAbility.ets** file. 4493Obtain the path of the application cache file. 4494```ts 4495// xxx.ets 4496import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 4497 4498export default class EntryAbility extends UIAbility { 4499 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 4500 // Data synchronization between the UIAbility component and the page can be implemented by binding cacheDir to the AppStorage object. 4501 AppStorage.setOrCreate("cacheDir", this.context.cacheDir); 4502 } 4503} 4504``` 4505 4506### restoreWebState 4507 4508restoreWebState(state: Uint8Array): void 4509 4510Restores the page status history from the serialized data of the current WebView. 4511 4512**System capability**: SystemCapability.Web.Webview.Core 4513 4514**Parameters** 4515 4516| Name| Type | Mandatory| Description | 4517| ------ | ---------- | ---- | ---------------------------- | 4518| state | Uint8Array | Yes | Serialized data of the page status history.| 4519 4520**Error codes** 4521 4522For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4523 4524| ID| Error Message | 4525| -------- | ------------------------------------------------------------ | 4526| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4527| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 4528 4529**Example** 4530 45311. To perform operations on files, you must first import the **fs** module. For details, see [File Management](../apis-core-file-kit/js-apis-file-fs.md). 4532```ts 4533// xxx.ets 4534import { webview } from '@kit.ArkWeb'; 4535import { BusinessError } from '@kit.BasicServicesKit'; 4536import { fileIo } from '@kit.CoreFileKit'; 4537 4538@Entry 4539@Component 4540struct WebComponent { 4541 controller: webview.WebviewController = new webview.WebviewController(); 4542 4543 build() { 4544 Column() { 4545 Button('RestoreWebState') 4546 .onClick(() => { 4547 try { 4548 let path: string | undefined = AppStorage.get("cacheDir"); 4549 if (path) { 4550 path += '/WebState'; 4551 // Synchronously open a file. 4552 let file = fileIo.openSync(path, fileIo.OpenMode.READ_WRITE); 4553 let stat = fileIo.statSync(path); 4554 let size = stat.size; 4555 let buf = new ArrayBuffer(size); 4556 fileIo.read(file.fd, buf, (err, readLen) => { 4557 if (err) { 4558 console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); 4559 } else { 4560 console.info("read file data succeed"); 4561 this.controller.restoreWebState(new Uint8Array(buf.slice(0, readLen))); 4562 fileIo.closeSync(file); 4563 } 4564 }); 4565 } 4566 } catch (error) { 4567 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4568 } 4569 }) 4570 Web({ src: 'www.example.com', controller: this.controller }) 4571 } 4572 } 4573} 4574``` 4575 45762. Modify the **EntryAbility.ets** file. 4577Obtain the path of the application cache file. 4578```ts 4579// xxx.ets 4580import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 4581 4582export default class EntryAbility extends UIAbility { 4583 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 4584 // Data synchronization between the UIAbility component and the page can be implemented by binding cacheDir to the AppStorage object. 4585 AppStorage.setOrCreate("cacheDir", this.context.cacheDir); 4586 } 4587} 4588``` 4589 4590### customizeSchemes 4591 4592static customizeSchemes(schemes: Array\<WebCustomScheme\>): void 4593 4594Grants the cross-domain request and fetch request permissions for the specified URL schemes (also known as protocols) to the web kernel. A cross-domain fetch request for any of the specified URL schemes can be intercepted by the **onInterceptRequest** API, so that you can further process the request. It is recommended that this API be called before any **Web** component is initialized. 4595 4596**System capability**: SystemCapability.Web.Webview.Core 4597 4598**Parameters** 4599 4600| Name | Type | Mandatory| Description | 4601| -------- | ------- | ---- | -------------------------------------- | 4602| schemes | Array\<[WebCustomScheme](#webcustomscheme)\> | Yes | Array of up to 10 custom schemes.| 4603 4604**Error codes** 4605 4606For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4607 4608| ID| Error Message | 4609| -------- | ------------------------------------------------------------ | 4610| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4611| 17100020 | Failed to register custom schemes. | 4612 4613**Example** 4614 4615```ts 4616// xxx.ets 4617import { webview } from '@kit.ArkWeb'; 4618import { BusinessError } from '@kit.BasicServicesKit'; 4619 4620@Entry 4621@Component 4622struct WebComponent { 4623 controller: webview.WebviewController = new webview.WebviewController(); 4624 responseWeb: WebResourceResponse = new WebResourceResponse(); 4625 scheme1: webview.WebCustomScheme = { schemeName: "name1", isSupportCORS: true, isSupportFetch: true }; 4626 scheme2: webview.WebCustomScheme = { schemeName: "name2", isSupportCORS: true, isSupportFetch: true }; 4627 scheme3: webview.WebCustomScheme = { schemeName: "name3", isSupportCORS: true, isSupportFetch: true }; 4628 4629 aboutToAppear(): void { 4630 try { 4631 webview.WebviewController.customizeSchemes([this.scheme1, this.scheme2, this.scheme3]); 4632 } catch (error) { 4633 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4634 } 4635 } 4636 4637 build() { 4638 Column() { 4639 Web({ src: 'www.example.com', controller: this.controller }) 4640 .onInterceptRequest((event) => { 4641 if (event) { 4642 console.log('url:' + event.request.getRequestUrl()); 4643 } 4644 return this.responseWeb; 4645 }) 4646 } 4647 } 4648} 4649``` 4650 4651### getCertificate<sup>10+</sup> 4652 4653getCertificate(): Promise<Array<cert.X509Cert>> 4654 4655Obtains 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](../apis-device-certificate-kit/js-apis-cert.md#x509cert) of the current website. 4656 4657**System capability**: SystemCapability.Web.Webview.Core 4658 4659**Return value** 4660 4661| Type | Description | 4662| ---------- | --------------------------------------------- | 4663| Promise<Array<cert.X509Cert>> | Promise used to obtain the X.509 certificate array of the current HTTPS website.| 4664 4665**Error codes** 4666 4667For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4668 4669| ID| Error Message | 4670| -------- | ------------------------------------------------------------ | 4671| 17100001 | Init error. The WebviewController must be associated with a web component. | 4672| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 4673 4674**Example** 4675 4676```ts 4677// xxx.ets 4678import { webview } from '@kit.ArkWeb'; 4679import { BusinessError } from '@kit.BasicServicesKit'; 4680import { cert } from '@kit.DeviceCertificateKit'; 4681 4682function Uint8ArrayToString(dataArray: Uint8Array) { 4683 let dataString = ''; 4684 for (let i = 0; i < dataArray.length; i++) { 4685 dataString += String.fromCharCode(dataArray[i]); 4686 } 4687 return dataString; 4688} 4689 4690function ParseX509CertInfo(x509CertArray: Array<cert.X509Cert>) { 4691 let res: string = 'getCertificate success: len = ' + x509CertArray.length; 4692 for (let i = 0; i < x509CertArray.length; i++) { 4693 res += ', index = ' + i + ', issuer name = ' 4694 + Uint8ArrayToString(x509CertArray[i].getIssuerName().data) + ', subject name = ' 4695 + Uint8ArrayToString(x509CertArray[i].getSubjectName().data) + ', valid start = ' 4696 + x509CertArray[i].getNotBeforeTime() 4697 + ', valid end = ' + x509CertArray[i].getNotAfterTime(); 4698 } 4699 return res; 4700} 4701 4702@Entry 4703@Component 4704struct Index { 4705 // outputStr displays debug information on the UI. 4706 @State outputStr: string = ''; 4707 webviewCtl: webview.WebviewController = new webview.WebviewController(); 4708 4709 build() { 4710 Row() { 4711 Column() { 4712 List({ space: 20, initialIndex: 0 }) { 4713 ListItem() { 4714 Button() { 4715 Text('load bad ssl') 4716 .fontSize(10) 4717 .fontWeight(FontWeight.Bold) 4718 } 4719 .type(ButtonType.Capsule) 4720 .onClick(() => { 4721 // Load an expired certificate website and view the obtained certificate information. 4722 this.webviewCtl.loadUrl('https://expired.badssl.com'); 4723 }) 4724 .height(50) 4725 } 4726 4727 ListItem() { 4728 Button() { 4729 Text('load example') 4730 .fontSize(10) 4731 .fontWeight(FontWeight.Bold) 4732 } 4733 .type(ButtonType.Capsule) 4734 .onClick(() => { 4735 // Load an HTTPS website and view the certificate information of the website. 4736 this.webviewCtl.loadUrl('https://www.example.com'); 4737 }) 4738 .height(50) 4739 } 4740 4741 ListItem() { 4742 Button() { 4743 Text('getCertificate Promise') 4744 .fontSize(10) 4745 .fontWeight(FontWeight.Bold) 4746 } 4747 .type(ButtonType.Capsule) 4748 .onClick(() => { 4749 try { 4750 this.webviewCtl.getCertificate().then((x509CertArray: Array<cert.X509Cert>) => { 4751 this.outputStr = ParseX509CertInfo(x509CertArray); 4752 }) 4753 } catch (error) { 4754 this.outputStr = 'getCertificate failed: ' + (error as BusinessError).code + ", errMsg: " + (error as BusinessError).message; 4755 } 4756 }) 4757 .height(50) 4758 } 4759 4760 ListItem() { 4761 Button() { 4762 Text('getCertificate AsyncCallback') 4763 .fontSize(10) 4764 .fontWeight(FontWeight.Bold) 4765 } 4766 .type(ButtonType.Capsule) 4767 .onClick(() => { 4768 try { 4769 this.webviewCtl.getCertificate((error: BusinessError, x509CertArray: Array<cert.X509Cert>) => { 4770 if (error) { 4771 this.outputStr = 'getCertificate failed: ' + error.code + ", errMsg: " + error.message; 4772 } else { 4773 this.outputStr = ParseX509CertInfo(x509CertArray); 4774 } 4775 }) 4776 } catch (error) { 4777 this.outputStr = 'getCertificate failed: ' + (error as BusinessError).code + ", errMsg: " + (error as BusinessError).message; 4778 } 4779 }) 4780 .height(50) 4781 } 4782 } 4783 .listDirection(Axis.Horizontal) 4784 .height('10%') 4785 4786 Text(this.outputStr) 4787 .width('100%') 4788 .fontSize(10) 4789 4790 Web({ src: 'https://www.example.com', controller: this.webviewCtl }) 4791 .fileAccess(true) 4792 .javaScriptAccess(true) 4793 .domStorageAccess(true) 4794 .onlineImageAccess(true) 4795 .onPageEnd((e) => { 4796 if (e) { 4797 this.outputStr = 'onPageEnd : url = ' + e.url; 4798 } 4799 }) 4800 .onSslErrorEventReceive((e) => { 4801 // Ignore SSL certificate errors to test websites whose certificates have expired, for example, https://expired.badssl.com. 4802 e.handler.handleConfirm(); 4803 }) 4804 .width('100%') 4805 .height('70%') 4806 } 4807 .height('100%') 4808 } 4809 } 4810} 4811``` 4812 4813### getCertificate<sup>10+</sup> 4814 4815getCertificate(callback: AsyncCallback<Array<cert.X509Cert>>): void 4816 4817Obtains 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](../apis-device-certificate-kit/js-apis-cert.md#x509cert) of the current website. 4818 4819**System capability**: SystemCapability.Web.Webview.Core 4820 4821**Parameters** 4822 4823| Name | Type | Mandatory| Description | 4824| -------- | ---------------------------- | ---- | ---------------------------------------- | 4825| callback | AsyncCallback<Array<cert.X509Cert>> | Yes | Callback used to obtain the X.509 certificate array of the current website.| 4826 4827**Error codes** 4828 4829For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4830 4831| ID| Error Message | 4832| -------- | ------------------------------------------------------------ | 4833| 17100001 | Init error. The WebviewController must be associated with a web component. | 4834 4835**Example** 4836 4837```ts 4838// xxx.ets 4839import { webview } from '@kit.ArkWeb'; 4840import { BusinessError } from '@kit.BasicServicesKit'; 4841import { cert } from '@kit.DeviceCertificateKit'; 4842 4843function Uint8ArrayToString(dataArray: Uint8Array) { 4844 let dataString = ''; 4845 for (let i = 0; i < dataArray.length; i++) { 4846 dataString += String.fromCharCode(dataArray[i]); 4847 } 4848 return dataString; 4849} 4850 4851function ParseX509CertInfo(x509CertArray: Array<cert.X509Cert>) { 4852 let res: string = 'getCertificate success: len = ' + x509CertArray.length; 4853 for (let i = 0; i < x509CertArray.length; i++) { 4854 res += ', index = ' + i + ', issuer name = ' 4855 + Uint8ArrayToString(x509CertArray[i].getIssuerName().data) + ', subject name = ' 4856 + Uint8ArrayToString(x509CertArray[i].getSubjectName().data) + ', valid start = ' 4857 + x509CertArray[i].getNotBeforeTime() 4858 + ', valid end = ' + x509CertArray[i].getNotAfterTime(); 4859 } 4860 return res; 4861} 4862 4863@Entry 4864@Component 4865struct Index { 4866 // outputStr displays debug information on the UI. 4867 @State outputStr: string = ''; 4868 webviewCtl: webview.WebviewController = new webview.WebviewController(); 4869 4870 build() { 4871 Row() { 4872 Column() { 4873 List({ space: 20, initialIndex: 0 }) { 4874 ListItem() { 4875 Button() { 4876 Text('load bad ssl') 4877 .fontSize(10) 4878 .fontWeight(FontWeight.Bold) 4879 } 4880 .type(ButtonType.Capsule) 4881 .onClick(() => { 4882 // Load an expired certificate website and view the obtained certificate information. 4883 this.webviewCtl.loadUrl('https://expired.badssl.com'); 4884 }) 4885 .height(50) 4886 } 4887 4888 ListItem() { 4889 Button() { 4890 Text('load example') 4891 .fontSize(10) 4892 .fontWeight(FontWeight.Bold) 4893 } 4894 .type(ButtonType.Capsule) 4895 .onClick(() => { 4896 // Load an HTTPS website and view the certificate information of the website. 4897 this.webviewCtl.loadUrl('https://www.example.com'); 4898 }) 4899 .height(50) 4900 } 4901 4902 ListItem() { 4903 Button() { 4904 Text('getCertificate Promise') 4905 .fontSize(10) 4906 .fontWeight(FontWeight.Bold) 4907 } 4908 .type(ButtonType.Capsule) 4909 .onClick(() => { 4910 try { 4911 this.webviewCtl.getCertificate().then((x509CertArray: Array<cert.X509Cert>) => { 4912 this.outputStr = ParseX509CertInfo(x509CertArray); 4913 }) 4914 } catch (error) { 4915 this.outputStr = 'getCertificate failed: ' + (error as BusinessError).code + ", errMsg: " + (error as BusinessError).message; 4916 } 4917 }) 4918 .height(50) 4919 } 4920 4921 ListItem() { 4922 Button() { 4923 Text('getCertificate AsyncCallback') 4924 .fontSize(10) 4925 .fontWeight(FontWeight.Bold) 4926 } 4927 .type(ButtonType.Capsule) 4928 .onClick(() => { 4929 try { 4930 this.webviewCtl.getCertificate((error: BusinessError, x509CertArray: Array<cert.X509Cert>) => { 4931 if (error) { 4932 this.outputStr = 'getCertificate failed: ' + error.code + ", errMsg: " + error.message; 4933 } else { 4934 this.outputStr = ParseX509CertInfo(x509CertArray); 4935 } 4936 }) 4937 } catch (error) { 4938 this.outputStr = 'getCertificate failed: ' + (error as BusinessError).code + ", errMsg: " + (error as BusinessError).message; 4939 } 4940 }) 4941 .height(50) 4942 } 4943 } 4944 .listDirection(Axis.Horizontal) 4945 .height('10%') 4946 4947 Text(this.outputStr) 4948 .width('100%') 4949 .fontSize(10) 4950 4951 Web({ src: 'https://www.example.com', controller: this.webviewCtl }) 4952 .fileAccess(true) 4953 .javaScriptAccess(true) 4954 .domStorageAccess(true) 4955 .onlineImageAccess(true) 4956 .onPageEnd((e) => { 4957 if (e) { 4958 this.outputStr = 'onPageEnd : url = ' + e.url; 4959 } 4960 }) 4961 .onSslErrorEventReceive((e) => { 4962 // Ignore SSL certificate errors to test websites whose certificates have expired, for example, https://expired.badssl.com. 4963 e.handler.handleConfirm(); 4964 }) 4965 .width('100%') 4966 .height('70%') 4967 } 4968 .height('100%') 4969 } 4970 } 4971} 4972``` 4973 4974### setAudioMuted<sup>10+</sup> 4975 4976setAudioMuted(mute: boolean): void 4977 4978Mutes this web page. 4979 4980**System capability**: SystemCapability.Web.Webview.Core 4981 4982**Parameters** 4983 4984| Name | Type | Mandatory| Description | 4985| -------- | ------- | ---- | -------------------------------------- | 4986| mute | boolean | Yes | Whether to mute the web page. The value **true** means to mute the web page, and **false** means the opposite.| 4987 4988**Error codes** 4989 4990For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4991 4992| ID| Error Message | 4993| -------- | ------------------------------------------------------------ | 4994| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4995| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4996 4997**Example** 4998 4999```ts 5000// xxx.ets 5001import { webview } from '@kit.ArkWeb'; 5002 5003@Entry 5004@Component 5005struct WebComponent { 5006 controller: webview.WebviewController = new webview.WebviewController(); 5007 @State muted: boolean = false; 5008 5009 build() { 5010 Column() { 5011 Button("Toggle Mute") 5012 .onClick(event => { 5013 if (event) { 5014 this.muted = !this.muted; 5015 this.controller.setAudioMuted(this.muted); 5016 } 5017 }) 5018 Web({ src: 'www.example.com', controller: this.controller }) 5019 } 5020 } 5021} 5022``` 5023 5024### prefetchPage<sup>10+</sup> 5025 5026prefetchPage(url: string, additionalHeaders?: Array\<WebHeader>): void 5027 5028Prefetches 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. 5029 5030> **NOTE** 5031> 5032> The downloaded page resources are cached for about 5 minutes. After this period, the **Web** component automatically releases the resources. 5033 5034**System capability**: SystemCapability.Web.Webview.Core 5035 5036**Parameters** 5037 5038| Name | Type | Mandatory | Description | 5039| ------------------| --------------------------------| ---- | ------------- | 5040| url | string | Yes | URL to be preloaded.| 5041| additionalHeaders | Array\<[WebHeader](#webheader)> | No | Additional HTTP headers of the URL.| 5042 5043**Error codes** 5044 5045For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5046 5047| ID | Error Message | 5048| -------- | ------------------------------------------------------------ | 5049| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5050| 17100002 | Invalid url. | 5051 5052**Example** 5053 5054```ts 5055// xxx.ets 5056import { webview } from '@kit.ArkWeb'; 5057import { BusinessError } from '@kit.BasicServicesKit'; 5058 5059@Entry 5060@Component 5061struct WebComponent { 5062 controller: webview.WebviewController = new webview.WebviewController(); 5063 5064 build() { 5065 Column() { 5066 Button('prefetchPopularPage') 5067 .onClick(() => { 5068 try { 5069 // Replace 'https://www.example.com' with a real URL for the API to work. 5070 this.controller.prefetchPage('https://www.example.com'); 5071 } catch (error) { 5072 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5073 } 5074 }) 5075 // Replace ''www.example1.com' with a real URL for the API to work. 5076 Web({ src: 'www.example1.com', controller: this.controller }) 5077 } 5078 } 5079} 5080``` 5081 5082### prefetchResource<sup>12+</sup> 5083 5084static prefetchResource(request: RequestInfo, additionalHeaders?: Array\<WebHeader>, cacheKey?: string, cacheValidTime?: number): void 5085 5086Prefetches resource requests based on specified request information and additional HTTP request headers, saves the requests to the memory cache, and specifies the cache key and validity period to accelerate loading. Currently, only POST requests whose Content-Type is application/x-www-form-urlencoded are supported. A maximum of six POST requests can be pre-obtained. To prefetch the seventh post request, call [clearPrefetchedResource](#clearprefetchedresource12) to clear the cache of unnecessary post requests. Otherwise, the cache of the earliest prefetched POST request will be automatically cleared. To use the prefetched resource cache, you need to add the key value **ArkWebPostCacheKey** to the header of the POST request. The content of the key value is the cacheKey of the corresponding cache. 5087 5088**System capability**: SystemCapability.Web.Webview.Core 5089 5090**Parameters** 5091 5092| Name | Type | Mandatory | Description | 5093| ------------------| ------------------------------- | ---- | ------------------------------------------------------------------ | 5094| request | [RequestInfo](#requestinfo12) | Yes | Information about the prefetched request. | 5095| additionalHeaders | Array\<[WebHeader](#webheader)> | No | Additional HTTP request header of the prefetched request. | 5096| cacheKey | string | No | Key used to query the cache of prefetched resources. The value can contain only letters and digits. If this parameter is not passed or is left empty, **url** is used by default.| 5097| cacheValidTime | number | No | Validity period for caching prefetched resources. Value range: (0, 2147483647] Unit: second. Default value: **300s** | 5098 5099**Error codes** 5100 5101For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5102 5103| ID | Error Message | 5104| -------- | ------------------------------------------------------------ | 5105| 401 | Invalid input parameter.Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | 5106| 17100002 | Invalid url. | 5107 5108**Example** 5109 5110```ts 5111// xxx.ets 5112import { webview } from '@kit.ArkWeb'; 5113import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 5114 5115export default class EntryAbility extends UIAbility { 5116 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 5117 console.log("EntryAbility onCreate"); 5118 webview.WebviewController.initializeWebEngine(); 5119 // Replace "https://www.example1.com/post?e=f&g=h" with the actual website address to visit. 5120 webview.WebviewController.prefetchResource( 5121 {url:"https://www.example1.com/post?e=f&g=h", 5122 method:"POST", 5123 formData:"a=x&b=y",}, 5124 [{headerKey:"c", 5125 headerValue:"z",},], 5126 "KeyX", 500); 5127 AppStorage.setOrCreate("abilityWant", want); 5128 console.log("EntryAbility onCreate done"); 5129 } 5130} 5131``` 5132 5133### clearPrefetchedResource<sup>12+</sup> 5134 5135static clearPrefetchedResource(cacheKeyList: Array\<string>): void 5136 5137Clears the cache of prefetched resources based on the specified cache key list. The cache key in the input parameter must be the prefetched resource cache key specified by [prefetchResource](#prefetchresource12). 5138 5139**System capability**: SystemCapability.Web.Webview.Core 5140 5141**Parameters** 5142 5143| Name | Type | Mandatory | Description | 5144| ------------------| ----------- | ---- | ------------------------------------------------------------------------- | 5145| cacheKeyList | Array\<string> | Yes | Key used to query the cache of prefetched resources. The value can contain only letters and digits. If this parameter is not passed or is left empty, **url** is used by default.| 5146 5147**Example** 5148 5149```ts 5150// xxx.ets 5151import { webview } from '@kit.ArkWeb'; 5152 5153@Entry 5154@Component 5155struct WebComponent { 5156 controller: webview.WebviewController = new webview.WebviewController(); 5157 build() { 5158 Column() { 5159 Web({ src: "https://www.example.com/", controller: this.controller}) 5160 .onAppear(() => { 5161 // Replace "https://www.example1.com/post?e=f&g=h" with the actual website address to visit. 5162 webview.WebviewController.prefetchResource( 5163 {url:"https://www.example1.com/post?e=f&g=h", 5164 method:"POST", 5165 formData:"a=x&b=y",}, 5166 [{headerKey:"c", 5167 headerValue:"z",},], 5168 "KeyX", 500); 5169 }) 5170 .onPageEnd(() => { 5171 // Clear the prefetch cache that is no longer used. 5172 webview.WebviewController.clearPrefetchedResource(["KeyX",]); 5173 }) 5174 } 5175 } 5176} 5177``` 5178 5179### prepareForPageLoad<sup>10+</sup> 5180 5181static prepareForPageLoad(url: string, preconnectable: boolean, numSockets: number): void 5182 5183Preconnects 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. 5184 5185**System capability**: SystemCapability.Web.Webview.Core 5186 5187**Parameters** 5188 5189| Name | Type | Mandatory | Description | 5190| ---------------| ------- | ---- | ------------- | 5191| url | string | Yes | URL to be preconnected.| 5192| 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.| 5193| numSockets | number | Yes | Number of sockets to be preconnected. The value must be greater than 0. A maximum of six socket connections are allowed.| 5194 5195**Error codes** 5196 5197For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5198 5199| ID | Error Message | 5200| -------- | ------------------------------------------------------------ | 5201| 17100002 | Invalid url. | 5202| 171000013| The number of preconnect sockets is invalid. | 5203 5204**Example** 5205 5206```ts 5207// xxx.ets 5208import { webview } from '@kit.ArkWeb'; 5209import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 5210 5211export default class EntryAbility extends UIAbility { 5212 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 5213 console.log("EntryAbility onCreate"); 5214 webview.WebviewController.initializeWebEngine(); 5215 // Replace 'https://www.example.com' with a real URL for the API to work. 5216 webview.WebviewController.prepareForPageLoad("https://www.example.com", true, 2); 5217 AppStorage.setOrCreate("abilityWant", want); 5218 console.log("EntryAbility onCreate done"); 5219 } 5220} 5221``` 5222 5223### setCustomUserAgent<sup>10+</sup> 5224 5225setCustomUserAgent(userAgent: string): void 5226 5227Sets a custom user agent, which will overwrite the default user agent. 5228 5229When a URL is set for the **Web** component **src**, you are advised to set UserAgent in the onControllerAttached callback event. For details, see the example. You are not advised to set **UserAgent** in the **onLoadIntercept** callback event. Otherwise, the setting may fail occasionally. 5230 5231When **src** of the **Web** component is set to an empty string, you are advised to call the **setCustomUserAgent** method to set **UserAgent** and then use **loadUrl** to load a specific page. 5232 5233For details about the default **UserAgent**, see [Default User Agent String](../../web/web-default-userAgent.md). 5234 5235> **NOTE** 5236> 5237>If a URL is set for the **Web** component **src**, and **UserAgent** is not set in the **onControllerAttached** callback event, calling **setCustomUserAgent** again may result in the loaded page being inconsistent with the actual user agent. 5238 5239**System capability**: SystemCapability.Web.Webview.Core 5240 5241**Parameters** 5242 5243| Name | Type | Mandatory | Description | 5244| ---------------| ------- | ---- | ------------- | 5245| userAgent | string | Yes | Information about the custom user agent. It is recommended that you obtain the current default user agent through [getUserAgent](#getuseragent) and then customize the obtained user agent.| 5246 5247**Error codes** 5248 5249For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5250 5251| ID | Error Message | 5252| -------- | ------------------------------------------------------------ | 5253| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5254| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5255 5256**Example** 5257 5258```ts 5259// xxx.ets 5260import { webview } from '@kit.ArkWeb'; 5261import { BusinessError } from '@kit.BasicServicesKit'; 5262 5263@Entry 5264@Component 5265struct WebComponent { 5266 controller: webview.WebviewController = new webview.WebviewController(); 5267 @State customUserAgent: string = 'test'; 5268 5269 build() { 5270 Column() { 5271 Web({ src: 'www.example.com', controller: this.controller }) 5272 .onControllerAttached(() => { 5273 console.log("onControllerAttached"); 5274 try { 5275 let userAgent = this.controller.getUserAgent() + this.customUserAgent; 5276 this.controller.setCustomUserAgent(userAgent); 5277 } catch (error) { 5278 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5279 } 5280 }) 5281 } 5282 } 5283} 5284``` 5285 5286### setDownloadDelegate<sup>11+</sup> 5287 5288setDownloadDelegate(delegate: WebDownloadDelegate): void 5289 5290Sets a **WebDownloadDelegate** object to receive downloads and download progress triggered from a page. 5291 5292**System capability**: SystemCapability.Web.Webview.Core 5293 5294**Parameters** 5295 5296| Name | Type | Mandatory | Description | 5297| ---------------| ------- | ---- | ------------- | 5298| delegate | [WebDownloadDelegate](#webdownloaddelegate11) | Yes | Delegate used to receive the download progress.| 5299 5300**Error codes** 5301 5302For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5303 5304| ID | Error Message | 5305| -------- | ------------------------------------------------------------ | 5306| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5307 5308**Example** 5309 5310```ts 5311// xxx.ets 5312import { webview } from '@kit.ArkWeb'; 5313import { BusinessError } from '@kit.BasicServicesKit'; 5314 5315@Entry 5316@Component 5317struct WebComponent { 5318 controller: webview.WebviewController = new webview.WebviewController(); 5319 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 5320 5321 build() { 5322 Column() { 5323 Button('setDownloadDelegate') 5324 .onClick(() => { 5325 try { 5326 this.controller.setDownloadDelegate(this.delegate); 5327 } catch (error) { 5328 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5329 } 5330 }) 5331 Web({ src: 'www.example.com', controller: this.controller }) 5332 } 5333 } 5334} 5335``` 5336 5337### startDownload<sup>11+</sup> 5338 5339startDownload(url: string): void 5340 5341Downloads a file, such as an image, from the specified URL. 5342 5343**System capability**: SystemCapability.Web.Webview.Core 5344 5345**Parameters** 5346 5347| Name | Type | Mandatory | Description | 5348| ---------------| ------- | ---- | ------------- | 5349| url | string | Yes | Download URL.| 5350 5351**Error codes** 5352 5353For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5354 5355| ID | Error Message | 5356| -------- | ------------------------------------------------------------ | 5357| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5358| 17100002 | Invalid url. | 5359 5360**Example** 5361 5362```ts 5363// xxx.ets 5364import { webview } from '@kit.ArkWeb'; 5365import { BusinessError } from '@kit.BasicServicesKit'; 5366 5367@Entry 5368@Component 5369struct WebComponent { 5370 controller: webview.WebviewController = new webview.WebviewController(); 5371 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 5372 5373 build() { 5374 Column() { 5375 Button('setDownloadDelegate') 5376 .onClick(() => { 5377 try { 5378 this.controller.setDownloadDelegate(this.delegate); 5379 } catch (error) { 5380 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5381 } 5382 }) 5383 Button('startDownload') 5384 .onClick(() => { 5385 try { 5386 this.controller.startDownload('https://www.example.com'); 5387 } catch (error) { 5388 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5389 } 5390 }) 5391 Web({ src: 'www.example.com', controller: this.controller }) 5392 } 5393 } 5394} 5395``` 5396 5397### getCustomUserAgent<sup>10+</sup> 5398 5399getCustomUserAgent(): string 5400 5401Obtains a custom user agent. 5402 5403For details about the default **UserAgent**, see [Default User Agent String](../../web/web-default-userAgent.md). 5404 5405**System capability**: SystemCapability.Web.Webview.Core 5406 5407**Return value** 5408 5409| Type | Description | 5410| ------ | ------------------------- | 5411| string | Information about the custom user agent.| 5412 5413**Error codes** 5414 5415For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5416 5417| ID | Error Message | 5418| -------- | ------------------------------------------------------------ | 5419| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5420 5421**Example** 5422 5423```ts 5424// xxx.ets 5425import { webview } from '@kit.ArkWeb'; 5426import { BusinessError } from '@kit.BasicServicesKit'; 5427 5428@Entry 5429@Component 5430struct WebComponent { 5431 controller: webview.WebviewController = new webview.WebviewController(); 5432 @State userAgent: string = ''; 5433 5434 build() { 5435 Column() { 5436 Button('getCustomUserAgent') 5437 .onClick(() => { 5438 try { 5439 this.userAgent = this.controller.getCustomUserAgent(); 5440 console.log("userAgent: " + this.userAgent); 5441 } catch (error) { 5442 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5443 } 5444 }) 5445 Web({ src: 'www.example.com', controller: this.controller }) 5446 } 5447 } 5448} 5449``` 5450 5451### setConnectionTimeout<sup>11+</sup> 5452 5453static setConnectionTimeout(timeout: number): void 5454 5455Sets the network connection timeout. You can use the **onErrorReceive** method in the **Web** component to obtain the timeout error code. 5456 5457**System capability**: SystemCapability.Web.Webview.Core 5458 5459**Parameters** 5460 5461| Name | Type | Mandatory | Description | 5462| ---------------| ------- | ---- | ------------- | 5463| timeout | number | Yes | Socket connection timeout interval, in seconds. The value of socket must be an integer greater than 0.| 5464 5465**Error codes** 5466 5467For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5468 5469| ID| Error Message | 5470| -------- | ------------------------------------------------------------ | 5471| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 5472 5473**Example** 5474 5475```ts 5476// xxx.ets 5477import { webview } from '@kit.ArkWeb'; 5478import { BusinessError } from '@kit.BasicServicesKit'; 5479 5480@Entry 5481@Component 5482struct WebComponent { 5483 controller: webview.WebviewController = new webview.WebviewController(); 5484 5485 build() { 5486 Column() { 5487 Button('setConnectionTimeout') 5488 .onClick(() => { 5489 try { 5490 webview.WebviewController.setConnectionTimeout(5); 5491 console.log("setConnectionTimeout: 5s"); 5492 } catch (error) { 5493 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5494 } 5495 }) 5496 Web({ src: 'www.example.com', controller: this.controller }) 5497 .onErrorReceive((event) => { 5498 if (event) { 5499 console.log('getErrorInfo:' + event.error.getErrorInfo()); 5500 console.log('getErrorCode:' + event.error.getErrorCode()); 5501 } 5502 }) 5503 } 5504 } 5505} 5506``` 5507 5508### warmupServiceWorker<sup>12+</sup> 5509 5510static warmupServiceWorker(url: string): void 5511 5512Warms up the ServiceWorker to enhance the loading speed of the first screen (only applicable to pages that will use ServiceWorker). This API is called before the URL is loaded. 5513 5514**System capability**: SystemCapability.Web.Webview.Core 5515 5516**Parameters** 5517 5518| Name | Type | Mandatory | Description | 5519| ---------------| ------- | ---- | ------------- | 5520| url | string | Yes | URL of the ServiceWorker to warm up.| 5521 5522**Error codes** 5523 5524For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5525 5526| ID | Error Message | 5527| -------- | ------------------------------------------------------------ | 5528| 17100002 | Invalid url. | 5529 5530**Example** 5531 5532```ts 5533// xxx.ts 5534import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 5535import { hilog } from '@kit.PerformanceAnalysisKit'; 5536import { window } from '@kit.ArkUI'; 5537import { webview } from '@kit.ArkWeb'; 5538 5539export default class EntryAbility extends UIAbility { 5540 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 5541 console.log("EntryAbility onCreate"); 5542 webview.WebviewController.warmupServiceWorker("https://www.example.com"); 5543 AppStorage.setOrCreate("abilityWant", want); 5544 } 5545} 5546``` 5547 5548### enableSafeBrowsing<sup>11+</sup> 5549 5550enableSafeBrowsing(enable: boolean): void 5551 5552<!--RP1-->Enables the safe browsing feature. This feature is forcibly enabled and cannot be disabled for identified untrusted websites.<!--RP1End--> 5553 5554**System capability**: SystemCapability.Web.Webview.Core 5555 5556**Parameters** 5557 5558| Name | Type | Mandatory | Description | 5559| --------| ------- | ---- | ---------------------------| 5560| enable | boolean | Yes | Whether to enable the safe browsing feature.| 5561 5562**Error codes** 5563 5564For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5565 5566| ID| Error Message | 5567| -------- | ----------------------- | 5568| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5569 5570**Example** 5571 5572```ts 5573// xxx.ets 5574import { webview } from '@kit.ArkWeb'; 5575import { BusinessError } from '@kit.BasicServicesKit'; 5576 5577@Entry 5578@Component 5579struct WebComponent { 5580 controller: webview.WebviewController = new webview.WebviewController(); 5581 5582 build() { 5583 Column() { 5584 Button('enableSafeBrowsing') 5585 .onClick(() => { 5586 try { 5587 this.controller.enableSafeBrowsing(true); 5588 console.log("enableSafeBrowsing: true"); 5589 } catch (error) { 5590 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5591 } 5592 }) 5593 Web({ src: 'www.example.com', controller: this.controller }) 5594 } 5595 } 5596} 5597``` 5598 5599### isSafeBrowsingEnabled<sup>11+</sup> 5600 5601isSafeBrowsingEnabled(): boolean 5602 5603Checks whether the safe browsing feature is enabled for this web page. 5604 5605**System capability**: SystemCapability.Web.Webview.Core 5606 5607**Return value** 5608 5609| Type | Description | 5610| ------- | --------------------------------------- | 5611| boolean | Whether the safe browsing feature is enabled. The default value is **false**.| 5612 5613**Example** 5614 5615```ts 5616// xxx.ets 5617import { webview } from '@kit.ArkWeb'; 5618 5619@Entry 5620@Component 5621struct WebComponent { 5622 controller: webview.WebviewController = new webview.WebviewController(); 5623 5624 build() { 5625 Column() { 5626 Button('isSafeBrowsingEnabled') 5627 .onClick(() => { 5628 let result = this.controller.isSafeBrowsingEnabled(); 5629 console.log("result: " + result); 5630 }) 5631 Web({ src: 'www.example.com', controller: this.controller }) 5632 } 5633 } 5634} 5635``` 5636 5637### enableIntelligentTrackingPrevention<sup>12+</sup> 5638 5639enableIntelligentTrackingPrevention(enable: boolean): void 5640 5641Enables intelligent tracking prevention. By default, this feature is disabled. 5642 5643**System capability**: SystemCapability.Web.Webview.Core 5644 5645**Parameters** 5646 5647| Name | Type | Mandatory | Description | 5648| --------| ------- | ---- | ---------------------------| 5649| enable | boolean | Yes | Whether to enable intelligent tracking prevention.| 5650 5651**Error codes** 5652 5653For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5654 5655| ID| Error Message | 5656| -------- | ----------------------- | 5657| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5658| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5659 5660**Example** 5661 5662```ts 5663// xxx.ets 5664import { webview } from '@kit.ArkWeb'; 5665import { BusinessError } from '@kit.BasicServicesKit'; 5666 5667@Entry 5668@Component 5669struct WebComponent { 5670 controller: webview.WebviewController = new webview.WebviewController(); 5671 5672 build() { 5673 Column() { 5674 Button('enableIntelligentTrackingPrevention') 5675 .onClick(() => { 5676 try { 5677 this.controller.enableIntelligentTrackingPrevention(true); 5678 console.log("enableIntelligentTrackingPrevention: true"); 5679 } catch (error) { 5680 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5681 } 5682 }) 5683 Web({ src: 'www.example.com', controller: this.controller }) 5684 } 5685 } 5686} 5687``` 5688 5689### isIntelligentTrackingPreventionEnabled<sup>12+</sup> 5690 5691isIntelligentTrackingPreventionEnabled(): boolean 5692 5693Obtains whether intelligent tracking prevention is enabled on this web page. 5694 5695**System capability**: SystemCapability.Web.Webview.Core 5696 5697**Return value** 5698 5699| Type | Description | 5700| ------- | --------------------------------------- | 5701| boolean | Whether intelligent tracking prevention is enabled on the current web page. The default value is **false**.| 5702 5703**Error codes** 5704 5705For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5706 5707| ID| Error Message | 5708| -------- | ----------------------- | 5709| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5710 5711**Example** 5712 5713```ts 5714// xxx.ets 5715import { webview } from '@kit.ArkWeb'; 5716import { BusinessError } from '@kit.BasicServicesKit'; 5717 5718@Entry 5719@Component 5720struct WebComponent { 5721 controller: webview.WebviewController = new webview.WebviewController(); 5722 5723 build() { 5724 Column() { 5725 Button('isIntelligentTrackingPreventionEnabled') 5726 .onClick(() => { 5727 try { 5728 let result = this.controller.isIntelligentTrackingPreventionEnabled(); 5729 console.log("result: " + result); 5730 } catch (error) { 5731 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5732 } 5733 }) 5734 Web({ src: 'www.example.com', controller: this.controller }) 5735 } 5736 } 5737} 5738``` 5739 5740### addIntelligentTrackingPreventionBypassingList<sup>12+</sup> 5741 5742static addIntelligentTrackingPreventionBypassingList(hostList: Array\<string>): void 5743 5744Adds a list of domain names that bypass intelligent tracking prevention. 5745 5746**System capability**: SystemCapability.Web.Webview.Core 5747 5748**Parameters** 5749 5750| Name | Type | Mandatory | Description | 5751| ----------- | ------------- | ---- | ------------------------ | 5752| hostList | Array\<string> | Yes | List of domain names that bypass intelligent tracking prevention.| 5753 5754**Error codes** 5755 5756For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5757 5758| ID | Error Message | 5759| -------- | ------------------------ | 5760| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5761 5762**Example** 5763 5764```ts 5765// xxx.ets 5766import { webview } from '@kit.ArkWeb'; 5767import { BusinessError } from '@kit.BasicServicesKit'; 5768 5769@Entry 5770@Component 5771struct WebComponent { 5772 controller: webview.WebviewController = new webview.WebviewController(); 5773 5774 build() { 5775 Column() { 5776 Button('addIntelligentTrackingPreventionBypassingList') 5777 .onClick(() => { 5778 try { 5779 let hostList = ["www.test1.com", "www.test2.com", "www.test3.com"]; 5780 webview.WebviewController.addIntelligentTrackingPreventionBypassingList(hostList); 5781 } catch (error) { 5782 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5783 } 5784 }) 5785 Web({ src: 'www.example.com', controller: this.controller }) 5786 } 5787 } 5788} 5789``` 5790 5791### removeIntelligentTrackingPreventionBypassingList<sup>12+</sup> 5792 5793static removeIntelligentTrackingPreventionBypassingList(hostList: Array\<string>): void 5794 5795Deletes the domain names from the list of domain names added through the **addIntelligentTrackingPreventionBypassingList** API. 5796 5797**System capability**: SystemCapability.Web.Webview.Core 5798 5799**Parameters** 5800 5801| Name | Type | Mandatory | Description | 5802| ----------- | ------------- | ---- | ------------------------ | 5803| hostList | Array\<string> | Yes | List of domain names that bypass intelligent tracking prevention.| 5804 5805**Error codes** 5806 5807For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5808 5809| ID | Error Message | 5810| -------- | ------------------------ | 5811| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5812 5813**Example** 5814 5815```ts 5816// xxx.ets 5817import { webview } from '@kit.ArkWeb'; 5818import { BusinessError } from '@kit.BasicServicesKit'; 5819 5820@Entry 5821@Component 5822struct WebComponent { 5823 controller: webview.WebviewController = new webview.WebviewController(); 5824 5825 build() { 5826 Column() { 5827 Button('removeIntelligentTrackingPreventionBypassingList') 5828 .onClick(() => { 5829 try { 5830 let hostList = ["www.test1.com", "www.test2.com"]; 5831 webview.WebviewController.removeIntelligentTrackingPreventionBypassingList(hostList); 5832 } catch (error) { 5833 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5834 } 5835 }) 5836 Web({ src: 'www.example.com', controller: this.controller }) 5837 } 5838 } 5839} 5840``` 5841 5842### clearIntelligentTrackingPreventionBypassingList<sup>12+</sup> 5843 5844static clearIntelligentTrackingPreventionBypassingList(): void 5845 5846Deletes all domain names from the list of domain names added through the **addIntelligentTrackingPreventionBypassingList** API. 5847 5848**System capability**: SystemCapability.Web.Webview.Core 5849 5850**Example** 5851 5852```ts 5853// xxx.ets 5854import { webview } from '@kit.ArkWeb'; 5855 5856@Entry 5857@Component 5858struct WebComponent { 5859 controller: webview.WebviewController = new webview.WebviewController(); 5860 5861 build() { 5862 Column() { 5863 Button('clearIntelligentTrackingPreventionBypassingList') 5864 .onClick(() => { 5865 webview.WebviewController.clearIntelligentTrackingPreventionBypassingList(); 5866 }) 5867 Web({ src: 'www.example.com', controller: this.controller }) 5868 } 5869 } 5870} 5871``` 5872 5873### enableAdsBlock<sup>12+</sup> 5874 5875enableAdsBlock(enable: boolean): void 5876 5877Enables ad blocking. By default, this feature is disabled. 5878 5879**System capability**: SystemCapability.Web.Webview.Core 5880 5881**Parameters** 5882 5883| Name | Type | Mandatory | Description | 5884| --------| ------- | ---- | ---------------------------| 5885| enable | boolean | Yes | Whether to enable ad blocking.| 5886 5887**Error codes** 5888 5889For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5890 5891| ID| Error Message | 5892| -------- | ----------------------- | 5893| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5894| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Parameter string is too long. 3.Parameter verification failed. | 5895 5896**Example** 5897 5898```ts 5899// xxx.ets 5900import { webview } from '@kit.ArkWeb'; 5901import { BusinessError } from '@kit.BasicServicesKit'; 5902 5903@Entry 5904@Component 5905struct WebComponent { 5906 controller: webview.WebviewController = new webview.WebviewController(); 5907 5908 build() { 5909 Column() { 5910 Button('enableAdsBlock') 5911 .onClick(() => { 5912 try { 5913 this.controller.enableAdsBlock(true); 5914 console.log("enableAdsBlock: true") 5915 } catch (error) { 5916 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5917 } 5918 }) 5919 Web({ src: 'www.example.com', controller: this.controller }) 5920 } 5921 } 5922} 5923``` 5924 5925### isAdsBlockEnabled<sup>12+</sup> 5926 5927isAdsBlockEnabled() : boolean 5928 5929Checks whether ad blocking is enabled. By default, this feature is disabled. 5930 5931**System capability**: SystemCapability.Web.Webview.Core 5932 5933**Return value** 5934 5935| Type | Description | 5936| ------------------------------------------------------------ | ---------------------- | 5937| boolean | Returns **true** if ad blocking is enabled; returns **false** otherwise.| 5938 5939**Example** 5940 5941```ts 5942// xxx.ets 5943import { webview } from '@kit.ArkWeb'; 5944import { BusinessError } from '@kit.BasicServicesKit'; 5945 5946@Entry 5947@Component 5948struct WebComponent { 5949 controller: webview.WebviewController = new webview.WebviewController(); 5950 5951 build() { 5952 Column() { 5953 Button('isAdsBlockEnabled') 5954 .onClick(() => { 5955 try { 5956 let isAdsBlockEnabled: boolean = this.controller.isAdsBlockEnabled(); 5957 console.log("isAdsBlockEnabled:", isAdsBlockEnabled); 5958 } catch (error) { 5959 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5960 } 5961 }) 5962 Web({ src: 'www.example.com', controller: this.controller }) 5963 } 5964 } 5965} 5966``` 5967 5968### isAdsBlockEnabledForCurPage<sup>12+</sup> 5969 5970isAdsBlockEnabledForCurPage() : boolean 5971 5972Checks whether ad blocking is enabled on this web page. 5973After ads blocking is enabled for the **Web** component, this feature is enabled for all web pages by default. You can call [addAdsBlockDisallowedList](#addadsblockdisallowedlist12) to disable the feature for specific domains. 5974 5975**System capability**: SystemCapability.Web.Webview.Core 5976 5977**Return value** 5978 5979| Type | Description | 5980| ------------------------------------------------------------ | ---------------------- | 5981| boolean | Returns **true** if ad blocking is enabled; returns **false** otherwise.| 5982 5983**Example** 5984 5985```ts 5986// xxx.ets 5987import { webview } from '@kit.ArkWeb'; 5988import { BusinessError } from '@kit.BasicServicesKit'; 5989 5990@Entry 5991@Component 5992struct WebComponent { 5993 controller: webview.WebviewController = new webview.WebviewController(); 5994 5995 build() { 5996 Column() { 5997 Button('isAdsBlockEnabledForCurPage') 5998 .onClick(() => { 5999 try { 6000 let isAdsBlockEnabledForCurPage: boolean = this.controller.isAdsBlockEnabledForCurPage(); 6001 console.log("isAdsBlockEnabledForCurPage:", isAdsBlockEnabledForCurPage); 6002 } catch (error) { 6003 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6004 } 6005 }) 6006 Web({ src: 'www.example.com', controller: this.controller }) 6007 } 6008 } 6009} 6010``` 6011 6012### setRenderProcessMode<sup>12+</sup> 6013 6014static setRenderProcessMode(mode: RenderProcessMode): void 6015 6016Sets the ArkWeb render subprocess mode. 6017 6018**System capability**: SystemCapability.Web.Webview.Core 6019 6020**Parameters** 6021 6022| Name | Type | Mandatory | Description | 6023| ----------- | ------------- | ---- | ------------------------ | 6024| mode | [RenderProcessMode](#renderprocessmode12)| Yes | Render subprocess mode.| 6025 6026**Error codes** 6027 6028For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6029 6030| ID | Error Message | 6031| -------- | ------------------------ | 6032| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 6033 6034**Example** 6035 6036```ts 6037// xxx.ets 6038import { webview } from '@kit.ArkWeb'; 6039import { BusinessError } from '@kit.BasicServicesKit'; 6040 6041@Entry 6042@Component 6043struct WebComponent { 6044 controller: webview.WebviewController = new webview.WebviewController(); 6045 6046 build() { 6047 Column() { 6048 Button('setRenderProcessMode') 6049 .onClick(() => { 6050 try { 6051 webview.WebviewController.setRenderProcessMode(webview.RenderProcessMode.MULTIPLE); 6052 } catch (error) { 6053 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6054 } 6055 }) 6056 Web({ src: 'www.example.com', controller: this.controller }) 6057 } 6058 } 6059} 6060``` 6061### getRenderProcessMode<sup>12+</sup> 6062 6063static getRenderProcessMode(): RenderProcessMode 6064 6065Obtains the ArkWeb render subprocess mode. 6066 6067**System capability**: SystemCapability.Web.Webview.Core 6068 6069**Return value** 6070 6071| Type | Description | 6072| ------------------------------------------------------------ | ---------------------- | 6073| [RenderProcessMode](#renderprocessmode12)| Render subprocess mode.| 6074 6075 6076**Example** 6077 6078```ts 6079// xxx.ets 6080import { webview } from '@kit.ArkWeb'; 6081 6082@Entry 6083@Component 6084struct WebComponent { 6085 controller: webview.WebviewController = new webview.WebviewController(); 6086 6087 build() { 6088 Column() { 6089 Button('getRenderProcessMode') 6090 .onClick(() => { 6091 let mode = webview.WebviewController.getRenderProcessMode(); 6092 console.log("getRenderProcessMode: " + mode); 6093 }) 6094 Web({ src: 'www.example.com', controller: this.controller }) 6095 } 6096 } 6097} 6098``` 6099 6100### terminateRenderProcess<sup>12+</sup> 6101 6102terminateRenderProcess(): boolean 6103 6104Terminates this render process. 6105 6106Calling this API will destroy the associated render process. If the render process has not been started or has been destroyed, there is no impact. In addition, destroying the render process affects all other instances associated with the render process. 6107 6108**System capability**: SystemCapability.Web.Webview.Core 6109 6110**Return value** 6111 6112| Type | Description | 6113| ------------------------------------------------------------ | ---------------------- | 6114| boolean | Result of destroying the render process. If the render process can be destroyed, **true** is returned. Otherwise, **false** is returned. If the rendering process is destroyed, **true** is returned.| 6115 6116**Error codes** 6117 6118For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6119 6120| ID | Error Message | 6121| -------- | ------------------------------------------------------------ | 6122| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6123 6124**Example** 6125 6126```ts 6127// xxx.ets 6128import { webview } from '@kit.ArkWeb'; 6129 6130@Entry 6131@Component 6132struct WebComponent { 6133 controller: webview.WebviewController = new webview.WebviewController(); 6134 6135 build() { 6136 Column() { 6137 Button('terminateRenderProcess') 6138 .onClick(() => { 6139 let result = this.controller.terminateRenderProcess(); 6140 console.log("terminateRenderProcess result: " + result); 6141 }) 6142 Web({ src: 'www.example.com', controller: this.controller }) 6143 } 6144 } 6145} 6146``` 6147 6148### postUrl<sup>11+</sup> 6149 6150postUrl(url: string, postData: ArrayBuffer): void 6151 6152Loads 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. 6153 6154**System capability**: SystemCapability.Web.Webview.Core 6155 6156**Parameters** 6157 6158| Name | Type | Mandatory| Description | 6159| ------- | ---------------- | ---- | :-------------------- | 6160| url | string | Yes | URL to load. | 6161| postData | ArrayBuffer | Yes | Data to transfer using the POST method. The request must be encoded in "application/x-www-form-urlencoded" format.| 6162 6163**Error codes** 6164 6165For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6166 6167| ID| Error Message | 6168| -------- | ------------------------------------------------------------ | 6169| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6170| 17100002 | Invalid url. | 6171| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 6172 6173**Example** 6174 6175```ts 6176// xxx.ets 6177import { webview } from '@kit.ArkWeb'; 6178import { BusinessError } from '@kit.BasicServicesKit'; 6179 6180class TestObj { 6181 constructor() { 6182 } 6183 6184 test(str: string): ArrayBuffer { 6185 let buf = new ArrayBuffer(str.length); 6186 let buff = new Uint8Array(buf); 6187 6188 for (let i = 0; i < str.length; i++) { 6189 buff[i] = str.charCodeAt(i); 6190 } 6191 return buf; 6192 } 6193} 6194 6195@Entry 6196@Component 6197struct WebComponent { 6198 controller: webview.WebviewController = new webview.WebviewController(); 6199 @State testObjtest: TestObj = new TestObj(); 6200 6201 build() { 6202 Column() { 6203 Button('postUrl') 6204 .onClick(() => { 6205 try { 6206 // Convert data to the ArrayBuffer type. 6207 let postData = this.testObjtest.test("Name=test&Password=test"); 6208 this.controller.postUrl('www.example.com', postData); 6209 } catch (error) { 6210 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6211 } 6212 }) 6213 Web({ src: '', controller: this.controller }) 6214 } 6215 } 6216} 6217``` 6218 6219### createWebPrintDocumentAdapter<sup>11+</sup> 6220 6221createWebPrintDocumentAdapter(jobName: string): print.PrintDocumentAdapter 6222 6223Creates a **PrintDocumentAdapter** instance to provide content for printing. 6224 6225**System capability**: SystemCapability.Web.Webview.Core 6226 6227**Parameters** 6228 6229| Name | Type | Mandatory| Description | 6230| ------- | ------ | ---- | :-------------------- | 6231| jobName | string | Yes | Name of the file to print. | 6232 6233**Return value** 6234 6235| Type | Description | 6236| -------------------- | ------------------------- | 6237| print.printDocumentAdapter | **PrintDocumentAdapter** instance created.| 6238 6239**Error codes** 6240 6241For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6242 6243| ID| Error Message | 6244| -------- | -------------------------------------------------------------------------- | 6245| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 6246| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6247 6248**Example** 6249 6250```ts 6251// xxx.ets 6252import { webview } from '@kit.ArkWeb'; 6253import { BusinessError, print } from '@kit.BasicServicesKit'; 6254 6255@Entry 6256@Component 6257struct WebComponent { 6258 controller: webview.WebviewController = new webview.WebviewController(); 6259 6260 build() { 6261 Column() { 6262 Button('createWebPrintDocumentAdapter') 6263 .onClick(() => { 6264 try { 6265 let webPrintDocadapter = this.controller.createWebPrintDocumentAdapter('example.pdf'); 6266 print.print('example_jobid', webPrintDocadapter, null, getContext()); 6267 } catch (error) { 6268 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6269 } 6270 }) 6271 Web({ src: 'www.example.com', controller: this.controller }) 6272 } 6273 } 6274} 6275``` 6276### isIncognitoMode<sup>11+</sup> 6277 6278isIncognitoMode(): boolean 6279 6280Checks whether this Webview is in incognito mode. 6281 6282**System capability**: SystemCapability.Web.Webview.Core 6283 6284**Return value** 6285 6286| Type | Description | 6287| -------------------- | ------------------------- | 6288| boolean | Whether the Webview is in incognito mode.| 6289 6290**Error codes** 6291 6292For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6293 6294| ID| Error Message | 6295| -------- | -------------------------------------------------------------------------- | 6296| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6297 6298**Example** 6299 6300```ts 6301// xxx.ets 6302import { webview } from '@kit.ArkWeb'; 6303import { BusinessError } from '@kit.BasicServicesKit'; 6304 6305@Entry 6306@Component 6307struct WebComponent { 6308 controller: webview.WebviewController = new webview.WebviewController(); 6309 6310 build() { 6311 Column() { 6312 Button('isIncognitoMode') 6313 .onClick(() => { 6314 try { 6315 let result = this.controller.isIncognitoMode(); 6316 console.log('isIncognitoMode' + result); 6317 } catch (error) { 6318 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6319 } 6320 }) 6321 Web({ src: 'www.example.com', controller: this.controller }) 6322 } 6323 } 6324} 6325``` 6326 6327### getSecurityLevel<sup>11+</sup> 6328 6329getSecurityLevel(): SecurityLevel 6330 6331Obtains the security level of this web page. 6332 6333**System capability**: SystemCapability.Web.Webview.Core 6334 6335**Return value** 6336 6337| Type | Description | 6338| ----------------------------------- | --------------------------- | 6339| [SecurityLevel](#securitylevel11) | Security level of the web page. The value can be **NONE**, **SECURE**, **WARNING**, or **DANGEROUS**.| 6340 6341**Error codes** 6342 6343For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6344 6345| ID| Error Message | 6346| -------- | ------------------------------------------------------------ | 6347| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6348 6349**Example** 6350 6351```ts 6352import { webview } from '@kit.ArkWeb'; 6353 6354@Entry 6355@Component 6356struct WebComponent { 6357 controller: webview.WebviewController = new webview.WebviewController(); 6358 6359 build() { 6360 Column() { 6361 Web({ src: 'www.example.com', controller: this.controller }) 6362 .onPageEnd((event) => { 6363 if (event) { 6364 let securityLevel = this.controller.getSecurityLevel(); 6365 console.info('securityLevel: ', securityLevel); 6366 } 6367 }) 6368 } 6369 } 6370} 6371``` 6372 6373### setScrollable<sup>12+</sup> 6374 6375setScrollable(enable: boolean, type?: ScrollType): void 6376 6377Sets whether this web page is scrollable. 6378 6379**System capability**: SystemCapability.Web.Webview.Core 6380 6381**Parameters** 6382 6383| Name| Type| Mandatory| Description | 6384| ------ | -------- | ---- | ---------------------- | 6385| enable | boolean | Yes | Whether the web page is scrollable. The value **true** means the web page is scrollable, and **false** means the opposite.| 6386| type | [ScrollType](#scrolltype12) | No| Scrolling type supported by the web page. The default value is supported.<br> - If the value of **enable** is set to **false**, the specified **ScrollType** is disabled. If **ScrollType** is set to the default value, all scrolling types are disabled.<br> - If the value of **enable** is set to **true**, all scrolling types are enabled regardless of the value of **ScrollType**.| 6387 6388**Error codes** 6389 6390For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6391 6392| ID| Error Message | 6393| -------- | ------------------------------------------------------------ | 6394| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 6395| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6396 6397**Example** 6398 6399```ts 6400// xxx.ets 6401import { webview } from '@kit.ArkWeb'; 6402import { BusinessError } from '@kit.BasicServicesKit'; 6403 6404@Entry 6405@Component 6406struct WebComponent { 6407 controller: webview.WebviewController = new webview.WebviewController(); 6408 6409 build() { 6410 Column() { 6411 Button('setScrollable') 6412 .onClick(() => { 6413 try { 6414 this.controller.setScrollable(true); 6415 } catch (error) { 6416 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6417 } 6418 }) 6419 Web({ src: 'www.example.com', controller: this.controller }) 6420 } 6421 } 6422} 6423``` 6424 6425### getScrollable<sup>12+</sup> 6426 6427getScrollable(): boolean 6428 6429Obtains whether this web page is scrollable. 6430 6431**System capability**: SystemCapability.Web.Webview.Core 6432 6433**Return value** 6434 6435| Type | Description | 6436| ------ | -------------- | 6437| boolean | Whether the web page is scrollable. The value **true** means the web page is scrollable, and **false** means the opposite.| 6438 6439**Error codes** 6440 6441For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6442 6443| ID| Error Message | 6444| -------- | ------------------------------------------------------------ | 6445| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6446 6447**Example** 6448 6449```ts 6450// xxx.ets 6451import { webview } from '@kit.ArkWeb'; 6452import { BusinessError } from '@kit.BasicServicesKit'; 6453 6454@Entry 6455@Component 6456struct WebComponent { 6457 controller: webview.WebviewController = new webview.WebviewController(); 6458 6459 build() { 6460 Column() { 6461 Button('getScrollable') 6462 .onClick(() => { 6463 try { 6464 let scrollEnabled = this.controller.getScrollable(); 6465 console.log("scrollEnabled: " + scrollEnabled); 6466 } catch (error) { 6467 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6468 } 6469 }) 6470 Web({ src: 'www.example.com', controller: this.controller }) 6471 } 6472 } 6473} 6474``` 6475 6476### setPrintBackground<sup>12+</sup> 6477 6478setPrintBackground(enable: boolean): void 6479 6480Sets whether to print the web page background. 6481 6482**System capability**: SystemCapability.Web.Webview.Core 6483 6484**Parameters** 6485 6486| Name | Type | Mandatory| Description | 6487| -------- | ------- | ---- | -------------------------------------- | 6488| enable | boolean | Yes | Whether to print the web page background. The value **true** means to print the web page background, and **false** means the opposite.| 6489 6490**Error codes** 6491 6492For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6493 6494| ID| Error Message | 6495| -------- | ------------------------------------------------------------ | 6496| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 6497| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6498 6499**Example** 6500 6501```ts 6502import { webview } from '@kit.ArkWeb'; 6503import { BusinessError } from '@kit.BasicServicesKit'; 6504 6505@Entry 6506@Component 6507struct WebComponent { 6508 controller: webview.WebviewController = new webview.WebviewController(); 6509 6510 build() { 6511 Column() { 6512 Button('setPrintBackground') 6513 .onClick(() => { 6514 try { 6515 this.controller.setPrintBackground(false); 6516 } catch (error) { 6517 console.error(`ErrorCode:${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6518 } 6519 }) 6520 Web({ src: 'www.example.com', controller: this.controller }) 6521 } 6522 } 6523} 6524``` 6525 6526### getPrintBackground<sup>12+</sup> 6527 6528getPrintBackground(): boolean 6529 6530Obtains whether the web page background is printed. 6531 6532**System capability**: SystemCapability.Web.Webview.Core 6533 6534**Return value** 6535 6536| Type | Description | 6537| -------------------- | ------------------------- | 6538| boolean | Whether the web page background is printed.| 6539 6540**Error codes** 6541 6542For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6543 6544| ID| Error Message | 6545| -------- | ------------------------------------------------------------ | 6546| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6547 6548**Example** 6549 6550```ts 6551import { webview } from '@kit.ArkWeb'; 6552import { BusinessError } from '@kit.BasicServicesKit'; 6553 6554@Entry 6555@Component 6556struct WebComponent { 6557 controller: webview.WebviewController = new webview.WebviewController(); 6558 6559 build() { 6560 Column() { 6561 Button('setPrintBackground') 6562 .onClick(() => { 6563 try { 6564 let enable = this.controller.getPrintBackground(); 6565 console.log("getPrintBackground: " + enable); 6566 } catch (error) { 6567 console.error(`ErrorCode:${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6568 } 6569 }) 6570 Web({ src: 'www.example.com', controller: this.controller }) 6571 } 6572 } 6573} 6574``` 6575### pauseAllTimers<sup>12+</sup> 6576 6577pauseAllTimers(): void 6578 6579Pauses all WebView timers. 6580 6581**System capability**: SystemCapability.Web.Webview.Core 6582 6583**Error codes** 6584 6585For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6586 6587| ID| Error Message | 6588| -------- | ------------------------------------------------------------ | 6589| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6590 6591**Example** 6592 6593```ts 6594import { webview } from '@kit.ArkWeb'; 6595import { BusinessError } from '@kit.BasicServicesKit'; 6596 6597@Entry 6598@Component 6599struct WebComponent { 6600 controller: webview.WebviewController = new webview.WebviewController(); 6601 6602 build() { 6603 Column() { 6604 Row() { 6605 Button('PauseAllTimers') 6606 .onClick(() => { 6607 try { 6608 webview.WebviewController.pauseAllTimers(); 6609 } catch (error) { 6610 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6611 } 6612 }) 6613 } 6614 Web({ src: $rawfile("index.html"), controller: this.controller }) 6615 } 6616 } 6617} 6618``` 6619HTML file to be loaded: 6620 6621```html 6622<!DOCTYPE html> 6623<html> 6624 <body> 6625 <button style="width:300px;height:150px;font-size:50px" onclick="startTimer()">start</button> 6626 <button style="width:300px;height:150px;font-size:50px" onclick="resetTimer()">reset</button> 6627 <input style="width:300px;height:150px;font-size:50px" value="0" id="show_num"> 6628 </body> 6629</html> 6630<script> 6631 var timer = null; 6632 var num = 0; 6633 6634 function startTimer() { 6635 timer = setInterval(function() { 6636 document.getElementById("show_num").value = ++num; 6637 }, 1000); 6638 } 6639</script> 6640``` 6641 6642### resumeAllTimers<sup>12+</sup> 6643 6644resumeAllTimers(): void 6645 6646Resumes all timers that are paused from the **pauseAllTimers()** API. 6647 6648**System capability**: SystemCapability.Web.Webview.Core 6649 6650**Error codes** 6651 6652For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6653 6654| ID| Error Message | 6655| -------- | ------------------------------------------------------------ | 6656| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6657 6658**Example** 6659 6660```ts 6661import { webview } from '@kit.ArkWeb'; 6662import { BusinessError } from '@kit.BasicServicesKit'; 6663 6664@Entry 6665@Component 6666struct WebComponent { 6667 controller: webview.WebviewController = new webview.WebviewController(); 6668 6669 build() { 6670 Column() { 6671 Row() { 6672 Button('ResumeAllTimers') 6673 .onClick(() => { 6674 try { 6675 webview.WebviewController.resumeAllTimers(); 6676 } catch (error) { 6677 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6678 } 6679 }) 6680 Button('PauseAllTimers') 6681 .onClick(() => { 6682 try { 6683 webview.WebviewController.pauseAllTimers(); 6684 } catch (error) { 6685 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6686 } 6687 }) 6688 } 6689 Web({ src: $rawfile("index.html"), controller: this.controller }) 6690 } 6691 } 6692} 6693``` 6694HTML file to be loaded: 6695 6696```html 6697<!DOCTYPE html> 6698<html> 6699 <body> 6700 <button style="width:300px;height:150px;font-size:50px" onclick="startTimer()">start</button> 6701 <button style="width:300px;height:150px;font-size:50px" onclick="resetTimer()">reset</button> 6702 <input style="width:300px;height:150px;font-size:50px" value="0" id="show_num"> 6703 </body> 6704</html> 6705<script> 6706 var timer = null; 6707 var num = 0; 6708 6709 function startTimer() { 6710 timer = setInterval(function() { 6711 document.getElementById("show_num").value = ++num; 6712 }, 1000); 6713 } 6714 6715 function resetTimer() { 6716 clearInterval(timer); 6717 document.getElementById("show_num").value = 0; 6718 num = 0; 6719 } 6720</script> 6721``` 6722 6723### stopAllMedia<sup>12+</sup> 6724 6725stopAllMedia(): void 6726 6727Stops all audio and video on a web page. 6728 6729**System capability**: SystemCapability.Web.Webview.Core 6730 6731**Error codes** 6732 6733For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6734 6735| ID| Error Message | 6736| -------- | ------------------------------------------------------------ | 6737| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6738 6739**Example** 6740 6741```ts 6742// xxx.ets 6743import { webview } from '@kit.ArkWeb'; 6744import { BusinessError } from '@kit.BasicServicesKit'; 6745 6746@Entry 6747@Component 6748struct WebComponent { 6749 controller: webview.WebviewController = new webview.WebviewController(); 6750 6751 build() { 6752 Column() { 6753 Button('stopAllMedia') 6754 .onClick(() => { 6755 try { 6756 this.controller.stopAllMedia(); 6757 } catch (error) { 6758 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6759 } 6760 }) 6761 Web({ src: 'www.example.com', controller: this.controller }) 6762 } 6763 } 6764} 6765``` 6766 6767### pauseAllMedia<sup>12+</sup> 6768 6769pauseAllMedia(): void 6770 6771Pauses all audio and video on a web page. 6772 6773**System capability**: SystemCapability.Web.Webview.Core 6774 6775**Error codes** 6776 6777For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6778 6779| ID| Error Message | 6780| -------- | ------------------------------------------------------------ | 6781| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6782 6783**Example** 6784 6785```ts 6786// xxx.ets 6787import { webview } from '@kit.ArkWeb'; 6788import { BusinessError } from '@kit.BasicServicesKit'; 6789 6790@Entry 6791@Component 6792struct WebComponent { 6793 controller: webview.WebviewController = new webview.WebviewController(); 6794 6795 build() { 6796 Column() { 6797 Button('pauseAllMedia') 6798 .onClick(() => { 6799 try { 6800 this.controller.pauseAllMedia(); 6801 } catch (error) { 6802 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6803 } 6804 }) 6805 Web({ src: 'www.example.com', controller: this.controller }) 6806 } 6807 } 6808} 6809``` 6810 6811### resumeAllMedia<sup>12+</sup> 6812 6813resumeAllMedia(): void 6814 6815Resumes the playback of the audio and video that are paused by the pauseAllMedia interface. 6816 6817**System capability**: SystemCapability.Web.Webview.Core 6818 6819**Error codes** 6820 6821For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6822 6823| ID| Error Message | 6824| -------- | ------------------------------------------------------------ | 6825| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6826 6827**Example** 6828 6829```ts 6830// xxx.ets 6831import { webview } from '@kit.ArkWeb'; 6832import { BusinessError } from '@kit.BasicServicesKit'; 6833 6834@Entry 6835@Component 6836struct WebComponent { 6837 controller: webview.WebviewController = new webview.WebviewController(); 6838 6839 build() { 6840 Column() { 6841 Button('resumeAllMedia') 6842 .onClick(() => { 6843 try { 6844 this.controller.resumeAllMedia(); 6845 } catch (error) { 6846 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6847 } 6848 }) 6849 Web({ src: 'www.example.com', controller: this.controller }) 6850 } 6851 } 6852} 6853``` 6854 6855### closeAllMediaPresentations<sup>12+</sup> 6856 6857closeAllMediaPresentations(): void 6858 6859Closes all full-screen videos on a web page. 6860 6861**System capability**: SystemCapability.Web.Webview.Core 6862 6863**Error codes** 6864 6865For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6866 6867| ID| Error Message | 6868| -------- | ------------------------------------------------------------ | 6869| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6870 6871**Example** 6872 6873```ts 6874// xxx.ets 6875import { webview } from '@kit.ArkWeb'; 6876import { BusinessError } from '@kit.BasicServicesKit'; 6877 6878@Entry 6879@Component 6880struct WebComponent { 6881 controller: webview.WebviewController = new webview.WebviewController(); 6882 6883 build() { 6884 Column() { 6885 Button('closeAllMediaPresentations') 6886 .onClick(() => { 6887 try { 6888 this.controller.closeAllMediaPresentations(); 6889 } catch (error) { 6890 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6891 } 6892 }) 6893 Web({ src: 'www.example.com', controller: this.controller }) 6894 } 6895 } 6896} 6897``` 6898 6899### getMediaPlaybackState<sup>12+</sup> 6900 6901getMediaPlaybackState(): MediaPlaybackState 6902 6903Queries the current audio and video playback control status. 6904 6905**System capability**: SystemCapability.Web.Webview.Core 6906 6907**Return value** 6908 6909| Type | Description | 6910| ------------------------------------------- | --------------------------------------------------------- | 6911| [MediaPlaybackState](#mediaplaybackstate12) | Playback control status of the current web page. The options are **NONE**, **PLAYING**, **PAUSED**, and **STOPPED**.| 6912 6913**Error codes** 6914 6915For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6916 6917| ID| Error Message | 6918| -------- | ------------------------------------------------------------ | 6919| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6920 6921**Example** 6922 6923```ts 6924// xxx.ets 6925import { webview } from '@kit.ArkWeb'; 6926import { BusinessError } from '@kit.BasicServicesKit'; 6927 6928@Entry 6929@Component 6930struct WebComponent { 6931 controller: webview.WebviewController = new webview.WebviewController(); 6932 6933 build() { 6934 Column() { 6935 Button('getMediaPlaybackState') 6936 .onClick(() => { 6937 try { 6938 console.log("MediaPlaybackState : " + this.controller.getMediaPlaybackState()); 6939 } catch (error) { 6940 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6941 } 6942 }) 6943 Web({ src: 'www.example.com', controller: this.controller }) 6944 } 6945 } 6946} 6947``` 6948 6949### setWebSchemeHandler<sup>12+</sup> 6950 6951setWebSchemeHandler(scheme: string, handler: WebSchemeHandler): void 6952 6953Sets the [WebSchemeHandler](#webschemehandler12), [WebSchemeHandler](#webschemehandler12) class for the current Web component to intercept requests of a specified scheme. 6954 6955**System capability**: SystemCapability.Web.Webview.Core 6956 6957**Parameters** 6958 6959| Name| Type | Mandatory| Description | 6960| ------ | ------ | ---- | :------------------------ | 6961| scheme | string | Yes | Protocol to be intercepted.| 6962| handler | [WebSchemeHandler](#webschemehandler12) | Yes | Interceptor that intercepts this protocol.| 6963 6964**Error codes** 6965 6966For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6967 6968| ID| Error Message | 6969| -------- | ------------------------------------------------------------ | 6970| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 6971| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6972 6973**Example** 6974 6975```ts 6976// xxx.ets 6977import { webview } from '@kit.ArkWeb'; 6978import { BusinessError } from '@kit.BasicServicesKit'; 6979 6980@Entry 6981@Component 6982struct WebComponent { 6983 controller: webview.WebviewController = new webview.WebviewController(); 6984 schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); 6985 6986 build() { 6987 Column() { 6988 Button('setWebSchemeHandler') 6989 .onClick(() => { 6990 try { 6991 this.controller.setWebSchemeHandler('http', this.schemeHandler); 6992 } catch (error) { 6993 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6994 } 6995 }) 6996 Web({ src: 'www.example.com', controller: this.controller }) 6997 } 6998 } 6999} 7000``` 7001 7002### clearWebSchemeHandler<sup>12+</sup> 7003 7004clearWebSchemeHandler(): void 7005 7006Clears all WebSchemeHandlers set for the current Web component. 7007 7008**System capability**: SystemCapability.Web.Webview.Core 7009 7010**Error codes** 7011 7012For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7013 7014| ID| Error Message | 7015| -------- | ------------------------------------------------------------ | 7016| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7017 7018**Example** 7019 7020```ts 7021// xxx.ets 7022import { webview } from '@kit.ArkWeb'; 7023import { BusinessError } from '@kit.BasicServicesKit'; 7024 7025@Entry 7026@Component 7027struct WebComponent { 7028 controller: webview.WebviewController = new webview.WebviewController(); 7029 7030 build() { 7031 Column() { 7032 Button('clearWebSchemeHandler') 7033 .onClick(() => { 7034 try { 7035 this.controller.clearWebSchemeHandler(); 7036 } catch (error) { 7037 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7038 } 7039 }) 7040 Web({ src: 'www.example.com', controller: this.controller }) 7041 } 7042 } 7043} 7044``` 7045 7046### setServiceWorkerWebSchemeHandler<sup>12+</sup> 7047 7048setServiceWorkerWebSchemeHandler(scheme: string, handler: WebSchemeHandler): void 7049 7050Sets the WebSchemeHandler used to intercept ServiceWorker for all Web components of the current application. 7051 7052**System capability**: SystemCapability.Web.Webview.Core 7053 7054**Parameters** 7055 7056| Name| Type | Mandatory| Description | 7057| ------ | ------ | ---- | :------------------------ | 7058| scheme | string | Yes | Protocol to be intercepted.| 7059| handler | [WebSchemeHandler](#webschemehandler12) | Yes | Interceptor that intercepts this protocol.| 7060 7061**Error codes** 7062 7063For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7064 7065| ID| Error Message | 7066| -------- | ------------------------------------------------------------ | 7067| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 7068 7069**Example** 7070 7071```ts 7072// xxx.ets 7073import { webview } from '@kit.ArkWeb'; 7074import { BusinessError } from '@kit.BasicServicesKit'; 7075 7076@Entry 7077@Component 7078struct WebComponent { 7079 controller: webview.WebviewController = new webview.WebviewController(); 7080 schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); 7081 7082 build() { 7083 Column() { 7084 Button('setWebSchemeHandler') 7085 .onClick(() => { 7086 try { 7087 webview.WebviewController.setServiceWorkerWebSchemeHandler('http', this.schemeHandler); 7088 } catch (error) { 7089 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7090 } 7091 }) 7092 Web({ src: 'www.example.com', controller: this.controller }) 7093 } 7094 } 7095} 7096``` 7097 7098### clearServiceWorkerWebSchemeHandler<sup>12+</sup> 7099 7100clearServiceWorkerWebSchemeHandler(): void 7101 7102Clears all WebSchemeHandlers that are set in the application and used to intercept ServiceWorker. 7103 7104**System capability**: SystemCapability.Web.Webview.Core 7105 7106**Example** 7107 7108```ts 7109// xxx.ets 7110import { webview } from '@kit.ArkWeb'; 7111 7112@Entry 7113@Component 7114struct WebComponent { 7115 controller: webview.WebviewController = new webview.WebviewController(); 7116 7117 build() { 7118 Column() { 7119 Button('clearServiceWorkerWebSchemeHandler') 7120 .onClick(() => { 7121 webview.WebviewController.clearServiceWorkerWebSchemeHandler(); 7122 }) 7123 Web({ src: 'www.example.com', controller: this.controller }) 7124 } 7125 } 7126} 7127``` 7128 7129### startCamera<sup>12+</sup> 7130 7131startCamera(): void 7132 7133Enables the camera capture of the current web page. 7134 7135**System capability**: SystemCapability.Web.Webview.Core 7136 7137**Error codes** 7138 7139For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7140 7141| ID| Error Message | 7142| -------- | ------------------------------------------------------------ | 7143| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7144 7145**Example** 7146```ts 7147// xxx.ets 7148import { webview } from '@kit.ArkWeb'; 7149import { BusinessError } from '@kit.BasicServicesKit'; 7150import { abilityAccessCtrl, PermissionRequestResult, common } from '@kit.AbilityKit'; 7151 7152let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); 7153try { 7154 let context: Context = getContext(this) as common.UIAbilityContext; 7155 atManager.requestPermissionsFromUser(context, ['ohos.permission.CAMERA'], (err: BusinessError, data: PermissionRequestResult) => { 7156 console.info('data:' + JSON.stringify(data)); 7157 console.info('data permissions:' + data.permissions); 7158 console.info('data authResults:' + data.authResults); 7159 }) 7160} catch (error) { 7161 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7162} 7163 7164@Entry 7165@Component 7166struct WebComponent { 7167 controller: webview.WebviewController = new webview.WebviewController(); 7168 7169 build() { 7170 Column() { 7171 Button("startCamera").onClick(() => { 7172 try { 7173 this.controller.startCamera(); 7174 } catch (error) { 7175 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7176 } 7177 }) 7178 Button("stopCamera").onClick(() => { 7179 try { 7180 this.controller.stopCamera(); 7181 } catch (error) { 7182 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7183 } 7184 }) 7185 Button("closeCamera").onClick(() => { 7186 try { 7187 this.controller.closeCamera(); 7188 } catch (error) { 7189 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7190 } 7191 }) 7192 Web({ src: $rawfile('index.html'), controller: this.controller }) 7193 .onPermissionRequest((event) => { 7194 if (event) { 7195 AlertDialog.show({ 7196 title: 'title', 7197 message: 'text', 7198 primaryButton: { 7199 value: 'deny', 7200 action: () => { 7201 event.request.deny(); 7202 } 7203 }, 7204 secondaryButton: { 7205 value: 'onConfirm', 7206 action: () => { 7207 event.request.grant(event.request.getAccessibleResource()); 7208 } 7209 }, 7210 cancel: () => { 7211 event.request.deny(); 7212 } 7213 }) 7214 } 7215 }) 7216 } 7217 } 7218} 7219 7220``` 7221HTML file to be loaded: 7222 ```html 7223<!-- index.html --> 7224<!DOCTYPE html> 7225<html> 7226 <head> 7227 <meta charset="UTF-8"> 7228 </head> 7229 <body> 7230 <video id="video" width="400px" height="400px" autoplay="autoplay"> 7231 </video> 7232 <input type="button" title="HTML5 Camera" value="Enable Camera" onclick="getMedia()"/> 7233 <script> 7234 function getMedia() { 7235 let constraints = { 7236 video: { 7237 width: 500, 7238 height: 500 7239 }, 7240 audio: true 7241 } 7242 let video = document.getElementById("video"); 7243 let promise = navigator.mediaDevices.getUserMedia(constraints); 7244 promise.then(function(MediaStream) { 7245 video.srcObject = MediaStream; 7246 video.play(); 7247 }) 7248 } 7249 </script> 7250 </body> 7251</html> 7252 ``` 7253 7254### stopCamera<sup>12+</sup> 7255 7256stopCamera(): void 7257 7258Stops the camera capture of the current web page. 7259 7260**System capability**: SystemCapability.Web.Webview.Core 7261 7262**Error codes** 7263 7264For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7265 7266| ID| Error Message | 7267| -------- | ------------------------------------------------------------ | 7268| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7269 7270**Example** 7271 7272For the complete sample code, see [startCamera](#startcamera12). 7273 7274### closeCamera<sup>12+</sup> 7275 7276closeCamera(): void 7277 7278Disables the camera capture of the current web page. 7279 7280**System capability**: SystemCapability.Web.Webview.Core 7281 7282**Error codes** 7283 7284For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7285 7286| ID| Error Message | 7287| -------- | ------------------------------------------------------------ | 7288| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7289 7290**Example** 7291 7292For the complete sample code, see [startCamera](#startcamera12). 7293 7294### precompileJavaScript<sup>12+</sup> 7295 7296precompileJavaScript(url: string, script: string | Uint8Array, cacheOptions: CacheOptions): Promise\<number\> 7297 7298Precompiles JavaScript to generate the bytecode cache or update the existing bytecode cache based on the provided parameters. 7299The API determines whether to update the existing bytecode cache based on the provided file information, E-Tag response header, and Last-Modified response header. 7300 7301**System capability**: SystemCapability.Web.Webview.Core 7302 7303**Parameters** 7304 7305| Name | Type | Mandatory| Description | 7306| ------- | ------ | ---- | :-------------------- | 7307| url | string | Yes | Network address corresponding to the local JavaScript file, that is, the network address used when the service web page requests the server version of the file. The network address supports only the HTTP and HTTPS protocols and contains a maximum of 2048 characters. If the cache corresponding to the network address is invalid, the service web page requests the corresponding resource through the network. | 7308| script | string \| Uint8Array | Yes | Text content of the local JavaScript. The content cannot be empty. | 7309| cacheOptions | [CacheOptions](#cacheoptions12) | Yes | Whether to update the bytecode cache. | 7310 7311**Return value** 7312 7313| Type | Description | 7314| ----------------------------------- | --------------------------- | 7315| Promise\<number\> | Promise used to return the error code for generating the bytecode cache. The value **0** indicates no error, and the value **-1** indicates an internal error.| 7316 7317**Error codes** 7318 7319For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7320 7321| ID| Error Message | 7322| -------- | ------------------------------------------------------------ | 7323| 401 | Invalid input parameter.Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | 7324| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7325 7326**Example** 7327 7328The API is recommended for use in conjunction with dynamic components. Employ offline **Web** components to generate bytecode caches, and at the appropriate time, load service **Web** components to utilize these bytecode caches. The following is a code example: 7329 73301. Save **UIContext** to localStorage in **EntryAbility**. 7331 7332 ```ts 7333 // EntryAbility.ets 7334 import { UIAbility } from '@kit.AbilityKit'; 7335 import { window } from '@kit.ArkUI'; 7336 7337 const localStorage: LocalStorage = new LocalStorage('uiContext'); 7338 7339 export default class EntryAbility extends UIAbility { 7340 storage: LocalStorage = localStorage; 7341 7342 onWindowStageCreate(windowStage: window.WindowStage) { 7343 windowStage.loadContent('pages/Index', this.storage, (err, data) => { 7344 if (err.code) { 7345 return; 7346 } 7347 7348 this.storage.setOrCreate<UIContext>("uiContext", windowStage.getMainWindowSync().getUIContext()); 7349 }); 7350 } 7351 } 7352 ``` 7353 73542. Write the basic code required by the dynamic component. 7355 7356 ```ts 7357 // DynamicComponent.ets 7358 import { NodeController, BuilderNode, FrameNode, UIContext } from '@kit.ArkUI'; 7359 7360 export interface BuilderData { 7361 url: string; 7362 controller: WebviewController; 7363 } 7364 7365 const storage = LocalStorage.getShared(); 7366 7367 export class NodeControllerImpl extends NodeController { 7368 private rootNode: BuilderNode<BuilderData[]> | null = null; 7369 private wrappedBuilder: WrappedBuilder<BuilderData[]> | null = null; 7370 7371 constructor(wrappedBuilder: WrappedBuilder<BuilderData[]>) { 7372 super(); 7373 this.wrappedBuilder = wrappedBuilder; 7374 } 7375 7376 makeNode(): FrameNode | null { 7377 if (this.rootNode != null) { 7378 return this.rootNode.getFrameNode(); 7379 } 7380 return null; 7381 } 7382 7383 initWeb(url: string, controller: WebviewController) { 7384 if(this.rootNode != null) { 7385 return; 7386 } 7387 7388 const uiContext: UIContext = storage.get<UIContext>("uiContext") as UIContext; 7389 if (!uiContext) { 7390 return; 7391 } 7392 this.rootNode = new BuilderNode(uiContext); 7393 this.rootNode.build(this.wrappedBuilder, { url: url, controller: controller }); 7394 } 7395 } 7396 7397 export const createNode = (wrappedBuilder: WrappedBuilder<BuilderData[]>, data: BuilderData) => { 7398 const baseNode = new NodeControllerImpl(wrappedBuilder); 7399 baseNode.initWeb(data.url, data.controller); 7400 return baseNode; 7401 } 7402 ``` 7403 74043. Write a component for generating bytecode caches. In this example, the local JavaScript resource content is read through the file reading API from a local file in the **rawfile** directory. 7405 7406 <!--code_no_check--> 7407 ```ts 7408 // PrecompileWebview.ets 7409 import { BuilderData } from "./DynamicComponent"; 7410 import { Config, configs } from "./PrecompileConfig"; 7411 7412 @Builder 7413 function WebBuilder(data: BuilderData) { 7414 Web({ src: data.url, controller: data.controller }) 7415 .onControllerAttached(() => { 7416 precompile(data.controller, configs); 7417 }) 7418 .fileAccess(true) 7419 } 7420 7421 export const precompileWebview = wrapBuilder<BuilderData[]>(WebBuilder); 7422 7423 export const precompile = async (controller: WebviewController, configs: Array<Config>) => { 7424 for (const config of configs) { 7425 let content = await readRawFile(config.localPath); 7426 7427 try { 7428 controller.precompileJavaScript(config.url, content, config.options) 7429 .then(errCode => { 7430 console.error("precompile successfully! " + errCode); 7431 }).catch((errCode: number) => { 7432 console.error("precompile failed. " + errCode); 7433 }); 7434 } catch (err) { 7435 console.error("precompile failed. " + err.code + " " + err.message); 7436 } 7437 } 7438 } 7439 7440 async function readRawFile(path: string) { 7441 try { 7442 return await getContext().resourceManager.getRawFileContent(path);; 7443 } catch (err) { 7444 return new Uint8Array(0); 7445 } 7446 } 7447 ``` 7448 7449JavaScript resources can also be obtained through [network requests](../apis-network-kit/js-apis-http.md). However, the HTTP response header obtained using this method is not in the standard HTTP response header format. Additional steps are required to convert the response header into the standard HTTP response header format before use. If the response header obtained through a network request is e-tag, convert it to E-Tag before using it. 7450 74514. Compile the code of the service component. 7452 7453 <!--code_no_check--> 7454 ```ts 7455 // BusinessWebview.ets 7456 import { BuilderData } from "./DynamicComponent"; 7457 7458 @Builder 7459 function WebBuilder(data: BuilderData) { 7460 // The component can be extended based on service requirements. 7461 Web({ src: data.url, controller: data.controller }) 7462 .cacheMode(CacheMode.Default) 7463 } 7464 7465 export const businessWebview = wrapBuilder<BuilderData[]>(WebBuilder); 7466 ``` 7467 74685. Write the resource configuration information. 7469 7470 ```ts 7471 // PrecompileConfig.ets 7472 import { webview } from '@kit.ArkWeb' 7473 7474 export interface Config { 7475 url: string, 7476 localPath: string, // Local resource path 7477 options: webview.CacheOptions 7478 } 7479 7480 export let configs: Array<Config> = [ 7481 { 7482 url: "https://www.example.com/example.js", 7483 localPath: "example.js", 7484 options: { 7485 responseHeaders: [ 7486 { headerKey: "E-Tag", headerValue: "aWO42N9P9dG/5xqYQCxsx+vDOoU="}, 7487 { headerKey: "Last-Modified", headerValue: "Wed, 21 Mar 2024 10:38:41 GMT"} 7488 ] 7489 } 7490 } 7491 ] 7492 ``` 7493 74946. Use the component on the page. 7495 7496 <!--code_no_check--> 7497 ```ts 7498 // Index.ets 7499 import { webview } from '@kit.ArkWeb'; 7500 import { NodeController } from '@kit.ArkUI'; 7501 import { createNode } from "./DynamicComponent" 7502 import { precompileWebview } from "./PrecompileWebview" 7503 import { businessWebview } from "./BusinessWebview" 7504 7505 @Entry 7506 @Component 7507 struct Index { 7508 @State precompileNode: NodeController | undefined = undefined; 7509 precompileController: webview.WebviewController = new webview.WebviewController(); 7510 7511 @State businessNode: NodeController | undefined = undefined; 7512 businessController: webview.WebviewController = new webview.WebviewController(); 7513 7514 aboutToAppear(): void { 7515 // Initialize the Web component used to inject local resources. 7516 this.precompileNode = createNode(precompileWebview, 7517 { url: "https://www.example.com/empty.html", controller: this.precompileController}); 7518 } 7519 7520 build() { 7521 Column() { 7522 // Load the Web component used by the service at a proper time. In this example, the button is clicked. 7523 Button ("Load Page") 7524 .onClick(() => { 7525 this.businessNode = createNode(businessWebview, { 7526 url: "https://www.example.com/business.html", 7527 controller: this.businessController 7528 }); 7529 }) 7530 // The Web component used for the service. 7531 NodeContainer(this.businessNode); 7532 } 7533 } 7534 } 7535 ``` 7536 7537To update the locally generated compiled bytecode, change the value of E-Tag or Last-Modified in responseHeaders of the cacheOptions parameter and call the API again. 7538 7539### onCreateNativeMediaPlayer<sup>12+</sup> 7540 7541onCreateNativeMediaPlayer(callback: CreateNativeMediaPlayerCallback): void 7542 7543Called when the [application takes over media playback on the web page](ts-basic-components-web.md#enablenativemediaplayer12) and media is played on the web page. 7544If the application does not take over media playback on the web page, this callback is not invoked. 7545 7546**System capability**: SystemCapability.Web.Webview.Core 7547 7548**Parameters** 7549 7550| Name| Type| Mandatory| Description| 7551|--------|------|------|------| 7552| callback | [CreateNativeMediaPlayerCallback](#createnativemediaplayercallback12) | Yes| Callback when the application takes over media playback on the web page.| 7553 7554**Example** 7555 7556```ts 7557// xxx.ets 7558import { webview } from '@kit.ArkWeb'; 7559 7560class ActualNativeMediaPlayerListener { 7561 handler: webview.NativeMediaPlayerHandler; 7562 7563 constructor(handler: webview.NativeMediaPlayerHandler) { 7564 this.handler = handler; 7565 } 7566 7567 onPlaying() { 7568 // The native media player starts playback. 7569 this.handler.handleStatusChanged(webview.PlaybackStatus.PLAYING); 7570 } 7571 onPaused() { 7572 // The native media player pauses the playback. 7573 this.handler.handleStatusChanged(webview.PlaybackStatus.PAUSED); 7574 } 7575 onSeeking() { 7576 // The local player starts to jump to the target time point. 7577 this.handler.handleSeeking(); 7578 } 7579 onSeekDone() { 7580 // The native media player seeks to the target time point. 7581 this.handler.handleSeekFinished(); 7582 } 7583 onEnded() { 7584 // The playback on the native media player is ended. 7585 this.handler.handleEnded(); 7586 } 7587 onVolumeChanged() { 7588 // Obtain the volume of the local player. 7589 let volume: number = getVolume(); 7590 this.handler.handleVolumeChanged(volume); 7591 } 7592 onCurrentPlayingTimeUpdate() { 7593 // Update the playback time. 7594 let currentTime: number = getCurrentPlayingTime(); 7595 // Convert the time unit to second. 7596 let currentTimeInSeconds = convertToSeconds(currentTime); 7597 this.handler.handleTimeUpdate(currentTimeInSeconds); 7598 } 7599 onBufferedChanged() { 7600 // The cache is changed. 7601 // Obtain the cache duration of the native media player. 7602 let bufferedEndTime: number = getCurrentBufferedTime(); 7603 // Convert the time unit to second. 7604 let bufferedEndTimeInSeconds = convertToSeconds(bufferedEndTime); 7605 this.handler.handleBufferedEndTimeChanged(bufferedEndTimeInSeconds); 7606 7607 // Check the cache status. 7608 // If the cache status changes, notify the ArkWeb engine of the cache status. 7609 let lastReadyState: webview.ReadyState = getLastReadyState(); 7610 let currentReadyState: webview.ReadyState = getCurrentReadyState(); 7611 if (lastReadyState != currentReadyState) { 7612 this.handler.handleReadyStateChanged(currentReadyState); 7613 } 7614 } 7615 onEnterFullscreen() { 7616 // The native media player enters the full screen mode. 7617 let isFullscreen: boolean = true; 7618 this.handler.handleFullscreenChanged(isFullscreen); 7619 } 7620 onExitFullscreen() { 7621 // The native media player exits the full screen mode. 7622 let isFullscreen: boolean = false; 7623 this.handler.handleFullscreenChanged(isFullscreen); 7624 } 7625 onUpdateVideoSize(width: number, height: number) { 7626 //Notify the ArkWeb engine when the local player parses the video width and height. 7627 this.handler.handleVideoSizeChanged(width, height); 7628 } 7629 7630 // Listen for other state of the native media player. 7631} 7632 7633class NativeMediaPlayerImpl implements webview.NativeMediaPlayerBridge { 7634 constructor(handler: webview.NativeMediaPlayerHandler, mediaInfo: webview.MediaInfo) { 7635 // 1. Create a listener for the native media player. 7636 let listener: ActualNativeMediaPlayerListener = new ActualNativeMediaPlayerListener(handler); 7637 // 2. Create a native media player. 7638 // 3. Listen for the local player. 7639 // ... 7640 } 7641 7642 updateRect(x: number, y: number, width: number, height: number) { 7643 // The position and size of the <video> tag are changed. 7644 // Make changes based on the information change. 7645 } 7646 7647 play() { 7648 // Start the native media player for playback. 7649 } 7650 7651 pause() { 7652 //Pause the playback on the local player. 7653 } 7654 7655 seek(targetTime: number) { 7656 // The local player jumps to a specified time point. 7657 } 7658 7659 release() { 7660 // Destroy the local player. 7661 } 7662 7663 setVolume(volume: number) { 7664 // The ArkWeb kernel requires the volume of the local player to be adjusted. 7665 // Set the volume of the local player. 7666 } 7667 7668 setMuted(muted: boolean) { 7669 // Mute or unmute the local player. 7670 } 7671 7672 setPlaybackRate(playbackRate: number) { 7673 // Adjust the playback speed of the local player. 7674 } 7675 7676 enterFullscreen() { 7677 // Set the local player to play in full screen mode. 7678 } 7679 7680 exitFullscreen() { 7681 // Set the local player to exit full screen mode. 7682 } 7683 7684 resumePlayer() { 7685 // Create a local player again. 7686 // Resume the status information of the local player. 7687 } 7688 7689 suspendPlayer(type: SuspendType) { 7690 // Record the status information of the local player. 7691 // Destroy the local player. 7692 } 7693} 7694 7695@Entry 7696@Component 7697struct WebComponent { 7698 controller: webview.WebviewController = new webview.WebviewController() 7699 build() { 7700 Column() { 7701 Web({ src: 'www.example.com', controller: this.controller }) 7702 .enableNativeMediaPlayer({enable: true, shouldOverlay: false}) 7703 .onPageBegin((event) => { 7704 this.controller.onCreateNativeMediaPlayer((handler: webview.NativeMediaPlayerHandler, mediaInfo: webview.MediaInfo) => { 7705 if (!shouldHandle(mediaInfo)) { 7706 // The local player does not take over the media. 7707 // The ArkWeb engine will play the media with its own player. 7708 return null; 7709 } 7710 let nativePlayer: webview.NativeMediaPlayerBridge = new NativeMediaPlayerImpl(handler, mediaInfo); 7711 return nativePlayer; 7712 }); 7713 }) 7714 } 7715 } 7716} 7717 7718// stub 7719function getVolume() { 7720 return 1; 7721} 7722function getCurrentPlayingTime() { 7723 return 1; 7724} 7725function getCurrentBufferedTime() { 7726 return 1; 7727} 7728function convertToSeconds(input: number) { 7729 return input; 7730} 7731function getLastReadyState() { 7732 return webview.ReadyState.HAVE_NOTHING; 7733} 7734function getCurrentReadyState() { 7735 return webview.ReadyState.HAVE_NOTHING; 7736} 7737function shouldHandle(mediaInfo: webview.MediaInfo) { 7738 return true; 7739} 7740``` 7741 7742### injectOfflineResources<sup>12+</sup> 7743 7744injectOfflineResources(resourceMaps: Array\<[OfflineResourceMap](#offlineresourcemap12)\>): void 7745 7746Injects local offline resources to the memory cache to improve the initial page startup speed. 7747Resources in the memory cache are automatically managed by the ArkWeb engine. When the injected resources are excessive and cause significant memory pressure, the engine will automatically release unused resources. It is advisable to avoid injecting a large number of resources into the memory cache. 7748Under normal circumstances, the validity period of the resources is controlled by the provided Cache-Control or Expires response header, with a default validity period of 86,400 seconds, which is one day. 7749The MIME type of the resources is configured through the provided Content-Type response header. The Content-Type must comply with standards; otherwise, the resources cannot be used correctly. For resources of type MODULE_JS, a valid MIME type must be provided. For other types, the MIME type is optional. 7750Resources injected in this mode can be loaded only through HTML tags. If the script tag on the business web page uses the **crossorigin** attribute, you must set the Cross-Origin response header to anonymous or use-credentials in the responseHeaders parameter of the interface. 7751After **web_webview.WebviewController.SetRenderProcessMode(web_webview.RenderProcessMode.MULTIPLE)** is called, the application starts the multi-rendering process mode. This API does not take effect in this scenario. 7752 7753**System capability**: SystemCapability.Web.Webview.Core 7754 7755**Parameters** 7756 7757| Name | Type | Mandatory| Description | 7758| ------- | ------ | ---- | :-------------------- | 7759| resourceMaps | Array\<[OfflineResourceMap](#offlineresourcemap12)\> | Yes | Configuration object for local offline resources. A maximum of 30 resources can be injected in a single call, with a maximum size of 10 MB per individual resource. | 7760 7761**Error codes** 7762 7763For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7764 7765| ID| Error Message | 7766| -------- | ------------------------------------------------------------ | 7767| 401 | Invalid input parameter.Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | 7768| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7769| 17100002 | Invalid url. | 7770 7771**Example** 7772 7773When appropriate, use this API in conjunction with dynamic components. Offline **Web** components are used to inject resources into the engine's memory cache, and at the appropriate time, the service **Web** components load and utilize these resources. The following is a code example: 77741. Save **UIContext** to localStorage in **EntryAbility**. 7775 7776 ```ts 7777 // EntryAbility.ets 7778 import { UIAbility } from '@kit.AbilityKit'; 7779 import { window } from '@kit.ArkUI'; 7780 7781 const localStorage: LocalStorage = new LocalStorage('uiContext'); 7782 7783 export default class EntryAbility extends UIAbility { 7784 storage: LocalStorage = localStorage; 7785 7786 onWindowStageCreate(windowStage: window.WindowStage) { 7787 windowStage.loadContent('pages/Index', this.storage, (err, data) => { 7788 if (err.code) { 7789 return; 7790 } 7791 7792 this.storage.setOrCreate<UIContext>("uiContext", windowStage.getMainWindowSync().getUIContext()); 7793 }); 7794 } 7795 } 7796 ``` 7797 77982. Write the basic code required by the dynamic component. 7799 7800 ```ts 7801 // DynamicComponent.ets 7802 import { NodeController, BuilderNode, FrameNode, UIContext } from '@kit.ArkUI'; 7803 7804 export interface BuilderData { 7805 url: string; 7806 controller: WebviewController; 7807 } 7808 7809 const storage = LocalStorage.getShared(); 7810 7811 export class NodeControllerImpl extends NodeController { 7812 private rootNode: BuilderNode<BuilderData[]> | null = null; 7813 private wrappedBuilder: WrappedBuilder<BuilderData[]> | null = null; 7814 7815 constructor(wrappedBuilder: WrappedBuilder<BuilderData[]>) { 7816 super(); 7817 this.wrappedBuilder = wrappedBuilder; 7818 } 7819 7820 makeNode(): FrameNode | null { 7821 if (this.rootNode != null) { 7822 return this.rootNode.getFrameNode(); 7823 } 7824 return null; 7825 } 7826 7827 initWeb(url: string, controller: WebviewController) { 7828 if(this.rootNode != null) { 7829 return; 7830 } 7831 7832 const uiContext: UIContext = storage.get<UIContext>("uiContext") as UIContext; 7833 if (!uiContext) { 7834 return; 7835 } 7836 this.rootNode = new BuilderNode(uiContext); 7837 this.rootNode.build(this.wrappedBuilder, { url: url, controller: controller }); 7838 } 7839 } 7840 7841 export const createNode = (wrappedBuilder: WrappedBuilder<BuilderData[]>, data: BuilderData) => { 7842 const baseNode = new NodeControllerImpl(wrappedBuilder); 7843 baseNode.initWeb(data.url, data.controller); 7844 return baseNode; 7845 } 7846 ``` 7847 78483. Write the component code for injecting resources. In this example, the local resource content reads the local file in the **rawfile** directory through the file reading API. 7849 7850 <!--code_no_check--> 7851 ```ts 7852 // InjectWebview.ets 7853 import { webview } from '@kit.ArkWeb'; 7854 import { resourceConfigs } from "./Resource"; 7855 import { BuilderData } from "./DynamicComponent"; 7856 7857 @Builder 7858 function WebBuilder(data: BuilderData) { 7859 Web({ src: data.url, controller: data.controller }) 7860 .onControllerAttached(async () => { 7861 try { 7862 data.controller.injectOfflineResources(await getData ()); 7863 } catch (err) { 7864 console.error("error: " + err.code + " " + err.message); 7865 } 7866 }) 7867 .fileAccess(true) 7868 } 7869 7870 export const injectWebview = wrapBuilder<BuilderData[]>(WebBuilder); 7871 7872 export async function getData() { 7873 const resourceMapArr: Array<webview.OfflineResourceMap> = []; 7874 7875 // Read the configuration and read the file content from the rawfile directory. 7876 for (let config of resourceConfigs) { 7877 let buf: Uint8Array = new Uint8Array(0); 7878 if (config.localPath) { 7879 buf = await readRawFile(config.localPath); 7880 } 7881 7882 resourceMapArr.push({ 7883 urlList: config.urlList, 7884 resource: buf, 7885 responseHeaders: config.responseHeaders, 7886 type: config.type, 7887 }) 7888 } 7889 7890 return resourceMapArr; 7891 } 7892 7893 export async function readRawFile(url: string) { 7894 try { 7895 return await getContext().resourceManager.getRawFileContent(url); 7896 } catch (err) { 7897 return new Uint8Array(0); 7898 } 7899 } 7900 ``` 7901 79024. Compile the code of the service component. 7903 7904 <!--code_no_check--> 7905 ```ts 7906 // BusinessWebview.ets 7907 import { BuilderData } from "./DynamicComponent"; 7908 7909 @Builder 7910 function WebBuilder(data: BuilderData) { 7911 // The component can be extended based on service requirements. 7912 Web({ src: data.url, controller: data.controller }) 7913 .cacheMode(CacheMode.Default) 7914 } 7915 7916 export const businessWebview = wrapBuilder<BuilderData[]>(WebBuilder); 7917 ``` 7918 79195. Write the resource configuration information. 7920 7921 ```ts 7922 // Resource.ets 7923 import { webview } from '@kit.ArkWeb'; 7924 7925 export interface ResourceConfig { 7926 urlList: Array<string>, 7927 type: webview.OfflineResourceType, 7928 responseHeaders: Array<Header>, 7929 localPath: string, // Path for storing local resources in the rawfile directory. 7930 } 7931 7932 export const resourceConfigs: Array<ResourceConfig> = [ 7933 { 7934 localPath: "example.png", 7935 urlList: [ 7936 "https://www.example.com/", 7937 "https://www.example.com/path1/example.png", 7938 "https://www.example.com/path2/example.png", 7939 ], 7940 type: webview.OfflineResourceType.IMAGE, 7941 responseHeaders: [ 7942 { headerKey: "Cache-Control", headerValue: "max-age=1000" }, 7943 { headerKey: "Content-Type", headerValue: "image/png" }, 7944 ] 7945 }, 7946 { 7947 localPath: "example.js", 7948 urlList: [ // Only one URL is provided. This URL is used as both the resource origin and the network request address of the resource. 7949 "https://www.example.com/example.js", 7950 ], 7951 type: webview.OfflineResourceType.CLASSIC_JS, 7952 responseHeaders: [ 7953 // Used in <script crossorigin="anonymous" /> mode to provide additional response headers. 7954 { headerKey: "Cross-Origin", headerValue:"anonymous" } 7955 ] 7956 }, 7957 ]; 7958 ``` 7959 79606. Use the component on the page. 7961 <!--code_no_check--> 7962 ```ts 7963 // Index.ets 7964 import { webview } from '@kit.ArkWeb'; 7965 import { NodeController } from '@kit.ArkUI'; 7966 import { createNode } from "./DynamicComponent" 7967 import { injectWebview } from "./InjectWebview" 7968 import { businessWebview } from "./BusinessWebview" 7969 7970 @Entry 7971 @Component 7972 struct Index { 7973 @State injectNode: NodeController | undefined = undefined; 7974 injectController: webview.WebviewController = new webview.WebviewController(); 7975 7976 @State businessNode: NodeController | undefined = undefined; 7977 businessController: webview.WebviewController = new webview.WebviewController(); 7978 7979 aboutToAppear(): void { 7980 // Initialize the Web component used to inject local resources and provide an empty HTML page as the URL. 7981 this.injectNode = createNode(injectWebview, 7982 { url: "https://www.example.com/empty.html", controller: this.injectController}); 7983 } 7984 7985 build() { 7986 Column() { 7987 // Load the Web component used by the service at a proper time. In this example, the button is clicked. 7988 Button ("Load Page") 7989 .onClick(() => { 7990 this.businessNode = createNode(businessWebview, { 7991 url: "https://www.example.com/business.html", 7992 controller: this.businessController 7993 }); 7994 }) 7995 // The Web component used for the service. 7996 NodeContainer(this.businessNode); 7997 } 7998 } 7999 } 8000 ``` 8001 80027. Example of a loaded HTML web page: 8003 8004 ```HTML 8005 <!DOCTYPE html> 8006 <html lang="en"> 8007 <head></head> 8008 <body> 8009 <img src="https://www.example.com/path1/request.png" /> 8010 <img src="https://www.example.com/path2/request.png" /> 8011 <script src="https://www.example.com/example.js" crossorigin="anonymous"></script> 8012 </body> 8013 </html> 8014 ``` 8015 8016### setHostIP<sup>12+</sup> 8017 8018static setHostIP(hostName: string, address: string, aliveTime: number): void 8019 8020Sets the IP address of the host after domain name resolution. 8021 8022**System capability**: SystemCapability.Web.Webview.Core 8023 8024**Parameters** 8025 8026| Name | Type| Mandatory| Description | 8027| --------- | -------- | ---- | ------------------------------------ | 8028| hostName | string | Yes | Domain name of the host whose DNS records are to be added. | 8029| address | string | Yes | Host domain name resolution address (IPv4 and IPv6).| 8030| aliveTime | number | Yes | Cache validity period, in seconds. | 8031 8032**Error codes** 8033 8034For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8035 8036| ID| Error Message | 8037| -------- | ------------------------ | 8038| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | 8039 8040**Example** 8041 8042For details, see [clearHostIP](#clearhostip12). 8043 8044### clearHostIP<sup>12+</sup> 8045 8046static clearHostIP(hostName: string): void 8047 8048Clears the IP address of a specified host after domain name resolution. 8049 8050**System capability**: SystemCapability.Web.Webview.Core 8051 8052**Parameters** 8053 8054| Name | Type| Mandatory| Description | 8055| -------- | -------- | ---- | ------------------------- | 8056| hostName | string | Yes | Domain name of the host whose DNS records are to be cleared.| 8057 8058**Error codes** 8059 8060For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8061 8062| ID| Error Message | 8063| -------- | ------------------------ | 8064| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | 8065 8066**Example** 8067 8068```ts 8069// xxx.ets 8070import { webview } from '@kit.ArkWeb'; 8071import { BusinessError } from '@kit.BasicServicesKit'; 8072 8073@Entry 8074@Component 8075struct WebComponent { 8076 controller: webview.WebviewController = new webview.WebviewController(); 8077 8078 build() { 8079 Column() { 8080 // The setting takes effect before the URL is loaded. 8081 Button('setHostIP') 8082 .onClick(() => { 8083 try { 8084 webview.WebviewController.setHostIP('www.example.com', '127.0.0.1', 30); 8085 } catch (error) { 8086 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8087 } 8088 }) 8089 Button('clearHostIP') 8090 .onClick(() => { 8091 try { 8092 webview.WebviewController.clearHostIP('www.example.com'); 8093 } catch (error) { 8094 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8095 } 8096 }) 8097 Web({ src: 'www.example.com', controller: this.controller }) 8098 } 8099 } 8100} 8101``` 8102 8103### getSurfaceId<sup>12+</sup> 8104 8105getSurfaceId(): string 8106 8107Obtains the ID of the surface corresponding to ArkWeb. This parameter is valid only when the rendering mode of the **Web** component is **ASYNC_RENDER**. The value of **getSurfaceId** can be obtained only after the **Web** component is initialized. 8108 8109**System capability**: SystemCapability.Web.Webview.Core 8110 8111**Return value** 8112 8113| Type | Description | 8114| ------ | ------------------- | 8115| string | ID of the surface held by ArkWeb.| 8116 8117**Example** 8118 8119```ts 8120// xxx.ets 8121import { webview } from '@kit.ArkWeb'; 8122import { image } from '@kit.ImageKit'; 8123import { BusinessError } from '@kit.BasicServicesKit'; 8124 8125@Entry 8126@Component 8127struct Example{ 8128 controller: webview.WebviewController = new webview.WebviewController(); 8129 8130 @State imagePixelMap: image.PixelMap | undefined = undefined; 8131 8132 build(){ 8133 Column(){ 8134 Button ("Screenshot") 8135 .onClick(()=>{ 8136 try { 8137 let surfaceId = this.controller.getSurfaceId(); 8138 console.log("surfaceId: " + surfaceId); 8139 if(surfaceId.length != 0) { 8140 let region:image.Region = { x: 0, y: 0, size: { height: 800, width: 1000}} 8141 this.imagePixelMap = image.createPixelMapFromSurfaceSync(surfaceId, region) 8142 } 8143 } catch (error) { 8144 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8145 } 8146 }) 8147 Image(this.imagePixelMap) 8148 .height(100) 8149 Web({src: 'www.example.com', controller: this.controller}) 8150 } 8151 } 8152} 8153``` 8154 8155### setUrlTrustList<sup>12+</sup> 8156 8157setUrlTrustList(urlTrustList: string): void 8158 8159Sets the URL trustlist of the web page. Only URLs in the trustlist can be loaded or redirected. Otherwise, the URL is blocked and an alarm page is displayed. 8160 8161**System capability**: SystemCapability.Web.Webview.Core 8162 8163**Parameters** 8164 8165| Name | Type | Mandatory| Description | 8166| ------- | ------ | ---- | :-------------------- | 8167| urlTrustList | string | Yes | URL trustlist, which is configured in JSON format. The maximum size is 10 MB.<br>**setUrlTrustList()** is used in overwrite mode. If it is called for multiple times, the latest setting overwrites the previous setting.<br>If this parameter is left blank, the trustlist is canceled and access to all URLs is allowed.<br>Example in JSON format:<br>{<br> "UrlPermissionList": [<br> {<br> "scheme": "https",<br> "host": "www\.example1.com",<br> "port": 443,<br> "path": "pathA/pathB"<br> },<br> {<br> "scheme": "http",<br> "host": "www\.example2.com",<br> "port": 80,<br> "path": "test1/test2/test3"<br> }<br> ]<br>} | 8168 8169**Parameters in JSON format**: 8170| Name | Type| Mandatory| Description | 8171| -------- | -------- | ---- | ------------------------- | 8172| scheme | string | No| Optional parameter. The supported protocols are HTTP and HTTPS.| 8173| host | string | Yes| Mandatory parameter. The URL is permitted only when its host field is the same as the rule field. Multiple rules for the same host at the same time are allowed.| 8174| port | number | No| Optional parameter.| 8175| path | string | No| Optional parameter. This field uses prefix matching. For example, in **pathA/pathB/pathC**, **pathA/pathB/** is specified, and all level-3 directories such as **pathC** can be accessed, which must be a complete directory name or file name. Partial matching is not allowed.| 8176 8177**Error codes** 8178 8179For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8180 8181| ID| Error Message | 8182| -------- | ------------------------------------------------------------ | 8183| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified.2. Parameter string is too long.3. Parameter verification failed. | 8184| 17100001 | Init error. The WebviewController must be associated with a Web component. | 8185 8186**Example** 8187 ```ts 8188 // xxx.ets 8189 import { webview } from '@kit.ArkWeb'; 8190 import { BusinessError } from '@kit.BasicServicesKit'; 8191 8192 @Entry 8193 @Component 8194 struct WebComponent { 8195 controller: webview.WebviewController = new webview.WebviewController(); 8196 urltrustList: string = "{\"UrlPermissionList\":[{\"scheme\":\"http\", \"host\":\"trust.example.com\", \"port\":80, \"path\":\"test\"}]}" 8197 8198 build() { 8199 Column() { 8200 Button('Setting the trustlist') 8201 .onClick(() => { 8202 try { 8203 // Set a trustlist to allow access only to trust web pages. 8204 this.controller.setUrlTrustList(this.urltrustList); 8205 } catch (error) { 8206 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8207 } 8208 }) 8209 Button('Cancel the trustlist.') 8210 .onClick(() => { 8211 try { 8212 // Input an empty string to setUrlTrustList() to disable the trustlist, and all URLs can be accessed. 8213 this.controller.setUrlTrustList(""); 8214 } catch (error) { 8215 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8216 } 8217 }) 8218 Button('Access the trust web') 8219 .onClick(() => { 8220 try { 8221 // The trustlist is enabled and trust web pages can be accessed. 8222 this.controller.loadUrl('http://trust.example.com/test'); 8223 } catch (error) { 8224 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8225 } 8226 }) 8227 Button('Access the untrust web') 8228 .onClick(() => { 8229 try { 8230 // The trustlist is enabled that untrust web pages cannot be accessed and an error page is displayed. 8231 this.controller.loadUrl('http://untrust.example.com/test'); 8232 } catch (error) { 8233 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8234 } 8235 }) 8236 Web({ src: 'http://untrust.example.com/test', controller: this.controller }).onControllerAttached(() => { 8237 try { 8238 // Set the trustlist using onControllerAttached() to enable the trustlist before the URL starts to be loaded. The untrusted web page cannot be accessed, and an error page is displayed. 8239 this.controller.setUrlTrustList(this.urltrustList); 8240 } catch (error) { 8241 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8242 } 8243 }) 8244 } 8245 } 8246 } 8247 ``` 8248 8249### setPathAllowingUniversalAccess<sup>12+</sup> 8250 8251setPathAllowingUniversalAccess(pathList: Array\<string\>): void 8252 8253Sets a path list. When a file protocol accesses resources in the path of list, it can access the local files across domains. In addition, when a path list is set, the file protocol can access only the resources in the path list. The behavior of [fileAccess](ts-basic-components-web.md#fileAccess) will be overwritten by that of this API. The paths in the list must be any of the following: 8254 82551. The path of subdirectory of the application file directory. (The application file directory is obtained using [Context.filesDir](../apis-ability-kit/js-apis-inner-application-context.md#context) in the Ability Kit.) For example: 8256 8257* /data/storage/el2/base/files/example 8258* /data/storage/el2/base/haps/entry/files/example 8259 82602. The path of application resource directory or its subdirectory. (The application resource directory is obtained from [Context.resourceDir](../apis-ability-kit/js-apis-inner-application-context.md#context) in the Ability Kit.) For example: 8261 8262* /data/storage/el1/bundle/entry/resource/resfile 8263* /data/storage/el1/bundle/entry/resource/resfile/example 8264 8265If a path in the list is not any of the preceding paths, error code 401 is reported and the path list fails to be set. When the path list is set to empty, the accessible files for the file protocol are subject to the behavior of the [fileAccess](ts-basic-components-web.md#fileAccess). 8266 8267**System capability**: SystemCapability.Web.Webview.Core 8268 8269**Parameters** 8270 8271| Name | Type| Mandatory| Description | 8272| -------- | -------- | ---- | ------------------------- | 8273| pathList | Array\<string\> | Yes | The path list.| 8274 8275**Error codes** 8276 8277For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8278 8279| ID| Error Message | 8280| -------- | ------------------------ | 8281| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Parameter string is too long. 3.Parameter verification failed. | 8282| 17100001 | Init error. The WebviewController must be associated with a Web component. | 8283 8284**Example** 8285 8286```ts 8287// xxx.ets 8288import { webview } from '@kit.ArkWeb'; 8289import { BusinessError } from '@kit.BasicServicesKit'; 8290 8291@Entry 8292@Component 8293struct WebComponent { 8294 controller: WebviewController = new webview.WebviewController(); 8295 8296 build() { 8297 Row() { 8298 Web({ src: "", controller: this.controller }) 8299 .onControllerAttached(() => { 8300 try { 8301 // Set the list of paths that can be accessed across domains. 8302 this.controller.setPathAllowingUniversalAccess([ 8303 getContext().resourceDir, 8304 getContext().filesDir + "/example" 8305 ]) 8306 this.controller.loadUrl("file://" + getContext().resourceDir + "/index.html") 8307 } catch (error) { 8308 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8309 } 8310 }) 8311 .javaScriptAccess(true) 8312 .fileAccess(true) 8313 .domStorageAccess(true) 8314 } 8315 } 8316} 8317 8318``` 8319 8320Load the HTML file, which is located in the application resource directory **resource/resfile/index.html**. 8321```html 8322<!-- index.html --> 8323<!DOCTYPE html> 8324<html lang="en"> 8325 8326<head> 8327 <meta charset="utf-8"> 8328 <title>Demo</title> 8329 <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, viewport-fit=cover"> 8330 <script> 8331 function getFile() { 8332 var file = "file:///data/storage/el1/bundle/entry/resources/resfile/js/script.js"; 8333 var xmlHttpReq = new XMLHttpRequest(); 8334 xmlHttpReq.onreadystatechange = function(){ 8335 console.log("readyState:" + xmlHttpReq.readyState); 8336 console.log("status:" + xmlHttpReq.status); 8337 if(xmlHttpReq.readyState == 4){ 8338 if (xmlHttpReq.status == 200) { 8339 // If the path list is set on the eTS, resources can be obtained. 8340 const element = document.getElementById('text'); 8341 element.textContent = "load " + file + " success"; 8342 } else { 8343 // If the path list is not set on the eTS, a CORS error is triggered. 8344 const element = document.getElementById('text'); 8345 element.textContent = "load " + file + " failed"; 8346 } 8347 } 8348 } 8349 xmlHttpReq.open("GET", file); 8350 xmlHttpReq.send(null); 8351 } 8352 8353 </script> 8354</head> 8355 8356<body> 8357<div class="page"> 8358 <button id="example" onclick="getFile()">stealFile</button> 8359</div> 8360<div id="text"></div> 8361</body> 8362 8363</html> 8364``` 8365 8366In HTML, the file protocol is used to access the local JS file through XMLHttpRequest. The JS file is stored in **resource/resfile/js/script.js**. 8367<!--code_no_check--> 8368```javascript 8369const body = document.body; 8370const element = document.createElement('div'); 8371element.textContent = 'success'; 8372body.appendChild(element); 8373``` 8374 8375### enableBackForwardCache<sup>12+</sup> 8376 8377static enableBackForwardCache(features: BackForwardCacheSupportedFeatures): void 8378 8379Enables the back-forward cache of a **Web** component. You can specify whether to add a specific page to the back-forward cache. 8380 8381This API must be called before [initializeWebEngine()](#initializewebengine) initializes the kernel. 8382 8383**System capability**: SystemCapability.Web.Webview.Core 8384 8385**Parameters** 8386 8387| Name | Type | Mandatory | Description | 8388| ---------------| ------- | ---- | ------------- | 8389| features | [BackForwardCacheSupportedFeatures](#backforwardcachesupportedfeatures12) | Yes | Features of the pages, which allow them to be added to the back-forward cache.| 8390 8391**Example** 8392 8393```ts 8394// EntryAbility.ets 8395import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 8396import { hilog } from '@kit.PerformanceAnalysisKit'; 8397import { window } from '@kit.ArkUI'; 8398import { webview } from '@kit.ArkWeb'; 8399 8400export default class EntryAbility extends UIAbility { 8401 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 8402 let features = new webview.BackForwardCacheSupportedFeatures(); 8403 features.nativeEmbed = true; 8404 features.mediaTakeOver = true; 8405 // If a page uses the same-layer rendering and takes over media playback at the same time, you need to set the values of **nativeEmbed** and **mediaTakeOver** to **true** to add the page to the back-forward cache. 8406 8407 webview.WebviewController.enableBackForwardCache(features); 8408 webview.WebviewController.initializeWebEngine(); 8409 AppStorage.setOrCreate("abilityWant", want); 8410 } 8411} 8412``` 8413 8414### setBackForwardCacheOptions<sup>12+</sup> 8415 8416setBackForwardCacheOptions(options: BackForwardCacheOptions): void 8417 8418Sets the back-forward cache options of the **Web** component. 8419 8420**System capability**: SystemCapability.Web.Webview.Core 8421 8422**Parameters** 8423 8424| Name | Type | Mandatory | Description | 8425| ---------------| ------- | ---- | ------------- | 8426| options | [BackForwardCacheOptions](#backforwardcacheoptions12) | Yes | Options to control the back-forward cache of the **Web** component.| 8427 8428**Error codes** 8429 8430For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8431 8432| ID| Error Message | 8433| -------- | ------------------------------------------------------------ | 8434| 17100001 | Init error. The WebviewController must be associated with a Web component. | 8435 8436**Example** 8437 8438```ts 8439// xxx.ts 8440import { webview } from '@kit.ArkWeb'; 8441 8442@Entry 8443@Component 8444struct Index { 8445 controller: webview.WebviewController = new webview.WebviewController(); 8446 8447 build() { 8448 Column() { 8449 Row() { 8450 Button("Add options").onClick((event: ClickEvent) => { 8451 let options = new webview.BackForwardCacheOptions(); 8452 options.size = 3; 8453 options.timeToLive = 10; 8454 this.controller.setBackForwardCacheOptions(options); 8455 }) 8456 Button("Backward").onClick((event: ClickEvent) => { 8457 this.controller.backward(); 8458 }) 8459 Button("Forward").onClick((event: ClickEvent) => { 8460 this.controller.forward(); 8461 }) 8462 } 8463 Web({ src: "https://www.example.com", controller: this.controller }) 8464 } 8465 .height('100%') 8466 .width('100%') 8467 } 8468} 8469``` 8470 8471### trimMemoryByPressureLevel<sup>14+</sup> 8472 8473trimMemoryByPressureLevel(level: number): void 8474 8475Clears the cache occupied by **Web** component based on the specified memory pressure level. 8476 8477**System capability**: SystemCapability.Web.Webview.Core 8478 8479**Parameters** 8480 8481| Name | Type | Mandatory| Description | 8482| ------- | ------ | ---- | :-------------------- | 8483| level | [PressureLevel](#pressurelevel14) | Yes| Pressure level of the memory to be cleared.| 8484 8485**Error codes** 8486 8487For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8488 8489| ID| Error Message | 8490| -------- | ------------------------------------------------------------ | 8491| 401 | Invalid input parameter.Possible causes: 1. Mandatory parameters are left unspecified.2. Parameter string is too long.3. Parameter verification failed. | 8492 8493**Example** 8494```ts 8495// xxx.ets 8496import { webview } from '@kit.ArkWeb'; 8497 8498@Entry 8499@Component 8500struct WebComponent { 8501 controller: WebviewController = new webview.WebviewController(); 8502 build() { 8503 Column() { 8504 Row() { 8505 Button('trim_Memory') 8506 .onClick(() => { 8507 try { 8508 // Set the current memory pressure level to moderate and release a small amount of memory. 8509 webview.WebviewController.trimMemoryByPressureLevel( 8510 webview.PressureLevel.MEMORY_PRESSURE_LEVEL_MODERATE); 8511 } catch (error) { 8512 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8513 } 8514 }) 8515 }.height('10%') 8516 Web({ src: 'www.example.com', controller: this.controller }) 8517 } 8518 } 8519} 8520``` 8521 8522## WebCookieManager 8523 8524Implements a **WebCookieManager** instance to manage behavior of cookies in **Web** components. All **Web** components in an application share a **WebCookieManager** instance. 8525 8526### getCookie<sup>(deprecated)</sup> 8527 8528static getCookie(url: string): string 8529 8530Obtains the cookie corresponding to the specified URL. 8531 8532> **NOTE** 8533> 8534> This API is supported since API version 9 and deprecated since API version 11. You are advised to use [fetchCookieSync](#fetchcookiesync11) instead. 8535 8536**System capability**: SystemCapability.Web.Webview.Core 8537 8538**Parameters** 8539 8540| Name| Type | Mandatory| Description | 8541| ------ | ------ | ---- | :------------------------ | 8542| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 8543 8544**Return value** 8545 8546| Type | Description | 8547| ------ | ------------------------- | 8548| string | Cookie value corresponding to the specified URL.| 8549 8550**Error codes** 8551 8552For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8553 8554| ID| Error Message | 8555| -------- | ------------------------------------------------------ | 8556| 17100002 | Invalid url. | 8557| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 8558 8559**Example** 8560 8561```ts 8562// xxx.ets 8563import { webview } from '@kit.ArkWeb'; 8564import { BusinessError } from '@kit.BasicServicesKit'; 8565 8566@Entry 8567@Component 8568struct WebComponent { 8569 controller: webview.WebviewController = new webview.WebviewController(); 8570 8571 build() { 8572 Column() { 8573 Button('getCookie') 8574 .onClick(() => { 8575 try { 8576 let value = webview.WebCookieManager.getCookie('https://www.example.com'); 8577 console.log("value: " + value); 8578 } catch (error) { 8579 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8580 } 8581 }) 8582 Web({ src: 'www.example.com', controller: this.controller }) 8583 } 8584 } 8585} 8586``` 8587 8588### fetchCookieSync<sup>11+</sup> 8589 8590static fetchCookieSync(url: string, incognito?: boolean): string 8591 8592Obtains the cookie value corresponding to the specified URL. 8593 8594**System capability**: SystemCapability.Web.Webview.Core 8595 8596**Parameters** 8597 8598| Name| Type | Mandatory| Description | 8599| ------ | ------ | ---- | :------------------------ | 8600| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 8601| 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.| 8602 8603**Return value** 8604 8605| Type | Description | 8606| ------ | ------------------------- | 8607| string | Cookie value corresponding to the specified URL.| 8608 8609**Error codes** 8610 8611For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8612 8613| ID| Error Message | 8614| -------- | ------------------------------------------------------ | 8615| 17100002 | Invalid url. | 8616| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 8617 8618**Example** 8619 8620```ts 8621// xxx.ets 8622import { webview } from '@kit.ArkWeb'; 8623import { BusinessError } from '@kit.BasicServicesKit'; 8624 8625@Entry 8626@Component 8627struct WebComponent { 8628 controller: webview.WebviewController = new webview.WebviewController(); 8629 8630 build() { 8631 Column() { 8632 Button('fetchCookieSync') 8633 .onClick(() => { 8634 try { 8635 let value = webview.WebCookieManager.fetchCookieSync('https://www.example.com'); 8636 console.log("fetchCookieSync cookie = " + value); 8637 } catch (error) { 8638 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8639 } 8640 }) 8641 Web({ src: 'www.example.com', controller: this.controller }) 8642 } 8643 } 8644} 8645``` 8646 8647### fetchCookie<sup>11+</sup> 8648 8649static fetchCookie(url: string, callback: AsyncCallback\<string>): void 8650 8651Obtains the cookie value of a specified URL. This API uses an asynchronous callback to return the result. 8652 8653**System capability**: SystemCapability.Web.Webview.Core 8654 8655**Parameters** 8656 8657| Name| Type | Mandatory| Description | 8658| ------ | ------ | ---- | :------------------------ | 8659| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 8660| callback | AsyncCallback\<string> | Yes| Callback used to return the result.| 8661 8662**Error codes** 8663 8664For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8665 8666| ID| Error Message | 8667| -------- | ------------------------------------------------------ | 8668| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 8669| 17100002 | Invalid url. | 8670 8671**Example** 8672 8673```ts 8674// xxx.ets 8675import { webview } from '@kit.ArkWeb'; 8676import { BusinessError } from '@kit.BasicServicesKit'; 8677 8678@Entry 8679@Component 8680struct WebComponent { 8681 controller: webview.WebviewController = new webview.WebviewController(); 8682 8683 build() { 8684 Column() { 8685 Button('fetchCookie') 8686 .onClick(() => { 8687 try { 8688 webview.WebCookieManager.fetchCookie('https://www.example.com', (error, cookie) => { 8689 if (error) { 8690 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8691 return; 8692 } 8693 if (cookie) { 8694 console.log('fetchCookie cookie = ' + cookie); 8695 } 8696 }) 8697 } catch (error) { 8698 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8699 } 8700 }) 8701 Web({ src: 'www.example.com', controller: this.controller }) 8702 } 8703 } 8704} 8705``` 8706 8707### fetchCookie<sup>11+</sup> 8708 8709static fetchCookie(url: string): Promise\<string> 8710 8711Obtains the cookie value of a specified URL. This API uses a promise to return the result. 8712 8713**System capability**: SystemCapability.Web.Webview.Core 8714 8715**Parameters** 8716 8717| Name| Type | Mandatory| Description | 8718| ------ | ------ | ---- | :------------------------ | 8719| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 8720 8721**Return value** 8722 8723| Type | Description | 8724| ------ | ------------------------- | 8725| Promise\<string> | Promise used to return the result.| 8726 8727**Error codes** 8728 8729For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8730 8731| ID| Error Message | 8732| -------- | ------------------------------------------------------ | 8733| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 8734| 17100002 | Invalid url. | 8735 8736**Example** 8737 8738```ts 8739// xxx.ets 8740import { webview } from '@kit.ArkWeb'; 8741import { BusinessError } from '@kit.BasicServicesKit'; 8742 8743@Entry 8744@Component 8745struct WebComponent { 8746 controller: webview.WebviewController = new webview.WebviewController(); 8747 8748 build() { 8749 Column() { 8750 Button('fetchCookie') 8751 .onClick(() => { 8752 try { 8753 webview.WebCookieManager.fetchCookie('https://www.example.com') 8754 .then(cookie => { 8755 console.log("fetchCookie cookie = " + cookie); 8756 }) 8757 .catch((error: BusinessError) => { 8758 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 8759 }) 8760 } catch (error) { 8761 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8762 } 8763 }) 8764 Web({ src: 'www.example.com', controller: this.controller }) 8765 } 8766 } 8767} 8768``` 8769 8770 8771### setCookie<sup>(deprecated)</sup> 8772 8773static setCookie(url: string, value: string): void 8774 8775Sets a cookie for the specified URL. 8776 8777> **NOTE** 8778> 8779> 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. 8780 8781**System capability**: SystemCapability.Web.Webview.Core 8782 8783**Parameters** 8784 8785| Name| Type | Mandatory| Description | 8786| ------ | ------ | ---- | :------------------------ | 8787| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 8788| value | string | Yes | Cookie value to set. | 8789 8790**Error codes** 8791 8792For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8793 8794| ID| Error Message | 8795| -------- | ------------------------------------------------------ | 8796| 17100002 | Invalid url. | 8797| 17100005 | Invalid cookie value. | 8798| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 8799 8800**Example** 8801 8802```ts 8803// xxx.ets 8804import { webview } from '@kit.ArkWeb'; 8805import { BusinessError } from '@kit.BasicServicesKit'; 8806 8807@Entry 8808@Component 8809struct WebComponent { 8810 controller: webview.WebviewController = new webview.WebviewController(); 8811 8812 build() { 8813 Column() { 8814 Button('setCookie') 8815 .onClick(() => { 8816 try { 8817 webview.WebCookieManager.setCookie('https://www.example.com', 'a=b'); 8818 } catch (error) { 8819 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8820 } 8821 }) 8822 Web({ src: 'www.example.com', controller: this.controller }) 8823 } 8824 } 8825} 8826``` 8827 8828### configCookieSync<sup>11+</sup> 8829 8830static configCookieSync(url: string, value: string, incognito?: boolean): void 8831 8832Sets the cookie value for the specified URL. 8833 8834> **NOTE** 8835> 8836>You can set **url** in **configCookieSync** to a domain name so that the cookie is attached to the requests on the page. 8837 8838>It is recommended that cookie syncing be completed before the **Web** component is loaded. 8839 8840**System capability**: SystemCapability.Web.Webview.Core 8841 8842**Parameters** 8843 8844| Name| Type | Mandatory| Description | 8845| ------ | ------ | ---- | :------------------------ | 8846| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 8847| value | string | Yes | Cookie value to set. | 8848| incognito | boolean | No | Whether to set the cookies in incognito mode. The value **true** means to set the cookies in incognito mode, and **false** means the opposite.| 8849 8850**Error codes** 8851 8852For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8853 8854| ID| Error Message | 8855| -------- | ------------------------------------------------------ | 8856| 17100002 | Invalid url. | 8857| 17100005 | Invalid cookie value. | 8858| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 8859 8860**Example** 8861 8862```ts 8863// xxx.ets 8864import { webview } from '@kit.ArkWeb'; 8865import { BusinessError } from '@kit.BasicServicesKit'; 8866 8867@Entry 8868@Component 8869struct WebComponent { 8870 controller: webview.WebviewController = new webview.WebviewController(); 8871 8872 build() { 8873 Column() { 8874 Button('configCookieSync') 8875 .onClick(() => { 8876 try { 8877 // Only a single cookie value can be set. 8878 webview.WebCookieManager.configCookieSync('https://www.example.com', 'a=b'); 8879 } catch (error) { 8880 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8881 } 8882 }) 8883 Web({ src: 'www.example.com', controller: this.controller }) 8884 } 8885 } 8886} 8887``` 8888 8889### configCookie<sup>11+</sup> 8890 8891static configCookie(url: string, value: string, callback: AsyncCallback\<void>): void 8892 8893Sets the value of a single cookie for a specified URL. This API uses an asynchronous callback to return the result. 8894 8895**System capability**: SystemCapability.Web.Webview.Core 8896 8897**Parameters** 8898 8899| Name| Type | Mandatory| Description | 8900| ------ | ------ | ---- | :------------------------ | 8901| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 8902| value | string | Yes | Cookie value to set. | 8903| callback | AsyncCallback\<void> | Yes| Callback used to return the result.| 8904 8905**Error codes** 8906 8907For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8908 8909| ID| Error Message | 8910| -------- | ------------------------------------------------------ | 8911| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 8912| 17100002 | Invalid url. | 8913| 17100005 | Invalid cookie value. | 8914 8915**Example** 8916 8917```ts 8918// xxx.ets 8919import { webview } from '@kit.ArkWeb'; 8920import { BusinessError } from '@kit.BasicServicesKit'; 8921 8922@Entry 8923@Component 8924struct WebComponent { 8925 controller: webview.WebviewController = new webview.WebviewController(); 8926 8927 build() { 8928 Column() { 8929 Button('configCookie') 8930 .onClick(() => { 8931 try { 8932 webview.WebCookieManager.configCookie('https://www.example.com', "a=b", (error) => { 8933 if (error) { 8934 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8935 } 8936 }) 8937 } catch (error) { 8938 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8939 } 8940 }) 8941 Web({ src: 'www.example.com', controller: this.controller }) 8942 } 8943 } 8944} 8945``` 8946 8947### configCookie<sup>11+</sup> 8948 8949static configCookie(url: string, value: string): Promise\<void> 8950 8951Sets the value of a single cookie for a specified URL. This API uses a promise to return the result. 8952 8953**System capability**: SystemCapability.Web.Webview.Core 8954 8955**Parameters** 8956 8957| Name| Type | Mandatory| Description | 8958| ------ | ------ | ---- | :------------------------ | 8959| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 8960| value | string | Yes | Cookie value to set. | 8961 8962**Return value** 8963 8964| Type | Description | 8965| ------ | ------------------------- | 8966| Promise\<void> | Promise used to return the result.| 8967 8968**Error codes** 8969 8970For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8971 8972| ID| Error Message | 8973| -------- | ------------------------------------------------------ | 8974| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 8975| 17100002 | Invalid url. | 8976| 17100005 | Invalid cookie value. | 8977 8978**Example** 8979 8980```ts 8981// xxx.ets 8982import { webview } from '@kit.ArkWeb'; 8983import { BusinessError } from '@kit.BasicServicesKit'; 8984 8985@Entry 8986@Component 8987struct WebComponent { 8988 controller: webview.WebviewController = new webview.WebviewController(); 8989 8990 build() { 8991 Column() { 8992 Button('configCookie') 8993 .onClick(() => { 8994 try { 8995 webview.WebCookieManager.configCookie('https://www.example.com', 'a=b') 8996 .then(() => { 8997 console.log('configCookie success!'); 8998 }) 8999 .catch((error: BusinessError) => { 9000 console.log('error: ' + JSON.stringify(error)); 9001 }) 9002 } catch (error) { 9003 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9004 } 9005 }) 9006 Web({ src: 'www.example.com', controller: this.controller }) 9007 } 9008 } 9009} 9010``` 9011 9012### saveCookieAsync 9013 9014static saveCookieAsync(callback: AsyncCallback\<void>): void 9015 9016Saves the cookies in the memory to the drive. This API uses an asynchronous callback to return the result. 9017 9018**System capability**: SystemCapability.Web.Webview.Core 9019 9020**Parameters** 9021 9022| Name | Type | Mandatory| Description | 9023| -------- | ---------------------- | ---- | :------------------------------------------------- | 9024| callback | AsyncCallback\<void> | Yes | Callback used to return whether the cookies are successfully saved.| 9025 9026**Error codes** 9027 9028For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9029 9030| ID| Error Message | 9031| -------- | ------------------------------------------------------ | 9032| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 9033 9034**Example** 9035 9036```ts 9037// xxx.ets 9038import { webview } from '@kit.ArkWeb'; 9039import { BusinessError } from '@kit.BasicServicesKit'; 9040 9041@Entry 9042@Component 9043struct WebComponent { 9044 controller: webview.WebviewController = new webview.WebviewController(); 9045 9046 build() { 9047 Column() { 9048 Button('saveCookieAsync') 9049 .onClick(() => { 9050 try { 9051 webview.WebCookieManager.saveCookieAsync((error) => { 9052 if (error) { 9053 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9054 } 9055 }) 9056 } catch (error) { 9057 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9058 } 9059 }) 9060 Web({ src: 'www.example.com', controller: this.controller }) 9061 } 9062 } 9063} 9064``` 9065 9066### saveCookieAsync 9067 9068static saveCookieAsync(): Promise\<void> 9069 9070Saves the cookies in the memory to the drive. This API uses a promise to return the result. 9071 9072**System capability**: SystemCapability.Web.Webview.Core 9073 9074**Return value** 9075 9076| Type | Description | 9077| ---------------- | ----------------------------------------- | 9078| Promise\<void> | Promise used to return the operation result.| 9079 9080**Error codes** 9081 9082For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9083 9084| ID| Error Message | 9085| -------- | ------------------------------------------------------ | 9086| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 9087 9088**Example** 9089 9090```ts 9091// xxx.ets 9092import { webview } from '@kit.ArkWeb'; 9093import { BusinessError } from '@kit.BasicServicesKit'; 9094 9095@Entry 9096@Component 9097struct WebComponent { 9098 controller: webview.WebviewController = new webview.WebviewController(); 9099 9100 build() { 9101 Column() { 9102 Button('saveCookieAsync') 9103 .onClick(() => { 9104 try { 9105 webview.WebCookieManager.saveCookieAsync() 9106 .then(() => { 9107 console.log("saveCookieAsyncCallback success!"); 9108 }) 9109 .catch((error: BusinessError) => { 9110 console.error("error: " + error); 9111 }); 9112 } catch (error) { 9113 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9114 } 9115 }) 9116 Web({ src: 'www.example.com', controller: this.controller }) 9117 } 9118 } 9119} 9120``` 9121 9122### putAcceptCookieEnabled 9123 9124static putAcceptCookieEnabled(accept: boolean): void 9125 9126Sets whether the **WebCookieManager** instance has the permission to send and receive cookies. 9127 9128**System capability**: SystemCapability.Web.Webview.Core 9129 9130**Parameters** 9131 9132| Name| Type | Mandatory| Description | 9133| ------ | ------- | ---- | :----------------------------------- | 9134| accept | boolean | Yes | Whether the **WebCookieManager** instance has the permission to send and receive cookies.<br>Default value: **true**| 9135 9136**Error codes** 9137 9138For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9139 9140| ID| Error Message | 9141| -------- | ------------------------------------------------------ | 9142| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 9143 9144**Example** 9145 9146```ts 9147// xxx.ets 9148import { webview } from '@kit.ArkWeb'; 9149import { BusinessError } from '@kit.BasicServicesKit'; 9150 9151@Entry 9152@Component 9153struct WebComponent { 9154 controller: webview.WebviewController = new webview.WebviewController(); 9155 9156 build() { 9157 Column() { 9158 Button('putAcceptCookieEnabled') 9159 .onClick(() => { 9160 try { 9161 webview.WebCookieManager.putAcceptCookieEnabled(false); 9162 } catch (error) { 9163 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9164 } 9165 }) 9166 Web({ src: 'www.example.com', controller: this.controller }) 9167 } 9168 } 9169} 9170``` 9171 9172### isCookieAllowed 9173 9174static isCookieAllowed(): boolean 9175 9176Checks whether the **WebCookieManager** instance has the permission to send and receive cookies. 9177 9178**System capability**: SystemCapability.Web.Webview.Core 9179 9180**Return value** 9181 9182| Type | Description | 9183| ------- | -------------------------------- | 9184| boolean | Whether the **WebCookieManager** instance has the permission to send and receive cookies. The default value is **true**.| 9185 9186**Example** 9187 9188```ts 9189// xxx.ets 9190import { webview } from '@kit.ArkWeb'; 9191 9192@Entry 9193@Component 9194struct WebComponent { 9195 controller: webview.WebviewController = new webview.WebviewController(); 9196 9197 build() { 9198 Column() { 9199 Button('isCookieAllowed') 9200 .onClick(() => { 9201 let result = webview.WebCookieManager.isCookieAllowed(); 9202 console.log("result: " + result); 9203 }) 9204 Web({ src: 'www.example.com', controller: this.controller }) 9205 } 9206 } 9207} 9208``` 9209 9210### putAcceptThirdPartyCookieEnabled 9211 9212static putAcceptThirdPartyCookieEnabled(accept: boolean): void 9213 9214Sets whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. 9215 9216**System capability**: SystemCapability.Web.Webview.Core 9217 9218**Parameters** 9219 9220| Name| Type | Mandatory| Description | 9221| ------ | ------- | ---- | :----------------------------------------- | 9222| accept | boolean | Yes | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies.<br>Default value: **false**| 9223 9224**Error codes** 9225 9226For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9227 9228| ID| Error Message | 9229| -------- | ------------------------------------------------------ | 9230| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 9231 9232**Example** 9233 9234```ts 9235// xxx.ets 9236import { webview } from '@kit.ArkWeb'; 9237import { BusinessError } from '@kit.BasicServicesKit'; 9238 9239@Entry 9240@Component 9241struct WebComponent { 9242 controller: webview.WebviewController = new webview.WebviewController(); 9243 9244 build() { 9245 Column() { 9246 Button('putAcceptThirdPartyCookieEnabled') 9247 .onClick(() => { 9248 try { 9249 webview.WebCookieManager.putAcceptThirdPartyCookieEnabled(false); 9250 } catch (error) { 9251 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9252 } 9253 }) 9254 Web({ src: 'www.example.com', controller: this.controller }) 9255 } 9256 } 9257} 9258``` 9259 9260### isThirdPartyCookieAllowed 9261 9262static isThirdPartyCookieAllowed(): boolean 9263 9264Checks whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. 9265 9266**System capability**: SystemCapability.Web.Webview.Core 9267 9268**Return value** 9269 9270| Type | Description | 9271| ------- | -------------------------------------- | 9272| boolean | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. The default value is **false**.| 9273 9274**Example** 9275 9276```ts 9277// xxx.ets 9278import { webview } from '@kit.ArkWeb'; 9279 9280@Entry 9281@Component 9282struct WebComponent { 9283 controller: webview.WebviewController = new webview.WebviewController(); 9284 9285 build() { 9286 Column() { 9287 Button('isThirdPartyCookieAllowed') 9288 .onClick(() => { 9289 let result = webview.WebCookieManager.isThirdPartyCookieAllowed(); 9290 console.log("result: " + result); 9291 }) 9292 Web({ src: 'www.example.com', controller: this.controller }) 9293 } 9294 } 9295} 9296``` 9297 9298### existCookie 9299 9300static existCookie(incognito?: boolean): boolean 9301 9302Checks whether cookies exist. 9303 9304**System capability**: SystemCapability.Web.Webview.Core 9305 9306**Parameters** 9307 9308| Name| Type | Mandatory| Description | 9309| ------ | ------- | ---- | :----------------------------------------- | 9310| 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.| 9311 9312**Return value** 9313 9314| Type | Description | 9315| ------- | -------------------------------------- | 9316| boolean | Whether cookies exist. The value **true** means that cookies exist, and **false** means the opposite.| 9317 9318**Example** 9319 9320```ts 9321// xxx.ets 9322import { webview } from '@kit.ArkWeb'; 9323 9324@Entry 9325@Component 9326struct WebComponent { 9327 controller: webview.WebviewController = new webview.WebviewController(); 9328 9329 build() { 9330 Column() { 9331 Button('existCookie') 9332 .onClick(() => { 9333 let result = webview.WebCookieManager.existCookie(); 9334 console.log("result: " + result); 9335 }) 9336 Web({ src: 'www.example.com', controller: this.controller }) 9337 } 9338 } 9339} 9340``` 9341 9342### deleteEntireCookie<sup>(deprecated)</sup> 9343 9344static deleteEntireCookie(): void 9345 9346Deletes all cookies. 9347 9348> **NOTE** 9349> 9350> This API is supported since API version 9 and deprecated since API version 11. You are advised to use [clearAllCookiesSync](#clearallcookiessync11) instead. 9351 9352**System capability**: SystemCapability.Web.Webview.Core 9353 9354**Example** 9355 9356```ts 9357// xxx.ets 9358import { webview } from '@kit.ArkWeb'; 9359 9360@Entry 9361@Component 9362struct WebComponent { 9363 controller: webview.WebviewController = new webview.WebviewController(); 9364 9365 build() { 9366 Column() { 9367 Button('deleteEntireCookie') 9368 .onClick(() => { 9369 webview.WebCookieManager.deleteEntireCookie(); 9370 }) 9371 Web({ src: 'www.example.com', controller: this.controller }) 9372 } 9373 } 9374} 9375``` 9376 9377### clearAllCookiesSync<sup>11+</sup> 9378 9379static clearAllCookiesSync(incognito?: boolean): void 9380 9381Deletes all cookies. 9382 9383**System capability**: SystemCapability.Web.Webview.Core 9384 9385**Parameters** 9386 9387| Name| Type | Mandatory| Description | 9388| ------ | ------- | ---- | :----------------------------------------- | 9389| 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.| 9390 9391**Example** 9392 9393```ts 9394// xxx.ets 9395import { webview } from '@kit.ArkWeb'; 9396 9397@Entry 9398@Component 9399struct WebComponent { 9400 controller: webview.WebviewController = new webview.WebviewController(); 9401 9402 build() { 9403 Column() { 9404 Button('clearAllCookiesSync') 9405 .onClick(() => { 9406 webview.WebCookieManager.clearAllCookiesSync(); 9407 }) 9408 Web({ src: 'www.example.com', controller: this.controller }) 9409 } 9410 } 9411} 9412``` 9413 9414### clearAllCookies<sup>11+</sup> 9415 9416static clearAllCookies(callback: AsyncCallback\<void>): void 9417 9418Clears all cookies. This API uses an asynchronous callback to return the result. 9419 9420**System capability**: SystemCapability.Web.Webview.Core 9421 9422**Parameters** 9423 9424| Name | Type | Mandatory| Description | 9425| -------- | ---------------------- | ---- | :------------------------------------------------- | 9426| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 9427 9428**Error codes** 9429 9430For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9431 9432| ID| Error Message | 9433| -------- | ------------------------------------------------------ | 9434| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9435 9436**Example** 9437 9438```ts 9439// xxx.ets 9440import { webview } from '@kit.ArkWeb'; 9441import { BusinessError } from '@kit.BasicServicesKit'; 9442 9443@Entry 9444@Component 9445struct WebComponent { 9446 controller: webview.WebviewController = new webview.WebviewController(); 9447 9448 build() { 9449 Column() { 9450 Button('clearAllCookies') 9451 .onClick(() => { 9452 try { 9453 webview.WebCookieManager.clearAllCookies((error) => { 9454 if (error) { 9455 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9456 } 9457 }) 9458 } catch (error) { 9459 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9460 } 9461 }) 9462 Web({ src: 'www.example.com', controller: this.controller }) 9463 } 9464 } 9465} 9466``` 9467 9468### clearAllCookies<sup>11+</sup> 9469 9470static clearAllCookies(): Promise\<void> 9471 9472Clears all cookies. This API uses a promise to return the result. 9473 9474**System capability**: SystemCapability.Web.Webview.Core 9475 9476**Return value** 9477 9478| Type | Description | 9479| ---------------- | ----------------------------------------- | 9480| Promise\<void> | Promise used to return the result.| 9481 9482**Error codes** 9483 9484For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9485 9486| ID| Error Message | 9487| -------- | ------------------------------------------------------ | 9488| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 9489 9490**Example** 9491 9492```ts 9493// xxx.ets 9494import { webview } from '@kit.ArkWeb'; 9495import { BusinessError } from '@kit.BasicServicesKit'; 9496 9497@Entry 9498@Component 9499struct WebComponent { 9500 controller: webview.WebviewController = new webview.WebviewController(); 9501 9502 build() { 9503 Column() { 9504 Button('clearAllCookies') 9505 .onClick(() => { 9506 try { 9507 webview.WebCookieManager.clearAllCookies() 9508 .then(() => { 9509 console.log("clearAllCookies success!"); 9510 }) 9511 .catch((error: BusinessError) => { 9512 console.error("error: " + error); 9513 }); 9514 } catch (error) { 9515 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9516 } 9517 }) 9518 Web({ src: 'www.example.com', controller: this.controller }) 9519 } 9520 } 9521} 9522``` 9523 9524### deleteSessionCookie<sup>(deprecated)</sup> 9525 9526static deleteSessionCookie(): void 9527 9528Deletes all session cookies. 9529 9530> **NOTE** 9531> 9532> This API is supported since API version 9 and deprecated since API version 11. You are advised to use [clearSessionCookiesync](#clearsessioncookiesync11) instead. 9533 9534**System capability**: SystemCapability.Web.Webview.Core 9535 9536**Example** 9537 9538```ts 9539// xxx.ets 9540import { webview } from '@kit.ArkWeb'; 9541 9542@Entry 9543@Component 9544struct WebComponent { 9545 controller: webview.WebviewController = new webview.WebviewController(); 9546 9547 build() { 9548 Column() { 9549 Button('deleteSessionCookie') 9550 .onClick(() => { 9551 webview.WebCookieManager.deleteSessionCookie(); 9552 }) 9553 Web({ src: 'www.example.com', controller: this.controller }) 9554 } 9555 } 9556} 9557``` 9558 9559### clearSessionCookieSync<sup>11+</sup> 9560 9561static clearSessionCookieSync(): void 9562 9563Deletes all session cookies. 9564 9565**System capability**: SystemCapability.Web.Webview.Core 9566 9567**Example** 9568 9569```ts 9570// xxx.ets 9571import { webview } from '@kit.ArkWeb'; 9572 9573@Entry 9574@Component 9575struct WebComponent { 9576 controller: webview.WebviewController = new webview.WebviewController(); 9577 9578 build() { 9579 Column() { 9580 Button('clearSessionCookieSync') 9581 .onClick(() => { 9582 webview.WebCookieManager.clearSessionCookieSync(); 9583 }) 9584 Web({ src: 'www.example.com', controller: this.controller }) 9585 } 9586 } 9587} 9588``` 9589 9590### clearSessionCookie<sup>11+</sup> 9591 9592static clearSessionCookie(callback: AsyncCallback\<void>): void 9593 9594Clears all session cookies. This API uses an asynchronous callback to return the result. 9595 9596**System capability**: SystemCapability.Web.Webview.Core 9597 9598**Parameters** 9599 9600| Name | Type | Mandatory| Description | 9601| -------- | ---------------------- | ---- | :------------------------------------------------- | 9602| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 9603 9604**Error codes** 9605 9606For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9607 9608| ID| Error Message | 9609| -------- | ------------------------------------------------------ | 9610| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9611 9612**Example** 9613 9614```ts 9615// xxx.ets 9616import { webview } from '@kit.ArkWeb'; 9617import { BusinessError } from '@kit.BasicServicesKit'; 9618 9619@Entry 9620@Component 9621struct WebComponent { 9622 controller: webview.WebviewController = new webview.WebviewController(); 9623 9624 build() { 9625 Column() { 9626 Button('clearSessionCookie') 9627 .onClick(() => { 9628 try { 9629 webview.WebCookieManager.clearSessionCookie((error) => { 9630 if (error) { 9631 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9632 } 9633 }) 9634 } catch (error) { 9635 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9636 } 9637 }) 9638 Web({ src: 'www.example.com', controller: this.controller }) 9639 } 9640 } 9641} 9642``` 9643 9644### clearSessionCookie<sup>11+</sup> 9645 9646static clearSessionCookie(): Promise\<void> 9647 9648Clears all session cookies. This API uses a promise to return the result. 9649 9650**System capability**: SystemCapability.Web.Webview.Core 9651 9652**Return value** 9653 9654| Type | Description | 9655| ---------------- | ----------------------------------------- | 9656| Promise\<void> | Promise used to return the result.| 9657 9658**Error codes** 9659 9660For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9661 9662| ID| Error Message | 9663| -------- | ------------------------------------------------------ | 9664| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 9665 9666**Example** 9667 9668```ts 9669// xxx.ets 9670import { webview } from '@kit.ArkWeb'; 9671import { BusinessError } from '@kit.BasicServicesKit'; 9672 9673@Entry 9674@Component 9675struct WebComponent { 9676 controller: webview.WebviewController = new webview.WebviewController(); 9677 9678 build() { 9679 Column() { 9680 Button('clearSessionCookie') 9681 .onClick(() => { 9682 try { 9683 webview.WebCookieManager.clearSessionCookie() 9684 .then(() => { 9685 console.log("clearSessionCookie success!"); 9686 }) 9687 .catch((error: BusinessError) => { 9688 console.error("error: " + error); 9689 }); 9690 } catch (error) { 9691 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9692 } 9693 }) 9694 Web({ src: 'www.example.com', controller: this.controller }) 9695 } 9696 } 9697} 9698``` 9699 9700## WebStorage 9701 9702Implements a **WebStorage** object to manage the Web SQL database and HTML5 Web Storage APIs. All **Web** components in an application share a **WebStorage** object. 9703 9704> **NOTE** 9705> 9706> You must load the **Web** component before calling the APIs in **WebStorage**. 9707 9708### deleteOrigin 9709 9710static deleteOrigin(origin: string): void 9711 9712Deletes all data in the specified origin. 9713 9714**System capability**: SystemCapability.Web.Webview.Core 9715 9716**Parameters** 9717 9718| Name| Type | Mandatory| Description | 9719| ------ | ------ | ---- | ------------------------ | 9720| origin | string | Yes | Index of the origin, which is obtained through [getOrigins](#getorigins).| 9721 9722**Error codes** 9723 9724For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9725 9726| ID| Error Message | 9727| -------- | ------------------------------------------------------ | 9728| 17100011 | Invalid origin. | 9729| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 9730 9731**Example** 9732 9733```ts 9734// xxx.ets 9735import { webview } from '@kit.ArkWeb'; 9736import { BusinessError } from '@kit.BasicServicesKit'; 9737 9738@Entry 9739@Component 9740struct WebComponent { 9741 controller: webview.WebviewController = new webview.WebviewController(); 9742 origin: string = "resource://rawfile/"; 9743 9744 build() { 9745 Column() { 9746 Button('deleteOrigin') 9747 .onClick(() => { 9748 try { 9749 webview.WebStorage.deleteOrigin(this.origin); 9750 } catch (error) { 9751 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9752 } 9753 9754 }) 9755 Web({ src: $rawfile('index.html'), controller: this.controller }) 9756 .databaseAccess(true) 9757 } 9758 } 9759} 9760``` 9761 9762HTML file to be loaded: 9763 ```html 9764 <!-- index.html --> 9765 <!DOCTYPE html> 9766 <html> 9767 <head> 9768 <meta charset="UTF-8"> 9769 <title>test</title> 9770 <script type="text/javascript"> 9771 9772 var db = openDatabase('mydb','1.0','Test DB',2 * 1024 * 1024); 9773 var msg; 9774 9775 db.transaction(function(tx){ 9776 tx.executeSql('INSERT INTO LOGS (id,log) VALUES(1,"test1")'); 9777 tx.executeSql('INSERT INTO LOGS (id,log) VALUES(2,"test2")'); 9778 msg = '<p>Data table created, with two data records inserted.</p>'; 9779 9780 document.querySelector('#status').innerHTML = msg; 9781 }); 9782 9783 db.transaction(function(tx){ 9784 tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) { 9785 var len = results.rows.length,i; 9786 msg = "<p>Number of records: " + len + "</p>"; 9787 9788 document.querySelector('#status').innerHTML += msg; 9789 9790 for(i = 0; i < len; i++){ 9791 msg = "<p><b>" + results.rows.item(i).log + "</b></p>"; 9792 9793 document.querySelector('#status').innerHTML += msg; 9794 } 9795 },null); 9796 }); 9797 9798 </script> 9799 </head> 9800 <body> 9801 <div id="status" name="status">Status</div> 9802 </body> 9803 </html> 9804 ``` 9805 9806### getOrigins 9807 9808static getOrigins(callback: AsyncCallback\<Array\<WebStorageOrigin>>): void 9809 9810Obtains information about all origins that are currently using the Web SQL Database. This API uses an asynchronous callback to return the result. 9811 9812**System capability**: SystemCapability.Web.Webview.Core 9813 9814**Parameters** 9815 9816| Name | Type | Mandatory| Description | 9817| -------- | -------------------------------------- | ---- | ------------------------------------------------------ | 9818| callback | AsyncCallback\<Array\<[WebStorageOrigin](#webstorageorigin)>> | Yes | Callback used to return the information about the origins. For details, see [WebStorageOrigin](#webstorageorigin).| 9819 9820**Error codes** 9821 9822For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9823 9824| ID| Error Message | 9825| -------- | ------------------------------------------------------ | 9826| 17100012 | Invalid web storage origin. | 9827| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 9828 9829**Example** 9830 9831```ts 9832// xxx.ets 9833import { webview } from '@kit.ArkWeb'; 9834import { BusinessError } from '@kit.BasicServicesKit'; 9835 9836@Entry 9837@Component 9838struct WebComponent { 9839 controller: webview.WebviewController = new webview.WebviewController(); 9840 9841 build() { 9842 Column() { 9843 Button('getOrigins') 9844 .onClick(() => { 9845 try { 9846 webview.WebStorage.getOrigins((error, origins) => { 9847 if (error) { 9848 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9849 return; 9850 } 9851 for (let i = 0; i < origins.length; i++) { 9852 console.log('origin: ' + origins[i].origin); 9853 console.log('usage: ' + origins[i].usage); 9854 console.log('quota: ' + origins[i].quota); 9855 } 9856 }) 9857 } catch (error) { 9858 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9859 } 9860 9861 }) 9862 Web({ src: $rawfile('index.html'), controller: this.controller }) 9863 .databaseAccess(true) 9864 } 9865 } 9866} 9867``` 9868 9869For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 9870 9871### getOrigins 9872 9873static getOrigins(): Promise\<Array\<WebStorageOrigin>> 9874 9875Obtains information about all origins that are currently using the Web SQL Database. This API uses a promise to return the result. 9876 9877**System capability**: SystemCapability.Web.Webview.Core 9878 9879**Return value** 9880 9881| Type | Description | 9882| -------------------------------- | ------------------------------------------------------------ | 9883| Promise\<Array\<[WebStorageOrigin](#webstorageorigin)>> | Promise used to return the information about the origins. For details, see [WebStorageOrigin](#webstorageorigin).| 9884 9885**Error codes** 9886 9887For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9888 9889| ID| Error Message | 9890| -------- | ------------------------------------------------------ | 9891| 17100012 | Invalid web storage origin. | 9892| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 9893 9894**Example** 9895 9896```ts 9897// xxx.ets 9898import { webview } from '@kit.ArkWeb'; 9899import { BusinessError } from '@kit.BasicServicesKit'; 9900 9901@Entry 9902@Component 9903struct WebComponent { 9904 controller: webview.WebviewController = new webview.WebviewController(); 9905 9906 build() { 9907 Column() { 9908 Button('getOrigins') 9909 .onClick(() => { 9910 try { 9911 webview.WebStorage.getOrigins() 9912 .then(origins => { 9913 for (let i = 0; i < origins.length; i++) { 9914 console.log('origin: ' + origins[i].origin); 9915 console.log('usage: ' + origins[i].usage); 9916 console.log('quota: ' + origins[i].quota); 9917 } 9918 }) 9919 .catch((e: BusinessError) => { 9920 console.log('error: ' + JSON.stringify(e)); 9921 }) 9922 } catch (error) { 9923 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9924 } 9925 9926 }) 9927 Web({ src: $rawfile('index.html'), controller: this.controller }) 9928 .databaseAccess(true) 9929 } 9930 } 9931} 9932``` 9933 9934For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 9935 9936### getOriginQuota 9937 9938static getOriginQuota(origin: string, callback: AsyncCallback\<number>): void 9939 9940Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. 9941 9942**System capability**: SystemCapability.Web.Webview.Core 9943 9944**Parameters** 9945 9946| Name | Type | Mandatory| Description | 9947| -------- | --------------------- | ---- | ------------------ | 9948| origin | string | Yes | Index of the origin.| 9949| callback | AsyncCallback\<number> | Yes | Storage quota of the origin. | 9950 9951**Error codes** 9952 9953For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9954 9955| ID| Error Message | 9956| -------- | ------------------------------------------------------ | 9957| 17100011 | Invalid origin. | 9958| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 9959 9960**Example** 9961 9962```ts 9963// xxx.ets 9964import { webview } from '@kit.ArkWeb'; 9965import { BusinessError } from '@kit.BasicServicesKit'; 9966 9967@Entry 9968@Component 9969struct WebComponent { 9970 controller: webview.WebviewController = new webview.WebviewController(); 9971 origin: string = "resource://rawfile/"; 9972 9973 build() { 9974 Column() { 9975 Button('getOriginQuota') 9976 .onClick(() => { 9977 try { 9978 webview.WebStorage.getOriginQuota(this.origin, (error, quota) => { 9979 if (error) { 9980 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9981 return; 9982 } 9983 console.log('quota: ' + quota); 9984 }) 9985 } catch (error) { 9986 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9987 } 9988 9989 }) 9990 Web({ src: $rawfile('index.html'), controller: this.controller }) 9991 .databaseAccess(true) 9992 } 9993 } 9994} 9995``` 9996 9997For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 9998 9999### getOriginQuota 10000 10001static getOriginQuota(origin: string): Promise\<number> 10002 10003Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. 10004 10005**System capability**: SystemCapability.Web.Webview.Core 10006 10007**Parameters** 10008 10009| Name| Type | Mandatory| Description | 10010| ------ | ------ | ---- | ------------------ | 10011| origin | string | Yes | Index of the origin.| 10012 10013**Return value** 10014 10015| Type | Description | 10016| --------------- | --------------------------------------- | 10017| Promise\<number> | Promise used to return the storage quota of the origin.| 10018 10019**Error codes** 10020 10021For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10022 10023| ID| Error Message | 10024| -------- | ------------------------------------------------------ | 10025| 17100011 | Invalid origin. | 10026| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10027 10028**Example** 10029 10030```ts 10031// xxx.ets 10032import { webview } from '@kit.ArkWeb'; 10033import { BusinessError } from '@kit.BasicServicesKit'; 10034 10035@Entry 10036@Component 10037struct WebComponent { 10038 controller: webview.WebviewController = new webview.WebviewController(); 10039 origin: string = "resource://rawfile/"; 10040 10041 build() { 10042 Column() { 10043 Button('getOriginQuota') 10044 .onClick(() => { 10045 try { 10046 webview.WebStorage.getOriginQuota(this.origin) 10047 .then(quota => { 10048 console.log('quota: ' + quota); 10049 }) 10050 .catch((e: BusinessError) => { 10051 console.log('error: ' + JSON.stringify(e)); 10052 }) 10053 } catch (error) { 10054 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10055 } 10056 10057 }) 10058 Web({ src: $rawfile('index.html'), controller: this.controller }) 10059 .databaseAccess(true) 10060 } 10061 } 10062} 10063``` 10064 10065For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 10066 10067### getOriginUsage 10068 10069static getOriginUsage(origin: string, callback: AsyncCallback\<number>): void 10070 10071Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. 10072 10073**System capability**: SystemCapability.Web.Webview.Core 10074 10075**Parameters** 10076 10077| Name | Type | Mandatory| Description | 10078| -------- | --------------------- | ---- | ------------------ | 10079| origin | string | Yes | Index of the origin.| 10080| callback | AsyncCallback\<number> | Yes | Storage usage of the origin. | 10081 10082**Error codes** 10083 10084For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10085 10086| ID| Error Message | 10087| -------- | ------------------------------------------------------ | 10088| 17100011 | Invalid origin. | 10089| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10090 10091**Example** 10092 10093```ts 10094// xxx.ets 10095import { webview } from '@kit.ArkWeb'; 10096import { BusinessError } from '@kit.BasicServicesKit'; 10097 10098@Entry 10099@Component 10100struct WebComponent { 10101 controller: webview.WebviewController = new webview.WebviewController(); 10102 origin: string = "resource://rawfile/"; 10103 10104 build() { 10105 Column() { 10106 Button('getOriginUsage') 10107 .onClick(() => { 10108 try { 10109 webview.WebStorage.getOriginUsage(this.origin, (error, usage) => { 10110 if (error) { 10111 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10112 return; 10113 } 10114 console.log('usage: ' + usage); 10115 }) 10116 } catch (error) { 10117 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10118 } 10119 10120 }) 10121 Web({ src: $rawfile('index.html'), controller: this.controller }) 10122 .databaseAccess(true) 10123 } 10124 } 10125} 10126``` 10127 10128For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 10129 10130### getOriginUsage 10131 10132static getOriginUsage(origin: string): Promise\<number> 10133 10134Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. 10135 10136**System capability**: SystemCapability.Web.Webview.Core 10137 10138**Parameters** 10139 10140| Name| Type | Mandatory| Description | 10141| ------ | ------ | ---- | ------------------ | 10142| origin | string | Yes | Index of the origin.| 10143 10144**Return value** 10145 10146| Type | Description | 10147| --------------- | ------------------------------------- | 10148| Promise\<number> | Promise used to return the storage usage of the origin.| 10149 10150**Error codes** 10151 10152For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10153 10154| ID| Error Message | 10155| -------- | ----------------------------------------------------- | 10156| 17100011 | Invalid origin. | 10157| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10158 10159**Example** 10160 10161```ts 10162// xxx.ets 10163import { webview } from '@kit.ArkWeb'; 10164import { BusinessError } from '@kit.BasicServicesKit'; 10165 10166@Entry 10167@Component 10168struct WebComponent { 10169 controller: webview.WebviewController = new webview.WebviewController(); 10170 origin: string = "resource://rawfile/"; 10171 10172 build() { 10173 Column() { 10174 Button('getOriginUsage') 10175 .onClick(() => { 10176 try { 10177 webview.WebStorage.getOriginUsage(this.origin) 10178 .then(usage => { 10179 console.log('usage: ' + usage); 10180 }).catch((e: BusinessError) => { 10181 console.error('error: ' + JSON.stringify(e)); 10182 }) 10183 } catch (error) { 10184 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10185 } 10186 }) 10187 Web({ src: $rawfile('index.html'), controller: this.controller }) 10188 .databaseAccess(true) 10189 } 10190 } 10191} 10192``` 10193 10194For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 10195 10196### deleteAllData 10197 10198static deleteAllData(incognito?: boolean): void 10199 10200Deletes all data in the Web SQL Database. 10201 10202**System capability**: SystemCapability.Web.Webview.Core 10203 10204**Parameters** 10205 10206| Name| Type | Mandatory| Description | 10207| ------ | ------ | ---- | ------------------ | 10208| 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.| 10209 10210**Example** 10211 10212```ts 10213// xxx.ets 10214import { webview } from '@kit.ArkWeb'; 10215import { BusinessError } from '@kit.BasicServicesKit'; 10216 10217@Entry 10218@Component 10219struct WebComponent { 10220 controller: webview.WebviewController = new webview.WebviewController(); 10221 10222 build() { 10223 Column() { 10224 Button('deleteAllData') 10225 .onClick(() => { 10226 try { 10227 webview.WebStorage.deleteAllData(); 10228 } catch (error) { 10229 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10230 } 10231 }) 10232 Web({ src: $rawfile('index.html'), controller: this.controller }) 10233 .databaseAccess(true) 10234 } 10235 } 10236} 10237``` 10238 10239For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 10240 10241## WebDataBase 10242 10243Implements a **WebDataBase** object. 10244 10245> **NOTE** 10246> 10247> You must load the **Web** component before calling the APIs in **WebDataBase**. 10248 10249### getHttpAuthCredentials 10250 10251static getHttpAuthCredentials(host: string, realm: string): Array\<string> 10252 10253Retrieves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. 10254 10255**System capability**: SystemCapability.Web.Webview.Core 10256 10257**Parameters** 10258 10259| Name| Type | Mandatory| Description | 10260| ------ | ------ | ---- | ---------------------------- | 10261| host | string | Yes | Host to which HTTP authentication credentials apply.| 10262| realm | string | Yes | Realm to which HTTP authentication credentials apply. | 10263 10264**Return value** 10265 10266| Type | Description | 10267| ----- | -------------------------------------------- | 10268| Array\<string> | Returns the array of the matching user names and passwords if the operation is successful; returns an empty array otherwise.| 10269 10270**Error codes** 10271 10272For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10273 10274| ID| Error Message | 10275| -------- | ------------------------------------------------------ | 10276| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10277 10278**Example** 10279 10280```ts 10281// xxx.ets 10282import { webview } from '@kit.ArkWeb'; 10283import { BusinessError } from '@kit.BasicServicesKit'; 10284 10285@Entry 10286@Component 10287struct WebComponent { 10288 controller: webview.WebviewController = new webview.WebviewController(); 10289 host: string = "www.spincast.org"; 10290 realm: string = "protected example"; 10291 username_password: string[] = []; 10292 10293 build() { 10294 Column() { 10295 Button('getHttpAuthCredentials') 10296 .onClick(() => { 10297 try { 10298 this.username_password = webview.WebDataBase.getHttpAuthCredentials(this.host, this.realm); 10299 console.log('num: ' + this.username_password.length); 10300 } catch (error) { 10301 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10302 } 10303 }) 10304 Web({ src: 'www.example.com', controller: this.controller }) 10305 } 10306 } 10307} 10308``` 10309 10310### saveHttpAuthCredentials 10311 10312static saveHttpAuthCredentials(host: string, realm: string, username: string, password: string): void 10313 10314Saves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. 10315 10316**System capability**: SystemCapability.Web.Webview.Core 10317 10318**Parameters** 10319 10320| Name | Type | Mandatory| Description | 10321| -------- | ------ | ---- | ---------------------------- | 10322| host | string | Yes | Host to which HTTP authentication credentials apply.| 10323| realm | string | Yes | Realm to which HTTP authentication credentials apply. | 10324| username | string | Yes | User name. | 10325| password | string | Yes | Password. | 10326 10327**Error codes** 10328 10329For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10330 10331| ID| Error Message | 10332| -------- | ------------------------------------------------------ | 10333| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10334 10335**Example** 10336 10337```ts 10338// xxx.ets 10339import { webview } from '@kit.ArkWeb'; 10340import { BusinessError } from '@kit.BasicServicesKit'; 10341 10342@Entry 10343@Component 10344struct WebComponent { 10345 controller: webview.WebviewController = new webview.WebviewController(); 10346 host: string = "www.spincast.org"; 10347 realm: string = "protected example"; 10348 10349 build() { 10350 Column() { 10351 Button('saveHttpAuthCredentials') 10352 .onClick(() => { 10353 try { 10354 webview.WebDataBase.saveHttpAuthCredentials(this.host, this.realm, "Stromgol", "Laroche"); 10355 } catch (error) { 10356 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10357 } 10358 }) 10359 Web({ src: 'www.example.com', controller: this.controller }) 10360 } 10361 } 10362} 10363``` 10364 10365### existHttpAuthCredentials 10366 10367static existHttpAuthCredentials(): boolean 10368 10369Checks whether any saved HTTP authentication credentials exist. This API returns the result synchronously. 10370 10371**System capability**: SystemCapability.Web.Webview.Core 10372 10373**Return value** 10374 10375| Type | Description | 10376| ------- | ------------------------------------------------------------ | 10377| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist; returns **false** otherwise.| 10378 10379**Example** 10380 10381```ts 10382// xxx.ets 10383import { webview } from '@kit.ArkWeb'; 10384import { BusinessError } from '@kit.BasicServicesKit'; 10385 10386@Entry 10387@Component 10388struct WebComponent { 10389 controller: webview.WebviewController = new webview.WebviewController(); 10390 10391 build() { 10392 Column() { 10393 Button('existHttpAuthCredentials') 10394 .onClick(() => { 10395 try { 10396 let result = webview.WebDataBase.existHttpAuthCredentials(); 10397 } catch (error) { 10398 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10399 } 10400 }) 10401 Web({ src: 'www.example.com', controller: this.controller }) 10402 } 10403 } 10404} 10405``` 10406 10407### deleteHttpAuthCredentials 10408 10409static deleteHttpAuthCredentials(): void 10410 10411Deletes all HTTP authentication credentials saved in the cache. This API returns the result synchronously. 10412 10413**System capability**: SystemCapability.Web.Webview.Core 10414 10415**Example** 10416 10417```ts 10418// xxx.ets 10419import { webview } from '@kit.ArkWeb'; 10420import { BusinessError } from '@kit.BasicServicesKit'; 10421 10422@Entry 10423@Component 10424struct WebComponent { 10425 controller: webview.WebviewController = new webview.WebviewController(); 10426 10427 build() { 10428 Column() { 10429 Button('deleteHttpAuthCredentials') 10430 .onClick(() => { 10431 try { 10432 webview.WebDataBase.deleteHttpAuthCredentials(); 10433 } catch (error) { 10434 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10435 } 10436 }) 10437 Web({ src: 'www.example.com', controller: this.controller }) 10438 } 10439 } 10440} 10441``` 10442 10443## GeolocationPermissions 10444 10445Implements a **GeolocationPermissions** object. 10446 10447> **NOTE** 10448> 10449> You must load the **Web** component before calling the APIs in **GeolocationPermissions**. 10450 10451### Required Permissions 10452 10453**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)](../apis-location-kit/js-apis-geolocation.md). 10454 10455### allowGeolocation 10456 10457static allowGeolocation(origin: string, incognito?: boolean): void 10458 10459Allows the specified origin to use the geolocation information. 10460 10461**System capability**: SystemCapability.Web.Webview.Core 10462 10463**Parameters** 10464 10465| Name| Type | Mandatory| Description | 10466| ------ | ------ | ---- | ------------------ | 10467| origin | string | Yes |Index of the origin.| 10468| 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.| 10469 10470**Error codes** 10471 10472For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10473 10474| ID| Error Message | 10475| -------- | ------------------------------------------------------ | 10476| 17100011 | Invalid origin. | 10477| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10478 10479**Example** 10480 10481```ts 10482// xxx.ets 10483import { webview } from '@kit.ArkWeb'; 10484import { BusinessError } from '@kit.BasicServicesKit'; 10485 10486@Entry 10487@Component 10488struct WebComponent { 10489 controller: webview.WebviewController = new webview.WebviewController(); 10490 origin: string = "file:///"; 10491 10492 build() { 10493 Column() { 10494 Button('allowGeolocation') 10495 .onClick(() => { 10496 try { 10497 webview.GeolocationPermissions.allowGeolocation(this.origin); 10498 } catch (error) { 10499 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10500 } 10501 }) 10502 Web({ src: 'www.example.com', controller: this.controller }) 10503 } 10504 } 10505} 10506``` 10507 10508### deleteGeolocation 10509 10510static deleteGeolocation(origin: string, incognito?: boolean): void 10511 10512Clears the geolocation permission status of a specified origin. 10513 10514**System capability**: SystemCapability.Web.Webview.Core 10515 10516**Parameters** 10517 10518| Name| Type | Mandatory| Description | 10519| ------ | ------ | ---- | ------------------ | 10520| origin | string | Yes | Index of the origin.| 10521| 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.| 10522 10523**Error codes** 10524 10525For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10526 10527| ID| Error Message | 10528| -------- | ------------------------------------------------------ | 10529| 17100011 | Invalid origin. | 10530| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10531 10532**Example** 10533 10534```ts 10535// xxx.ets 10536import { webview } from '@kit.ArkWeb'; 10537import { BusinessError } from '@kit.BasicServicesKit'; 10538 10539@Entry 10540@Component 10541struct WebComponent { 10542 controller: webview.WebviewController = new webview.WebviewController(); 10543 origin: string = "file:///"; 10544 10545 build() { 10546 Column() { 10547 Button('deleteGeolocation') 10548 .onClick(() => { 10549 try { 10550 webview.GeolocationPermissions.deleteGeolocation(this.origin); 10551 } catch (error) { 10552 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10553 } 10554 }) 10555 Web({ src: 'www.example.com', controller: this.controller }) 10556 } 10557 } 10558} 10559``` 10560 10561### getAccessibleGeolocation 10562 10563static getAccessibleGeolocation(origin: string, callback: AsyncCallback\<boolean>, incognito?: boolean): void 10564 10565Obtains the geolocation permission status of the specified origin. This API uses an asynchronous callback to return the result. 10566 10567**System capability**: SystemCapability.Web.Webview.Core 10568 10569**Parameters** 10570 10571| Name | Type | Mandatory| Description | 10572| -------- | ---------------------- | ---- | ------------------------------------------------------------ | 10573| origin | string | Yes | Index of the origin. | 10574| 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.| 10575| 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.| 10576 10577**Error codes** 10578 10579For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10580 10581| ID| Error Message | 10582| -------- | ------------------------------------------------------ | 10583| 17100011 | Invalid origin. | 10584| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10585 10586**Example** 10587 10588```ts 10589// xxx.ets 10590import { webview } from '@kit.ArkWeb'; 10591import { BusinessError } from '@kit.BasicServicesKit'; 10592 10593@Entry 10594@Component 10595struct WebComponent { 10596 controller: webview.WebviewController = new webview.WebviewController(); 10597 origin: string = "file:///"; 10598 10599 build() { 10600 Column() { 10601 Button('getAccessibleGeolocation') 10602 .onClick(() => { 10603 try { 10604 webview.GeolocationPermissions.getAccessibleGeolocation(this.origin, (error, result) => { 10605 if (error) { 10606 console.error(`getAccessibleGeolocationAsync error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10607 return; 10608 } 10609 console.log('getAccessibleGeolocationAsync result: ' + result); 10610 }); 10611 } catch (error) { 10612 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10613 } 10614 }) 10615 Web({ src: 'www.example.com', controller: this.controller }) 10616 } 10617 } 10618} 10619``` 10620 10621### getAccessibleGeolocation 10622 10623static getAccessibleGeolocation(origin: string, incognito?: boolean): Promise\<boolean> 10624 10625Obtains the geolocation permission status of the specified origin. This API uses a promise to return the result. 10626 10627**System capability**: SystemCapability.Web.Webview.Core 10628 10629**Parameters** 10630 10631| Name| Type| Mandatory| Description | 10632| ------ | -------- | ---- | -------------------- | 10633| origin | string | Yes | Index of the origin.| 10634| 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.| 10635 10636**Return value** 10637 10638| Type | Description | 10639| ---------------- | ------------------------------------------------------------ | 10640| 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.| 10641 10642**Error codes** 10643 10644For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10645 10646| ID| Error Message | 10647| -------- | ------------------------------------------------------ | 10648| 17100011 | Invalid origin. | 10649| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10650 10651**Example** 10652 10653```ts 10654// xxx.ets 10655import { webview } from '@kit.ArkWeb'; 10656import { BusinessError } from '@kit.BasicServicesKit'; 10657 10658@Entry 10659@Component 10660struct WebComponent { 10661 controller: webview.WebviewController = new webview.WebviewController(); 10662 origin: string = "file:///"; 10663 10664 build() { 10665 Column() { 10666 Button('getAccessibleGeolocation') 10667 .onClick(() => { 10668 try { 10669 webview.GeolocationPermissions.getAccessibleGeolocation(this.origin) 10670 .then(result => { 10671 console.log('getAccessibleGeolocationPromise result: ' + result); 10672 }).catch((error: BusinessError) => { 10673 console.error(`getAccessibleGeolocationPromise error, ErrorCode: ${error.code}, Message: ${error.message}`); 10674 }); 10675 } catch (error) { 10676 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10677 } 10678 }) 10679 Web({ src: 'www.example.com', controller: this.controller }) 10680 } 10681 } 10682} 10683``` 10684 10685### getStoredGeolocation 10686 10687static getStoredGeolocation(callback: AsyncCallback\<Array\<string>>, incognito?: boolean): void 10688 10689Obtains the geolocation permission status of all origins. This API uses an asynchronous callback to return the result. 10690 10691**System capability**: SystemCapability.Web.Webview.Core 10692 10693**Parameters** 10694 10695| Name | Type | Mandatory| Description | 10696| -------- | ---------------------------- | ---- | ---------------------------------------- | 10697| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return the geolocation permission status of all origins.| 10698| 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.| 10699 10700**Error codes** 10701 10702For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10703 10704| ID| Error Message | 10705| -------- | ------------------------------------------------------ | 10706| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10707 10708**Example** 10709 10710```ts 10711// xxx.ets 10712import { webview } from '@kit.ArkWeb'; 10713import { BusinessError } from '@kit.BasicServicesKit'; 10714 10715@Entry 10716@Component 10717struct WebComponent { 10718 controller: webview.WebviewController = new webview.WebviewController(); 10719 10720 build() { 10721 Column() { 10722 Button('getStoredGeolocation') 10723 .onClick(() => { 10724 try { 10725 webview.GeolocationPermissions.getStoredGeolocation((error, origins) => { 10726 if (error) { 10727 console.error(`getStoredGeolocationAsync error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10728 return; 10729 } 10730 let origins_str: string = origins.join(); 10731 console.log('getStoredGeolocationAsync origins: ' + origins_str); 10732 }); 10733 } catch (error) { 10734 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10735 } 10736 }) 10737 Web({ src: 'www.example.com', controller: this.controller }) 10738 } 10739 } 10740} 10741``` 10742 10743### getStoredGeolocation 10744 10745static getStoredGeolocation(incognito?: boolean): Promise\<Array\<string>> 10746 10747Obtains the geolocation permission status of all origins. This API uses a promise to return the result. 10748 10749**System capability**: SystemCapability.Web.Webview.Core 10750 10751**Parameters** 10752 10753| Name | Type | Mandatory| Description | 10754| -------- | ---------------------------- | ---- | ---------------------------------------- | 10755| 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.| 10756 10757**Return value** 10758 10759| Type | Description | 10760| ---------------------- | --------------------------------------------------------- | 10761| Promise\<Array\<string>> | Promise used to return the geolocation permission status of all origins.| 10762 10763**Error codes** 10764 10765For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10766 10767| ID| Error Message | 10768| -------- | ------------------------------------------------------ | 10769| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10770 10771**Example** 10772 10773```ts 10774// xxx.ets 10775import { webview } from '@kit.ArkWeb'; 10776import { BusinessError } from '@kit.BasicServicesKit'; 10777 10778@Entry 10779@Component 10780struct WebComponent { 10781 controller: webview.WebviewController = new webview.WebviewController(); 10782 10783 build() { 10784 Column() { 10785 Button('getStoredGeolocation') 10786 .onClick(() => { 10787 try { 10788 webview.GeolocationPermissions.getStoredGeolocation() 10789 .then(origins => { 10790 let origins_str: string = origins.join(); 10791 console.log('getStoredGeolocationPromise origins: ' + origins_str); 10792 }).catch((error: BusinessError) => { 10793 console.error(`getStoredGeolocationPromise error, ErrorCode: ${error.code}, Message: ${error.message}`); 10794 }); 10795 } catch (error) { 10796 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10797 } 10798 }) 10799 Web({ src: 'www.example.com', controller: this.controller }) 10800 } 10801 } 10802} 10803``` 10804 10805### deleteAllGeolocation 10806 10807static deleteAllGeolocation(incognito?: boolean): void 10808 10809Clears the geolocation permission status of all sources. 10810 10811**System capability**: SystemCapability.Web.Webview.Core 10812 10813**Parameters** 10814 10815| Name | Type | Mandatory| Description | 10816| -------- | ---------------------------- | ---- | ---------------------------------------- | 10817| 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.| 10818 10819**Example** 10820 10821```ts 10822// xxx.ets 10823import { webview } from '@kit.ArkWeb'; 10824import { BusinessError } from '@kit.BasicServicesKit'; 10825 10826@Entry 10827@Component 10828struct WebComponent { 10829 controller: webview.WebviewController = new webview.WebviewController(); 10830 10831 build() { 10832 Column() { 10833 Button('deleteAllGeolocation') 10834 .onClick(() => { 10835 try { 10836 webview.GeolocationPermissions.deleteAllGeolocation(); 10837 } catch (error) { 10838 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10839 } 10840 }) 10841 Web({ src: 'www.example.com', controller: this.controller }) 10842 } 10843 } 10844} 10845``` 10846## WebHeader 10847 10848Describes the request/response header returned by the **Web** component. 10849 10850**System capability**: SystemCapability.Web.Webview.Core 10851 10852| Name | Type | Readable| Writable|Description | 10853| ----------- | ------ | -----|------|------------------- | 10854| headerKey | string | Yes| Yes| Key of the request/response header. | 10855| headerValue | string | Yes| Yes| Value of the request/response header.| 10856 10857## RequestInfo<sup>12+</sup> 10858 10859Describes the information about the resource request sent by the **Web** component. 10860 10861**System capability**: SystemCapability.Web.Webview.Core 10862 10863| Name | Type | Readable| Writable|Description | 10864| ---------| ------ | -----|------|-------- | 10865| url | string | Yes| Yes| URL of the request. | 10866| method | string | Yes| Yes| Method of the request. | 10867| formData | string | Yes| Yes| Form data in the request body.| 10868 10869## WebHitTestType 10870 10871The [getHitTest](#gethittest) API is used to indicate a cursor node. 10872 10873**System capability**: SystemCapability.Web.Webview.Core 10874 10875| Name | Value| Description | 10876| ------------- | -- |----------------------------------------- | 10877| EditText | 0 |Editable area. | 10878| Email | 1 |Email address. | 10879| HttpAnchor | 2 |Hyperlink, where **src** is **http**. | 10880| HttpAnchorImg | 3 |Image with a hyperlink, where **src** is http + HTML::img.| 10881| Img | 4 |HTML::img tag. | 10882| Map | 5 |Geographical address. | 10883| Phone | 6 |Phone number. | 10884| Unknown | 7 |Unknown content. | 10885 10886## SecurityLevel<sup>11+</sup> 10887 10888Defines the security level of the web page. 10889 10890**System capability**: SystemCapability.Web.Webview.Core 10891 10892| Name | Value| Description | 10893| ------------- | -- |----------------------------------------- | 10894| 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.| 10895| SECURE | 1 |The web page is secure, using the HTTPS protocol and a trusted certificate.| 10896| 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.| 10897| 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.| 10898 10899## HitTestValue 10900 10901Provides the element information of the area being clicked. For details about the sample code, see [getHitTestValue](#gethittestvalue). 10902 10903**System capability**: SystemCapability.Web.Webview.Core 10904 10905| Name| Type| Readable| Writable| Description| 10906| ---- | ---- | ---- | ---- |---- | 10907| type | [WebHitTestType](#webhittesttype) | Yes| Yes| Element type of the area being clicked.| 10908| extra | string | Yes| Yes|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.| 10909 10910## WebMessage 10911 10912type WebMessage = ArrayBuffer | string 10913 10914Describes the data types supported for [WebMessagePort](#webmessageport). 10915 10916**System capability**: SystemCapability.Web.Webview.Core 10917 10918| Type | Description | 10919| -------- | -------------------------------------- | 10920| string | String type.| 10921| ArrayBuffer | Binary type.| 10922 10923## JsMessageType<sup>10+</sup> 10924 10925Describes the type of the returned result of script execution using [runJavaScirptExt](#runjavascriptext10). 10926 10927**System capability**: SystemCapability.Web.Webview.Core 10928 10929| Name | Value| Description | 10930| ------------ | -- |--------------------------------- | 10931| NOT_SUPPORT | 0 |Unsupported data type.| 10932| STRING | 1 |String type.| 10933| NUMBER | 2 |Number type.| 10934| BOOLEAN | 3 |Boolean type.| 10935| ARRAY_BUFFER | 4 |Raw binary data buffer.| 10936| ARRAY | 5 |Array type.| 10937 10938## WebMessageType<sup>10+</sup> 10939 10940Describes the data type supported by the [webMessagePort](#webmessageport) API. 10941 10942**System capability**: SystemCapability.Web.Webview.Core 10943 10944| Name | Value| Description | 10945| ------------ | -- |------------------------------- | 10946| NOT_SUPPORT | 0 |Unsupported data type.| 10947| STRING | 1 |String type.| 10948| NUMBER | 2 |Number type.| 10949| BOOLEAN | 3 |Boolean type.| 10950| ARRAY_BUFFER | 4 |Raw binary data buffer.| 10951| ARRAY | 5 |Array type.| 10952| ERROR | 6 |Error object type.| 10953 10954## MediaPlaybackState<sup>12+</sup> 10955 10956Enumerates the playback states on the current web page. 10957 10958**System capability**: SystemCapability.Web.Webview.Core 10959 10960| Name | Value | Description | 10961| ------- | ---- | ------------------ | 10962| NONE | 0 | No audio or video playback is started on the page.| 10963| PLAYING | 1 | The audio and video on the page are being played.| 10964| PAUSED | 2 | The audio and video on the page are paused. | 10965| STOPPED | 3 | The audio and video on the page are stopped. | 10966 10967## RenderProcessMode<sup>12+</sup> 10968 10969Enumerates the ArkWeb render subprocess modes. 10970 10971**System capability**: SystemCapability.Web.Webview.Core 10972 10973| Name | Value| Description | 10974| ------------- | -- |----------------------------------------- | 10975| SINGLE | 0 |ArkWeb single render subprocess mode. In this mode, multiple **Web** components share one render subprocess.| 10976| MULTIPLE | 1 |ArkWeb multi-render subprocess mode. In this mode, each **Web** component has a rendering subprocess.| 10977 10978 10979## JsMessageExt<sup>10+</sup> 10980 10981Implements the **JsMessageExt** data object that is returned after script execution using the [runJavaScirptExt](#runjavascriptext10) API. 10982 10983### getType<sup>10+</sup> 10984 10985getType(): JsMessageType 10986 10987Obtains the type of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 10988 10989**System capability**: SystemCapability.Web.Webview.Core 10990 10991**Return value** 10992 10993| Type | Description | 10994| --------------| --------------------------------------------------------- | 10995| [JsMessageType](#jsmessagetype10) | Type of the data object that is returned after script execution using the [runJavaScirptExt](#runjavascriptext10) API.| 10996 10997### getString<sup>10+</sup> 10998 10999getString(): string 11000 11001Obtains string-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 11002 11003**System capability**: SystemCapability.Web.Webview.Core 11004 11005**Return value** 11006 11007| Type | Description | 11008| --------------| ------------- | 11009| string | Data of the string type.| 11010 11011**Error codes** 11012 11013For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11014 11015| ID| Error Message | 11016| -------- | ------------------------------------- | 11017| 17100014 | The type and value of the message do not match. | 11018 11019### getNumber<sup>10+</sup> 11020 11021getNumber(): number 11022 11023Obtains number-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 11024 11025**System capability**: SystemCapability.Web.Webview.Core 11026 11027**Return value** 11028 11029| Type | Description | 11030| --------------| ------------- | 11031| number | Data of the number type.| 11032 11033**Error codes** 11034 11035For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11036 11037| ID| Error Message | 11038| -------- | ------------------------------------- | 11039| 17100014 | The type and value of the message do not match. | 11040 11041### getBoolean<sup>10+</sup> 11042 11043getBoolean(): boolean 11044 11045Obtains Boolean-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 11046 11047**System capability**: SystemCapability.Web.Webview.Core 11048 11049**Return value** 11050 11051| Type | Description | 11052| --------------| ------------- | 11053| boolean | Data of the Boolean type.| 11054 11055**Error codes** 11056 11057For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11058 11059| ID| Error Message | 11060| -------- | ------------------------------------- | 11061| 17100014 | The type and value of the message do not match. | 11062 11063### getArrayBuffer<sup>10+</sup> 11064 11065getArrayBuffer(): ArrayBuffer 11066 11067Obtains raw binary data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 11068 11069**System capability**: SystemCapability.Web.Webview.Core 11070 11071**Return value** 11072 11073| Type | Description | 11074| --------------| ------------- | 11075| ArrayBuffer | Raw binary data.| 11076 11077**Error codes** 11078 11079For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11080 11081| ID| Error Message | 11082| -------- | ------------------------------------- | 11083| 17100014 | The type and value of the message do not match. | 11084 11085### getArray<sup>10+</sup> 11086 11087getArray(): Array\<string | number | boolean\> 11088 11089Obtains array-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 11090 11091**System capability**: SystemCapability.Web.Webview.Core 11092 11093**Return value** 11094 11095| Type | Description | 11096| --------------| ------------- | 11097| Array\<string \| number \| boolean\> | Data of the array type.| 11098 11099**Error codes** 11100 11101For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11102 11103| ID| Error Message | 11104| -------- | ------------------------------------- | 11105| 17100014 | The type and value of the message do not match. | 11106 11107## WebMessageExt<sup>10+</sup> 11108 11109Represents a data object received and sent through the [webMessagePort](#webmessageport) API. 11110 11111### getType<sup>10+</sup> 11112 11113getType(): WebMessageType 11114 11115Obtains the type of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11116 11117**System capability**: SystemCapability.Web.Webview.Core 11118 11119**Return value** 11120 11121| Type | Description | 11122| --------------| --------------------------------------------------------- | 11123| [WebMessageType](#webmessagetype10) | Data type supported by the [webMessagePort](#webmessageport) API.| 11124 11125### getString<sup>10+</sup> 11126 11127getString(): string 11128 11129Obtains string-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11130 11131**System capability**: SystemCapability.Web.Webview.Core 11132 11133**Return value** 11134 11135| Type | Description | 11136| --------------| ------------- | 11137| string | Data of the string type.| 11138 11139**Error codes** 11140 11141For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11142 11143| ID| Error Message | 11144| -------- | ------------------------------------- | 11145| 17100014 | The type and value of the message do not match. | 11146 11147### getNumber<sup>10+</sup> 11148 11149getNumber(): number 11150 11151Obtains number-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11152 11153**System capability**: SystemCapability.Web.Webview.Core 11154 11155**Return value** 11156 11157| Type | Description | 11158| --------------| ------------- | 11159| number | Data of the number type.| 11160 11161**Error codes** 11162 11163For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11164 11165| ID| Error Message | 11166| -------- | ------------------------------------- | 11167| 17100014 | The type and value of the message do not match. | 11168 11169### getBoolean<sup>10+</sup> 11170 11171getBoolean(): boolean 11172 11173Obtains Boolean-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11174 11175**System capability**: SystemCapability.Web.Webview.Core 11176 11177**Return value** 11178 11179| Type | Description | 11180| --------------| ------------- | 11181| boolean | Data of the Boolean type.| 11182 11183**Error codes** 11184 11185For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11186 11187| ID| Error Message | 11188| -------- | ------------------------------------- | 11189| 17100014 | The type and value of the message do not match. | 11190 11191### getArrayBuffer<sup>10+</sup> 11192 11193getArrayBuffer(): ArrayBuffer 11194 11195Obtains raw binary data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11196 11197**System capability**: SystemCapability.Web.Webview.Core 11198 11199**Return value** 11200 11201| Type | Description | 11202| --------------| ------------- | 11203| ArrayBuffer | Raw binary data.| 11204 11205**Error codes** 11206 11207For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11208 11209| ID| Error Message | 11210| -------- | ------------------------------------- | 11211| 17100014 | The type and value of the message do not match. | 11212 11213### getArray<sup>10+</sup> 11214 11215getArray(): Array\<string | number | boolean\> 11216 11217Obtains array-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11218 11219**System capability**: SystemCapability.Web.Webview.Core 11220 11221**Return value** 11222 11223| Type | Description | 11224| --------------| ------------- | 11225| Array\<string \| number \| boolean\> | Data of the array type.| 11226 11227**Error codes** 11228 11229For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11230 11231| ID| Error Message | 11232| -------- | ------------------------------------- | 11233| 17100014 | The type and value of the message do not match. | 11234 11235### getError<sup>10+</sup> 11236 11237getError(): Error 11238 11239Obtains the error-object-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11240 11241**System capability**: SystemCapability.Web.Webview.Core 11242 11243**Return value** 11244 11245| Type | Description | 11246| --------------| ------------- | 11247| Error | Data of the error object type.| 11248 11249**Error codes** 11250 11251For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11252 11253| ID| Error Message | 11254| -------- | ------------------------------------- | 11255| 17100014 | The type and value of the message do not match. | 11256 11257### setType<sup>10+</sup> 11258 11259setType(type: WebMessageType): void 11260 11261Sets the type for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11262 11263**System capability**: SystemCapability.Web.Webview.Core 11264 11265**Parameters** 11266 11267| Name| Type | Mandatory| Description | 11268| ------ | ------ | ---- | ---------------------- | 11269| type | [WebMessageType](#webmessagetype10) | Yes | Data type supported by the [webMessagePort](#webmessageport) API.| 11270 11271**Error codes** 11272 11273| ID| Error Message | 11274| -------- | ------------------------------------- | 11275| 17100014 | The type and value of the message do not match. | 11276| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11277 11278### setString<sup>10+</sup> 11279 11280setString(message: string): void 11281 11282Sets the string-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11283 11284**System capability**: SystemCapability.Web.Webview.Core 11285 11286**Parameters** 11287 11288| Name| Type | Mandatory| Description | 11289| ------ | ------ | ---- | -------------------- | 11290| message | string | Yes | String type.| 11291 11292**Error codes** 11293 11294| ID| Error Message | 11295| -------- | ------------------------------------- | 11296| 17100014 | The type and value of the message do not match. | 11297| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11298 11299### setNumber<sup>10+</sup> 11300 11301setNumber(message: number): void 11302 11303Sets the number-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11304 11305**System capability**: SystemCapability.Web.Webview.Core 11306 11307**Parameters** 11308 11309| Name| Type | Mandatory| Description | 11310| ------ | ------ | ---- | -------------------- | 11311| message | number | Yes | Data of the number type.| 11312 11313**Error codes** 11314 11315| ID| Error Message | 11316| -------- | ------------------------------------- | 11317| 17100014 | The type and value of the message do not match. | 11318| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11319 11320### setBoolean<sup>10+</sup> 11321 11322setBoolean(message: boolean): void 11323 11324Sets the Boolean-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11325 11326**System capability**: SystemCapability.Web.Webview.Core 11327 11328**Parameters** 11329 11330| Name| Type | Mandatory| Description | 11331| ------ | ------ | ---- | -------------------- | 11332| message | boolean | Yes | Data of the Boolean type.| 11333 11334**Error codes** 11335 11336| ID| Error Message | 11337| -------- | ------------------------------------- | 11338| 17100014 | The type and value of the message do not match. | 11339| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11340 11341### setArrayBuffer<sup>10+</sup> 11342 11343setArrayBuffer(message: ArrayBuffer): void 11344 11345Sets the raw binary data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11346 11347**System capability**: SystemCapability.Web.Webview.Core 11348 11349**Parameters** 11350 11351| Name| Type | Mandatory| Description | 11352| ------ | ------ | ---- | -------------------- | 11353| message | ArrayBuffer | Yes | Raw binary data.| 11354 11355**Error codes** 11356 11357For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11358 11359| ID| Error Message | 11360| -------- | ------------------------------------- | 11361| 17100014 | The type and value of the message do not match. | 11362| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11363 11364### setArray<sup>10+</sup> 11365 11366setArray(message: Array\<string | number | boolean\>): void 11367 11368Sets the array-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11369 11370**System capability**: SystemCapability.Web.Webview.Core 11371 11372**Parameters** 11373 11374| Name| Type | Mandatory| Description | 11375| ------ | ------ | ---- | -------------------- | 11376| message | Array\<string \| number \| boolean\> | Yes | Data of the array type.| 11377 11378**Error codes** 11379 11380For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11381 11382| ID| Error Message | 11383| -------- | ------------------------------------- | 11384| 17100014 | The type and value of the message do not match. | 11385| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11386 11387### setError<sup>10+</sup> 11388 11389setError(message: Error): void 11390 11391Sets the error-object-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11392 11393**System capability**: SystemCapability.Web.Webview.Core 11394 11395**Parameters** 11396 11397| Name| Type | Mandatory| Description | 11398| ------ | ------ | ---- | -------------------- | 11399| message | Error | Yes | Data of the error object type.| 11400 11401**Error codes** 11402 11403For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11404 11405| ID| Error Message | 11406| -------- | ------------------------------------- | 11407| 17100014 | The type and value of the message do not match. | 11408| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11409 11410## WebStorageOrigin 11411 11412Provides usage information of the Web SQL Database. 11413 11414**System capability**: SystemCapability.Web.Webview.Core 11415 11416| Name | Type | Readable| Writable| Description| 11417| ------ | ------ | ---- | ---- | ---- | 11418| origin | string | Yes | Yes| Index of the origin.| 11419| usage | number | Yes | Yes| Storage usage of the origin. | 11420| quota | number | Yes | Yes| Storage quota of the origin. | 11421 11422## BackForwardList 11423 11424Provides the historical information list of the current webview. 11425 11426**System capability**: SystemCapability.Web.Webview.Core 11427 11428| Name | Type | Readable| Writable| Description | 11429| ------------ | ------ | ---- | ---- | ------------------------------------------------------------ | 11430| currentIndex | number | Yes | Yes | Index of the current page in the page history stack. | 11431| size | number | Yes | Yes | Number of indexes in the history stack. The maximum value is 50. If this value is exceeded, the earliest index will be overwritten.| 11432 11433### getItemAtIndex 11434 11435getItemAtIndex(index: number): HistoryItem 11436 11437Obtains the page record with the specified index in the history stack. 11438 11439**System capability**: SystemCapability.Web.Webview.Core 11440 11441**Parameters** 11442 11443| Name| Type | Mandatory| Description | 11444| ------ | ------ | ---- | ---------------------- | 11445| index | number | Yes | Index of the target page record in the history stack.| 11446 11447**Return value** 11448 11449| Type | Description | 11450| --------------------------- | ------------ | 11451| [HistoryItem](#historyitem) | Historical page record.| 11452 11453**Error codes** 11454 11455For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11456 11457| ID| Error Message | 11458| -------- | ------------------------------------------------------ | 11459| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11460 11461**Example** 11462 11463```ts 11464// xxx.ets 11465import { webview } from '@kit.ArkWeb'; 11466import { BusinessError } from '@kit.BasicServicesKit'; 11467import { image } from '@kit.ImageKit'; 11468 11469@Entry 11470@Component 11471struct WebComponent { 11472 controller: webview.WebviewController = new webview.WebviewController(); 11473 @State icon: image.PixelMap | undefined = undefined; 11474 11475 build() { 11476 Column() { 11477 Button('getBackForwardEntries') 11478 .onClick(() => { 11479 try { 11480 let list = this.controller.getBackForwardEntries(); 11481 let historyItem = list.getItemAtIndex(list.currentIndex); 11482 console.log("HistoryItem: " + JSON.stringify(historyItem)); 11483 this.icon = historyItem.icon; 11484 } catch (error) { 11485 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11486 } 11487 }) 11488 Web({ src: 'www.example.com', controller: this.controller }) 11489 } 11490 } 11491} 11492``` 11493 11494## HistoryItem 11495 11496Describes a historical page record. 11497 11498**System capability**: SystemCapability.Web.Webview.Core 11499 11500| Name | Type | Readable| Writable| Description | 11501| ------------- | -------------------------------------- | ---- | ---- | ---------------------------- | 11502| icon | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | No | **PixelMap** object of the icon on the historical page.| 11503| historyUrl | string | Yes | Yes | URL of the historical page. | 11504| historyRawUrl | string | Yes | Yes | Original URL of the historical page. | 11505| title | string | Yes | Yes | Title of the historical page. | 11506 11507## WebCustomScheme 11508 11509Defines a custom URL scheme. 11510 11511**System capability**: SystemCapability.Web.Webview.Core 11512 11513| Name | Type | Readable| Writable| Description | 11514| -------------- | --------- | ---- | ---- | ---------------------------- | 11515| schemeName | string | Yes | Yes | Name of the custom URL scheme. The value can contain a maximum of 32 characters, including lowercase letters, digits, periods (.), plus signs (+), and hyphens (-), and must start with a letter. | 11516| isSupportCORS | boolean | Yes | Yes | Whether to support cross-origin resource sharing (CORS). | 11517| isSupportFetch | boolean | Yes | Yes | Whether to support fetch requests. | 11518| isStandard<sup>12+</sup> | boolean | Yes | Yes | Whether the scheme is processed as a standard scheme. The standard scheme must comply with the URL normalization and parsing rules defined in section 3.1 of RFC 1738. | 11519| isLocal<sup>12+</sup> | boolean | Yes | Yes | Whether the scheme is treated with the same security rules as those applied to file URLs. | 11520| isDisplayIsolated<sup>12+</sup> | boolean | Yes | Yes | Whether the content of the scheme can be displayed or accessed from other content that uses the same scheme. | 11521| isSecure<sup>12+</sup> | boolean | Yes | Yes | Whether the scheme is treated with the same security rules as those applied to HTTPS URLs. | 11522| isCspBypassing<sup>12+</sup> | boolean | Yes | Yes | Whether the scheme can bypass the content security policy (CSP) checks. In most cases, this value should not be set when **isStandard** is set to **true**. | 11523| isCodeCacheSupported<sup>12+</sup> | boolean | Yes | Yes | Whether JavaScript resources loaded with the scheme can be used to create a code cache. | 11524 11525## SecureDnsMode<sup>10+</sup> 11526 11527Describes the mode in which the **Web** component uses HTTPDNS. 11528 11529**System capability**: SystemCapability.Web.Webview.Core 11530 11531| Name | Value| Description | 11532| ------------- | -- |----------------------------------------- | 11533| OFF | 0 |HTTPDNS is not used. This value can be used to revoke the previously used HTTPDNS configuration.| 11534| AUTO | 1 |HTTPDNS is used in automatic mode. If the specified HTTPDNS server is unavailable for resolution, the component falls back to the system DNS server.| 11535| SECURE_ONLY | 2 |The specified HTTPDNS server is forcibly used for DNS resolution.| 11536 11537## WebDownloadState<sup>11+</sup> 11538 11539Describes the state of a download task. 11540 11541**System capability**: SystemCapability.Web.Webview.Core 11542 11543| Name | Value| Description | 11544| ------------- | -- |----------------------------------------- | 11545| IN_PROGRESS | 0 |The download task is in progress.| 11546| COMPLETED | 1 |The download task is completed.| 11547| CANCELED | 2 |The download task has been canceled.| 11548| INTERRUPTED | 3 |The download task is interrupted.| 11549| PENDING | 4 |The download task is pending.| 11550| PAUSED | 5 |The download task is paused.| 11551| UNKNOWN | 6 |The state of the download task is unknown.| 11552 11553## WebDownloadErrorCode<sup>11+</sup> 11554 11555Describes the download task error code. 11556 11557**System capability**: SystemCapability.Web.Webview.Core 11558 11559| Name | Value| Description | 11560| ------------- | -- |----------------------------------------- | 11561| ERROR_UNKNOWN | 0 |Unknown error.| 11562| FILE_FAILED | 1 | Failed to operate the file.| 11563| FILE_ACCESS_DENIED | 2 | No permission to access the file.| 11564| FILE_NO_SPACE | 3 | The disk space is insufficient.| 11565| FILE_NAME_TOO_LONG | 5 | The file name is too long.| 11566| FILE_TOO_LARGE | 6 | The file is too large.| 11567| FILE_TRANSIENT_ERROR | 10 | Some temporary issues occur, such as insufficient memory, files in use, and too many files open at the same time.| 11568| FILE_BLOCKED | 11 | Access to the file is blocked due to certain local policies.| 11569| FILE_TOO_SHORT | 13 | The file to resume downloading is not long enough. It may not exist.| 11570| FILE_HASH_MISMATCH | 14 | Hash mismatch.| 11571| FILE_SAME_AS_SOURCE | 15 | The file already exists.| 11572| NETWORK_FAILED | 20 | Common network error.| 11573| NETWORK_TIMEOUT | 21 | Network connection timeout.| 11574| NETWORK_DISCONNECTED | 22 | Network disconnected.| 11575| NETWORK_SERVER_DOWN | 23 | The server is shut down.| 11576| NETWORK_INVALID_REQUEST | 24 | Invalid network request. The request may be redirected to an unsupported scheme or an invalid URL.| 11577| SERVER_FAILED | 30 | The server returns a general error.| 11578| SERVER_NO_RANGE | 31 | The server does not support the range request.| 11579| SERVER_BAD_CONTENT | 33 | The server does not have the requested data.| 11580| SERVER_UNAUTHORIZED | 34 | The file cannot be downloaded from the server.| 11581| SERVER_CERT_PROBLEM | 35 | The server certificate is incorrect.| 11582| SERVER_FORBIDDEN | 36 | The access to the server is forbidden.| 11583| SERVER_UNREACHABLE | 37 | The server cannot be accessed.| 11584| SERVER_CONTENT_LENGTH_MISMATCH | 38 | The received data does not match the content length.| 11585| SERVER_CROSS_ORIGIN_REDIRECT | 39 | An unexpected cross-site redirection occurs.| 11586| USER_CANCELED | 40 | The user cancels the download.| 11587| USER_SHUTDOWN | 41 | The user closes the application.| 11588| CRASH | 50 | The application crashes.| 11589 11590## WebDownloadItem<sup>11+</sup> 11591 11592 Implements a **WebDownloadItem** object. You can use this object to perform operations on the corresponding download task. 11593 11594> **NOTE** 11595> 11596> During the download, the download process is notified to the user through **WebDownloadDelegate**. The user can operate the download task through the **WebDownloadItem** parameter. 11597 11598### getGuid<sup>11+</sup> 11599 11600getGuid(): string 11601 11602Obtains the unique ID of this download task. 11603 11604**System capability**: SystemCapability.Web.Webview.Core 11605 11606**Return value** 11607 11608| Type | Description | 11609| ------ | ------------------------- | 11610| string | Unique ID of the download task.| 11611 11612**Example** 11613 11614```ts 11615// xxx.ets 11616import { webview } from '@kit.ArkWeb'; 11617import { BusinessError } from '@kit.BasicServicesKit'; 11618 11619@Entry 11620@Component 11621struct WebComponent { 11622 controller: webview.WebviewController = new webview.WebviewController(); 11623 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 11624 11625 build() { 11626 Column() { 11627 Button('setDownloadDelegate') 11628 .onClick(() => { 11629 try { 11630 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 11631 console.log("will start a download."); 11632 // Pass in a download path and start the download. 11633 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 11634 }) 11635 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 11636 console.log("download update guid: " + webDownloadItem.getGuid()); 11637 }) 11638 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 11639 console.log("download failed guid: " + webDownloadItem.getGuid()); 11640 }) 11641 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 11642 console.log("download finish guid: " + webDownloadItem.getGuid()); 11643 }) 11644 this.controller.setDownloadDelegate(this.delegate); 11645 } catch (error) { 11646 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11647 } 11648 }) 11649 Button('startDownload') 11650 .onClick(() => { 11651 try { 11652 this.controller.startDownload('https://www.example.com'); 11653 } catch (error) { 11654 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11655 } 11656 }) 11657 Web({ src: 'www.example.com', controller: this.controller }) 11658 } 11659 } 11660} 11661``` 11662 11663### getCurrentSpeed<sup>11+</sup> 11664 11665getCurrentSpeed(): number 11666 11667Obtains the download speed, in bytes per second. 11668 11669**System capability**: SystemCapability.Web.Webview.Core 11670 11671**Return value** 11672 11673| Type | Description | 11674| ------ | ------------------------- | 11675| number | Download speed, in bytes per second.| 11676 11677**Example** 11678 11679```ts 11680// xxx.ets 11681import { webview } from '@kit.ArkWeb'; 11682import { BusinessError } from '@kit.BasicServicesKit'; 11683 11684@Entry 11685@Component 11686struct WebComponent { 11687 controller: webview.WebviewController = new webview.WebviewController(); 11688 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 11689 11690 build() { 11691 Column() { 11692 Button('setDownloadDelegate') 11693 .onClick(() => { 11694 try { 11695 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 11696 console.log("will start a download."); 11697 // Pass in a download path and start the download. 11698 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 11699 }) 11700 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 11701 console.log("download update current speed: " + webDownloadItem.getCurrentSpeed()); 11702 }) 11703 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 11704 console.log("download failed guid: " + webDownloadItem.getGuid()); 11705 }) 11706 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 11707 console.log("download finish guid: " + webDownloadItem.getGuid()); 11708 }) 11709 this.controller.setDownloadDelegate(this.delegate); 11710 } catch (error) { 11711 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11712 } 11713 }) 11714 Button('startDownload') 11715 .onClick(() => { 11716 try { 11717 this.controller.startDownload('https://www.example.com'); 11718 } catch (error) { 11719 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11720 } 11721 }) 11722 Web({ src: 'www.example.com', controller: this.controller }) 11723 } 11724 } 11725} 11726``` 11727 11728### getPercentComplete<sup>11+</sup> 11729 11730getPercentComplete(): number 11731 11732Obtains the download progress. The value **100** indicates that the download is complete. 11733 11734**System capability**: SystemCapability.Web.Webview.Core 11735 11736**Return value** 11737 11738| Type | Description | 11739| ------ | ------------------------- | 11740| number | Download progress. The value **100** indicates that the download is complete.| 11741 11742**Example** 11743 11744```ts 11745// xxx.ets 11746import { webview } from '@kit.ArkWeb'; 11747import { BusinessError } from '@kit.BasicServicesKit'; 11748 11749@Entry 11750@Component 11751struct WebComponent { 11752 controller: webview.WebviewController = new webview.WebviewController(); 11753 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 11754 11755 build() { 11756 Column() { 11757 Button('setDownloadDelegate') 11758 .onClick(() => { 11759 try { 11760 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 11761 console.log("will start a download."); 11762 // Pass in a download path and start the download. 11763 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 11764 }) 11765 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 11766 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 11767 }) 11768 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 11769 console.log("download failed guid: " + webDownloadItem.getGuid()); 11770 }) 11771 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 11772 console.log("download finish guid: " + webDownloadItem.getGuid()); 11773 }) 11774 this.controller.setDownloadDelegate(this.delegate); 11775 } catch (error) { 11776 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11777 } 11778 }) 11779 Button('startDownload') 11780 .onClick(() => { 11781 try { 11782 this.controller.startDownload('https://www.example.com'); 11783 } catch (error) { 11784 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11785 } 11786 }) 11787 Web({ src: 'www.example.com', controller: this.controller }) 11788 } 11789 } 11790} 11791``` 11792 11793### getTotalBytes<sup>11+</sup> 11794 11795getTotalBytes(): number 11796 11797Obtains the total length of the file to be downloaded. 11798 11799**System capability**: SystemCapability.Web.Webview.Core 11800 11801**Return value** 11802 11803| Type | Description | 11804| ------ | ------------------------- | 11805| number | Total length of the file to be downloaded.| 11806 11807**Example** 11808 11809```ts 11810// xxx.ets 11811import { webview } from '@kit.ArkWeb'; 11812import { BusinessError } from '@kit.BasicServicesKit'; 11813 11814@Entry 11815@Component 11816struct WebComponent { 11817 controller: webview.WebviewController = new webview.WebviewController(); 11818 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 11819 11820 build() { 11821 Column() { 11822 Button('setDownloadDelegate') 11823 .onClick(() => { 11824 try { 11825 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 11826 console.log("will start a download."); 11827 // Pass in a download path and start the download. 11828 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 11829 }) 11830 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 11831 console.log("download update total bytes: " + webDownloadItem.getTotalBytes()); 11832 }) 11833 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 11834 console.log("download failed guid: " + webDownloadItem.getGuid()); 11835 }) 11836 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 11837 console.log("download finish guid: " + webDownloadItem.getGuid()); 11838 }) 11839 this.controller.setDownloadDelegate(this.delegate); 11840 } catch (error) { 11841 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11842 } 11843 }) 11844 Button('startDownload') 11845 .onClick(() => { 11846 try { 11847 this.controller.startDownload('https://www.example.com'); 11848 } catch (error) { 11849 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11850 } 11851 }) 11852 Web({ src: 'www.example.com', controller: this.controller }) 11853 } 11854 } 11855} 11856``` 11857 11858### getState<sup>11+</sup> 11859 11860getState(): WebDownloadState 11861 11862Obtains the download state. 11863 11864**System capability**: SystemCapability.Web.Webview.Core 11865 11866**Return value** 11867 11868| Type | Description | 11869| ------ | ------------------------- | 11870| [WebDownloadState](#webdownloadstate11) | Download state.| 11871 11872**Example** 11873 11874```ts 11875// xxx.ets 11876import { webview } from '@kit.ArkWeb'; 11877import { BusinessError } from '@kit.BasicServicesKit'; 11878 11879@Entry 11880@Component 11881struct WebComponent { 11882 controller: webview.WebviewController = new webview.WebviewController(); 11883 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 11884 11885 build() { 11886 Column() { 11887 Button('setDownloadDelegate') 11888 .onClick(() => { 11889 try { 11890 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 11891 console.log("will start a download."); 11892 // Pass in a download path and start the download. 11893 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 11894 }) 11895 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 11896 console.log("download update download state: " + webDownloadItem.getState()); 11897 }) 11898 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 11899 console.log("download failed guid: " + webDownloadItem.getGuid()); 11900 }) 11901 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 11902 console.log("download finish guid: " + webDownloadItem.getGuid()); 11903 }) 11904 this.controller.setDownloadDelegate(this.delegate); 11905 } catch (error) { 11906 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11907 } 11908 }) 11909 Button('startDownload') 11910 .onClick(() => { 11911 try { 11912 this.controller.startDownload('https://www.example.com'); 11913 } catch (error) { 11914 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11915 } 11916 }) 11917 Web({ src: 'www.example.com', controller: this.controller }) 11918 } 11919 } 11920} 11921``` 11922 11923### getLastErrorCode<sup>11+</sup> 11924 11925getLastErrorCode(): WebDownloadErrorCode 11926 11927Obtains the download error code. 11928 11929**System capability**: SystemCapability.Web.Webview.Core 11930 11931**Return value** 11932 11933| Type | Description | 11934| ------ | ------------------------- | 11935| [WebDownloadErrorCode](#webdownloaderrorcode11) | Error code returned when the download error occurs.| 11936 11937**Example** 11938 11939```ts 11940// xxx.ets 11941import { webview } from '@kit.ArkWeb'; 11942import { BusinessError } from '@kit.BasicServicesKit'; 11943 11944@Entry 11945@Component 11946struct WebComponent { 11947 controller: webview.WebviewController = new webview.WebviewController(); 11948 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 11949 11950 build() { 11951 Column() { 11952 Button('setDownloadDelegate') 11953 .onClick(() => { 11954 try { 11955 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 11956 console.log("will start a download."); 11957 // Pass in a download path and start the download. 11958 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 11959 }) 11960 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 11961 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 11962 }) 11963 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 11964 console.log("download failed guid: " + webDownloadItem.getGuid()); 11965 console.log("download error code: " + webDownloadItem.getLastErrorCode()); 11966 }) 11967 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 11968 console.log("download finish guid: " + webDownloadItem.getGuid()); 11969 }) 11970 this.controller.setDownloadDelegate(this.delegate); 11971 } catch (error) { 11972 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11973 } 11974 }) 11975 Button('startDownload') 11976 .onClick(() => { 11977 try { 11978 this.controller.startDownload('https://www.example.com'); 11979 } catch (error) { 11980 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11981 } 11982 }) 11983 Web({ src: 'www.example.com', controller: this.controller }) 11984 } 11985 } 11986} 11987``` 11988 11989### getMethod<sup>11+</sup> 11990 11991getMethod(): string 11992 11993Obtains the request mode of this download task. 11994 11995**System capability**: SystemCapability.Web.Webview.Core 11996 11997**Return value** 11998 11999| Type | Description | 12000| ------ | ------------------------- | 12001| string | Request mode of the download task.| 12002 12003**Example** 12004 12005```ts 12006// xxx.ets 12007import { webview } from '@kit.ArkWeb'; 12008import { BusinessError } from '@kit.BasicServicesKit'; 12009 12010@Entry 12011@Component 12012struct WebComponent { 12013 controller: webview.WebviewController = new webview.WebviewController(); 12014 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12015 12016 build() { 12017 Column() { 12018 Button('setDownloadDelegate') 12019 .onClick(() => { 12020 try { 12021 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12022 console.log("Download will start. Method:" + webDownloadItem.getMethod()); 12023 // Pass in a download path and start the download. 12024 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12025 }) 12026 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12027 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12028 }) 12029 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12030 console.log("download failed guid: " + webDownloadItem.getGuid()); 12031 }) 12032 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12033 console.log("download finish guid: " + webDownloadItem.getGuid()); 12034 }) 12035 this.controller.setDownloadDelegate(this.delegate); 12036 } catch (error) { 12037 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12038 } 12039 }) 12040 Button('startDownload') 12041 .onClick(() => { 12042 try { 12043 this.controller.startDownload('https://www.example.com'); 12044 } catch (error) { 12045 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12046 } 12047 }) 12048 Web({ src: 'www.example.com', controller: this.controller }) 12049 } 12050 } 12051} 12052``` 12053 12054### getMimeType<sup>11+</sup> 12055 12056getMimeType(): string 12057 12058Obtains 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). 12059 12060**System capability**: SystemCapability.Web.Webview.Core 12061 12062**Return value** 12063 12064| Type | Description | 12065| ------ | ------------------------- | 12066| string | MIME type (for example, audio/ogg for a sound file, and image/png for an image file).| 12067 12068**Example** 12069 12070```ts 12071// xxx.ets 12072import { webview } from '@kit.ArkWeb'; 12073import { BusinessError } from '@kit.BasicServicesKit'; 12074 12075@Entry 12076@Component 12077struct WebComponent { 12078 controller: webview.WebviewController = new webview.WebviewController(); 12079 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12080 12081 build() { 12082 Column() { 12083 Button('setDownloadDelegate') 12084 .onClick(() => { 12085 try { 12086 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12087 console.log("Download will start. MIME type:" + webDownloadItem.getMimeType()); 12088 // Pass in a download path and start the download. 12089 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12090 }) 12091 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12092 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12093 }) 12094 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12095 console.log("download failed guid: " + webDownloadItem.getGuid()); 12096 }) 12097 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12098 console.log("download finish guid: " + webDownloadItem.getGuid()); 12099 }) 12100 this.controller.setDownloadDelegate(this.delegate); 12101 } catch (error) { 12102 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12103 } 12104 }) 12105 Button('startDownload') 12106 .onClick(() => { 12107 try { 12108 this.controller.startDownload('https://www.example.com'); 12109 } catch (error) { 12110 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12111 } 12112 }) 12113 Web({ src: 'www.example.com', controller: this.controller }) 12114 } 12115 } 12116} 12117``` 12118 12119### getUrl<sup>11+</sup> 12120 12121getUrl(): string 12122 12123Obtains the download request URL. 12124 12125**System capability**: SystemCapability.Web.Webview.Core 12126 12127**Return value** 12128 12129| Type | Description | 12130| ------ | ------------------------- | 12131| string | Download request URL.| 12132 12133**Example** 12134 12135```ts 12136// xxx.ets 12137import { webview } from '@kit.ArkWeb'; 12138import { BusinessError } from '@kit.BasicServicesKit'; 12139 12140@Entry 12141@Component 12142struct WebComponent { 12143 controller: webview.WebviewController = new webview.WebviewController(); 12144 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12145 12146 build() { 12147 Column() { 12148 Button('setDownloadDelegate') 12149 .onClick(() => { 12150 try { 12151 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12152 console.log("will start a download, url:" + webDownloadItem.getUrl()); 12153 // Pass in a download path and start the download. 12154 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12155 }) 12156 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12157 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12158 }) 12159 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12160 console.log("download failed guid: " + webDownloadItem.getGuid()); 12161 }) 12162 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12163 console.log("download finish guid: " + webDownloadItem.getGuid()); 12164 }) 12165 this.controller.setDownloadDelegate(this.delegate); 12166 } catch (error) { 12167 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12168 } 12169 }) 12170 Button('startDownload') 12171 .onClick(() => { 12172 try { 12173 this.controller.startDownload('https://www.example.com'); 12174 } catch (error) { 12175 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12176 } 12177 }) 12178 Web({ src: 'www.example.com', controller: this.controller }) 12179 } 12180 } 12181} 12182``` 12183 12184### getSuggestedFileName<sup>11+</sup> 12185 12186getSuggestedFileName(): string 12187 12188Obtains the suggested file name for this download task. 12189 12190**System capability**: SystemCapability.Web.Webview.Core 12191 12192**Return value** 12193 12194| Type | Description | 12195| ------ | ------------------------- | 12196| string | Suggested file name.| 12197 12198**Example** 12199 12200```ts 12201// xxx.ets 12202import { webview } from '@kit.ArkWeb'; 12203import { BusinessError } from '@kit.BasicServicesKit'; 12204 12205@Entry 12206@Component 12207struct WebComponent { 12208 controller: webview.WebviewController = new webview.WebviewController(); 12209 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12210 12211 build() { 12212 Column() { 12213 Button('setDownloadDelegate') 12214 .onClick(() => { 12215 try { 12216 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12217 console.log("will start a download, suggest name:" + webDownloadItem.getSuggestedFileName()); 12218 // Pass in a download path and start the download. 12219 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12220 }) 12221 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12222 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12223 }) 12224 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12225 console.log("download failed guid: " + webDownloadItem.getGuid()); 12226 }) 12227 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12228 console.log("download finish guid: " + webDownloadItem.getGuid()); 12229 }) 12230 this.controller.setDownloadDelegate(this.delegate); 12231 } catch (error) { 12232 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12233 } 12234 }) 12235 Button('startDownload') 12236 .onClick(() => { 12237 try { 12238 this.controller.startDownload('https://www.example.com'); 12239 } catch (error) { 12240 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12241 } 12242 }) 12243 Web({ src: 'www.example.com', controller: this.controller }) 12244 } 12245 } 12246} 12247``` 12248 12249### getReceivedBytes<sup>11+</sup> 12250 12251getReceivedBytes(): number 12252 12253Obtains the number of received bytes. 12254 12255**System capability**: SystemCapability.Web.Webview.Core 12256 12257**Return value** 12258 12259| Type | Description | 12260| ------ | ------------------------- | 12261| number | Number of received bytes.| 12262 12263**Example** 12264 12265```ts 12266// xxx.ets 12267import { webview } from '@kit.ArkWeb'; 12268import { BusinessError } from '@kit.BasicServicesKit'; 12269 12270@Entry 12271@Component 12272struct WebComponent { 12273 controller: webview.WebviewController = new webview.WebviewController(); 12274 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12275 12276 build() { 12277 Column() { 12278 Button('setDownloadDelegate') 12279 .onClick(() => { 12280 try { 12281 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12282 console.log("will start a download."); 12283 // Pass in a download path and start the download. 12284 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12285 }) 12286 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12287 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12288 console.log("download update received bytes: " + webDownloadItem.getReceivedBytes()); 12289 }) 12290 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12291 console.log("download failed guid: " + webDownloadItem.getGuid()); 12292 }) 12293 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12294 console.log("download finish guid: " + webDownloadItem.getGuid()); 12295 }) 12296 this.controller.setDownloadDelegate(this.delegate); 12297 } catch (error) { 12298 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12299 } 12300 }) 12301 Button('startDownload') 12302 .onClick(() => { 12303 try { 12304 this.controller.startDownload('https://www.example.com'); 12305 } catch (error) { 12306 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12307 } 12308 }) 12309 Web({ src: 'www.example.com', controller: this.controller }) 12310 } 12311 } 12312} 12313``` 12314 12315### getFullPath<sup>11+</sup> 12316 12317getFullPath(): string 12318 12319Obtains the full path of the downloaded file on the disk. 12320 12321**System capability**: SystemCapability.Web.Webview.Core 12322 12323**Return value** 12324 12325| Type | Description | 12326| ------ | ------------------------- | 12327| string | Full path of the downloaded file on the disk.| 12328 12329**Example** 12330 12331```ts 12332// xxx.ets 12333import { webview } from '@kit.ArkWeb'; 12334import { BusinessError } from '@kit.BasicServicesKit'; 12335 12336@Entry 12337@Component 12338struct WebComponent { 12339 controller: webview.WebviewController = new webview.WebviewController(); 12340 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12341 12342 build() { 12343 Column() { 12344 Button('setDownloadDelegate') 12345 .onClick(() => { 12346 try { 12347 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12348 console.log("will start a download."); 12349 // Pass in a download path and start the download. 12350 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12351 }) 12352 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12353 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12354 }) 12355 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12356 console.log("download failed guid: " + webDownloadItem.getGuid()); 12357 }) 12358 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12359 console.log("download finish guid: " + webDownloadItem.getGuid()); 12360 console.log("download finish full path: " + webDownloadItem.getFullPath()); 12361 }) 12362 this.controller.setDownloadDelegate(this.delegate); 12363 } catch (error) { 12364 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12365 } 12366 }) 12367 Button('startDownload') 12368 .onClick(() => { 12369 try { 12370 this.controller.startDownload('https://www.example.com'); 12371 } catch (error) { 12372 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12373 } 12374 }) 12375 Web({ src: 'www.example.com', controller: this.controller }) 12376 } 12377 } 12378} 12379``` 12380 12381### serialize<sup>11+</sup> 12382 12383serialize(): Uint8Array 12384 12385Serializes the failed download to a byte array. 12386 12387**System capability**: SystemCapability.Web.Webview.Core 12388 12389**Return value** 12390 12391| Type | Description | 12392| ------ | ------------------------- | 12393| Uint8Array | Byte array into which the failed download is serialized.| 12394 12395**Example** 12396 12397```ts 12398// xxx.ets 12399import { webview } from '@kit.ArkWeb'; 12400import { BusinessError } from '@kit.BasicServicesKit'; 12401 12402@Entry 12403@Component 12404struct WebComponent { 12405 controller: webview.WebviewController = new webview.WebviewController(); 12406 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12407 failedData: Uint8Array = new Uint8Array(); 12408 12409 build() { 12410 Column() { 12411 Button('setDownloadDelegate') 12412 .onClick(() => { 12413 try { 12414 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12415 console.log("will start a download."); 12416 // Pass in a download path and start the download. 12417 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12418 }) 12419 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12420 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12421 }) 12422 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12423 console.log("download failed guid: " + webDownloadItem.getGuid()); 12424 // Serialize the failed download to a byte array. 12425 this.failedData = webDownloadItem.serialize(); 12426 }) 12427 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12428 console.log("download finish guid: " + webDownloadItem.getGuid()); 12429 }) 12430 this.controller.setDownloadDelegate(this.delegate); 12431 } catch (error) { 12432 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12433 } 12434 }) 12435 Button('startDownload') 12436 .onClick(() => { 12437 try { 12438 this.controller.startDownload('https://www.example.com'); 12439 } catch (error) { 12440 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12441 } 12442 }) 12443 Web({ src: 'www.example.com', controller: this.controller }) 12444 } 12445 } 12446} 12447``` 12448 12449### deserialize<sup>11+</sup> 12450 12451static deserialize(serializedData: Uint8Array): WebDownloadItem 12452 12453Deserializes the serialized byte array into a **WebDownloadItem** object. 12454 12455**System capability**: SystemCapability.Web.Webview.Core 12456 12457**Parameters** 12458 12459| Name | Type | Mandatory | Description| 12460| ------------------ | ------- | ---- | ------------- | 12461| serializedData | Uint8Array | Yes | Byte array into which the download is serialized.| 12462 12463**Return value** 12464 12465| Type | Description | 12466| ------ | ------------------------- | 12467| [WebDownloadItem](#webdownloaditem11) | **WebDownloadItem** object.| 12468 12469**Error codes** 12470 12471For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12472 12473| ID| Error Message | 12474| -------- | ------------------------------------------------------------ | 12475| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. 2. Parameter verification failed. | 12476 12477**Example** 12478 12479```ts 12480// xxx.ets 12481import { webview } from '@kit.ArkWeb'; 12482import { BusinessError } from '@kit.BasicServicesKit'; 12483 12484@Entry 12485@Component 12486struct WebComponent { 12487 controller: webview.WebviewController = new webview.WebviewController(); 12488 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12489 failedData: Uint8Array = new Uint8Array(); 12490 12491 build() { 12492 Column() { 12493 Button('setDownloadDelegate') 12494 .onClick(() => { 12495 try { 12496 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12497 console.log("will start a download."); 12498 // Pass in a download path and start the download. 12499 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12500 }) 12501 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12502 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12503 }) 12504 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12505 console.log("download failed guid: " + webDownloadItem.getGuid()); 12506 // Serialize the failed download to a byte array. 12507 this.failedData = webDownloadItem.serialize(); 12508 }) 12509 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12510 console.log("download finish guid: " + webDownloadItem.getGuid()); 12511 }) 12512 this.controller.setDownloadDelegate(this.delegate); 12513 } catch (error) { 12514 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12515 } 12516 }) 12517 Button('startDownload') 12518 .onClick(() => { 12519 try { 12520 this.controller.startDownload('https://www.example.com'); 12521 } catch (error) { 12522 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12523 } 12524 }) 12525 Button('resumeDownload') 12526 .onClick(() => { 12527 try { 12528 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 12529 } catch (error) { 12530 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12531 } 12532 }) 12533 Web({ src: 'www.example.com', controller: this.controller }) 12534 } 12535 } 12536} 12537``` 12538 12539### start<sup>11+</sup> 12540 12541start(downloadPath: string): void 12542 12543Starts 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. 12544 12545**System capability**: SystemCapability.Web.Webview.Core 12546 12547**Parameters** 12548 12549| Name| Type | Mandatory| Description | 12550| ------ | ---------------------- | ---- | ------------------------------| 12551| downloadPath | string | Yes | Path (including the file name) of the file to download.| 12552 12553**Error codes** 12554 12555For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12556 12557| ID| Error Message | 12558| -------- | ------------------------------------------------------------ | 12559| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. 2. Parameter verification failed. | 12560 12561**Example** 12562 12563```ts 12564// xxx.ets 12565import { webview } from '@kit.ArkWeb'; 12566import { BusinessError } from '@kit.BasicServicesKit'; 12567 12568@Entry 12569@Component 12570struct WebComponent { 12571 controller: webview.WebviewController = new webview.WebviewController(); 12572 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12573 failedData: Uint8Array = new Uint8Array(); 12574 12575 build() { 12576 Column() { 12577 Button('setDownloadDelegate') 12578 .onClick(() => { 12579 try { 12580 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12581 console.log("will start a download."); 12582 // Pass in a download path and start the download. 12583 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12584 }) 12585 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12586 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12587 }) 12588 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12589 console.log("download failed guid: " + webDownloadItem.getGuid()); 12590 // Serialize the failed download to a byte array. 12591 this.failedData = webDownloadItem.serialize(); 12592 }) 12593 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12594 console.log("download finish guid: " + webDownloadItem.getGuid()); 12595 }) 12596 this.controller.setDownloadDelegate(this.delegate); 12597 } catch (error) { 12598 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12599 } 12600 }) 12601 Button('startDownload') 12602 .onClick(() => { 12603 try { 12604 this.controller.startDownload('https://www.example.com'); 12605 } catch (error) { 12606 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12607 } 12608 }) 12609 Button('resumeDownload') 12610 .onClick(() => { 12611 try { 12612 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 12613 } catch (error) { 12614 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12615 } 12616 }) 12617 Web({ src: 'www.example.com', controller: this.controller }) 12618 } 12619 } 12620} 12621``` 12622 12623### cancel<sup>11+</sup> 12624 12625cancel(): void 12626 12627Cancels a download task. 12628 12629**System capability**: SystemCapability.Web.Webview.Core 12630 12631**Example** 12632 12633```ts 12634// xxx.ets 12635import { webview } from '@kit.ArkWeb'; 12636import { BusinessError } from '@kit.BasicServicesKit'; 12637 12638@Entry 12639@Component 12640struct WebComponent { 12641 controller: webview.WebviewController = new webview.WebviewController(); 12642 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12643 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 12644 failedData: Uint8Array = new Uint8Array(); 12645 12646 build() { 12647 Column() { 12648 Button('setDownloadDelegate') 12649 .onClick(() => { 12650 try { 12651 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12652 console.log("will start a download."); 12653 // Pass in a download path and start the download. 12654 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12655 }) 12656 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12657 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12658 this.download = webDownloadItem; 12659 }) 12660 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12661 console.log("download failed guid: " + webDownloadItem.getGuid()); 12662 // Serialize the failed download to a byte array. 12663 this.failedData = webDownloadItem.serialize(); 12664 }) 12665 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12666 console.log("download finish guid: " + webDownloadItem.getGuid()); 12667 }) 12668 this.controller.setDownloadDelegate(this.delegate); 12669 } catch (error) { 12670 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12671 } 12672 }) 12673 Button('startDownload') 12674 .onClick(() => { 12675 try { 12676 this.controller.startDownload('https://www.example.com'); 12677 } catch (error) { 12678 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12679 } 12680 }) 12681 Button('resumeDownload') 12682 .onClick(() => { 12683 try { 12684 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 12685 } catch (error) { 12686 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12687 } 12688 }) 12689 Button('cancel') 12690 .onClick(() => { 12691 try { 12692 this.download.cancel(); 12693 } catch (error) { 12694 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12695 } 12696 }) 12697 Web({ src: 'www.example.com', controller: this.controller }) 12698 } 12699 } 12700} 12701``` 12702 12703### pause<sup>11+</sup> 12704 12705pause(): void 12706 12707Pauses a download task. 12708 12709**System capability**: SystemCapability.Web.Webview.Core 12710 12711**Error codes** 12712 12713For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12714 12715| ID | Error Message | 12716| -------- | ------------------------------------------------------------ | 12717| 17100019 | The download task is not started yet. | 12718 12719**Example** 12720 12721```ts 12722// xxx.ets 12723import { webview } from '@kit.ArkWeb'; 12724import { BusinessError } from '@kit.BasicServicesKit'; 12725 12726@Entry 12727@Component 12728struct WebComponent { 12729 controller: webview.WebviewController = new webview.WebviewController(); 12730 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12731 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 12732 failedData: Uint8Array = new Uint8Array(); 12733 12734 build() { 12735 Column() { 12736 Button('setDownloadDelegate') 12737 .onClick(() => { 12738 try { 12739 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12740 console.log("will start a download."); 12741 // Pass in a download path and start the download. 12742 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12743 }) 12744 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12745 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12746 this.download = webDownloadItem; 12747 }) 12748 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12749 console.log("download failed guid: " + webDownloadItem.getGuid()); 12750 // Serialize the failed download to a byte array. 12751 this.failedData = webDownloadItem.serialize(); 12752 }) 12753 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12754 console.log("download finish guid: " + webDownloadItem.getGuid()); 12755 }) 12756 this.controller.setDownloadDelegate(this.delegate); 12757 } catch (error) { 12758 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12759 } 12760 }) 12761 Button('startDownload') 12762 .onClick(() => { 12763 try { 12764 this.controller.startDownload('https://www.example.com'); 12765 } catch (error) { 12766 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12767 } 12768 }) 12769 Button('resumeDownload') 12770 .onClick(() => { 12771 try { 12772 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 12773 } catch (error) { 12774 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12775 } 12776 }) 12777 Button('cancel') 12778 .onClick(() => { 12779 try { 12780 this.download.cancel(); 12781 } catch (error) { 12782 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12783 } 12784 }) 12785 Button('pause') 12786 .onClick(() => { 12787 try { 12788 this.download.pause(); 12789 } catch (error) { 12790 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12791 } 12792 }) 12793 Web({ src: 'www.example.com', controller: this.controller }) 12794 } 12795 } 12796} 12797``` 12798 12799### resume<sup>11+</sup> 12800 12801resume(): void 12802 12803Resumes a download task. 12804 12805**System capability**: SystemCapability.Web.Webview.Core 12806 12807**Error codes** 12808 12809For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12810 12811| ID | Error Message | 12812| -------- | ------------------------------------------------------------ | 12813| 17100016 | The download task is not paused. | 12814 12815**Example** 12816 12817```ts 12818// xxx.ets 12819import { webview } from '@kit.ArkWeb'; 12820import { BusinessError } from '@kit.BasicServicesKit'; 12821 12822@Entry 12823@Component 12824struct WebComponent { 12825 controller: webview.WebviewController = new webview.WebviewController(); 12826 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12827 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 12828 failedData: Uint8Array = new Uint8Array(); 12829 12830 build() { 12831 Column() { 12832 Button('setDownloadDelegate') 12833 .onClick(() => { 12834 try { 12835 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12836 console.log("will start a download."); 12837 // Pass in a download path and start the download. 12838 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12839 }) 12840 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12841 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12842 this.download = webDownloadItem; 12843 }) 12844 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12845 console.log("download failed guid: " + webDownloadItem.getGuid()); 12846 // Serialize the failed download to a byte array. 12847 this.failedData = webDownloadItem.serialize(); 12848 }) 12849 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12850 console.log("download finish guid: " + webDownloadItem.getGuid()); 12851 }) 12852 this.controller.setDownloadDelegate(this.delegate); 12853 } catch (error) { 12854 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12855 } 12856 }) 12857 Button('startDownload') 12858 .onClick(() => { 12859 try { 12860 this.controller.startDownload('https://www.example.com'); 12861 } catch (error) { 12862 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12863 } 12864 }) 12865 Button('resumeDownload') 12866 .onClick(() => { 12867 try { 12868 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 12869 } catch (error) { 12870 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12871 } 12872 }) 12873 Button('cancel') 12874 .onClick(() => { 12875 try { 12876 this.download.cancel(); 12877 } catch (error) { 12878 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12879 } 12880 }) 12881 Button('pause') 12882 .onClick(() => { 12883 try { 12884 this.download.pause(); 12885 } catch (error) { 12886 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12887 } 12888 }) 12889 Button('resume') 12890 .onClick(() => { 12891 try { 12892 this.download.resume(); 12893 } catch (error) { 12894 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12895 } 12896 }) 12897 Web({ src: 'www.example.com', controller: this.controller }) 12898 } 12899 } 12900} 12901``` 12902 12903## WebDownloadDelegate<sup>11+</sup> 12904 12905 Implements a **WebDownloadDelegate** class. You can use the callbacks of this class to notify users of the download state. 12906 12907### onBeforeDownload<sup>11+</sup> 12908 12909onBeforeDownload(callback: Callback\<WebDownloadItem>): void 12910 12911Invoked 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. 12912 12913**System capability**: SystemCapability.Web.Webview.Core 12914 12915**Parameters** 12916 12917| Name | Type | Mandatory| Description | 12918| ------- | ------ | ---- | :------------- | 12919| callback | Callback\<[WebDownloadItem](#webdownloaditem11)> | Yes | Callback for triggering a download.| 12920 12921**Example** 12922 12923```ts 12924// xxx.ets 12925import { webview } from '@kit.ArkWeb'; 12926import { BusinessError } from '@kit.BasicServicesKit'; 12927 12928@Entry 12929@Component 12930struct WebComponent { 12931 controller: webview.WebviewController = new webview.WebviewController(); 12932 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12933 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 12934 failedData: Uint8Array = new Uint8Array(); 12935 12936 build() { 12937 Column() { 12938 Button('setDownloadDelegate') 12939 .onClick(() => { 12940 try { 12941 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12942 console.log("will start a download."); 12943 // Pass in a download path and start the download. 12944 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12945 }) 12946 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12947 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12948 this.download = webDownloadItem; 12949 }) 12950 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12951 console.log("download failed guid: " + webDownloadItem.getGuid()); 12952 // Serialize the failed download to a byte array. 12953 this.failedData = webDownloadItem.serialize(); 12954 }) 12955 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12956 console.log("download finish guid: " + webDownloadItem.getGuid()); 12957 }) 12958 this.controller.setDownloadDelegate(this.delegate); 12959 } catch (error) { 12960 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12961 } 12962 }) 12963 Button('startDownload') 12964 .onClick(() => { 12965 try { 12966 this.controller.startDownload('https://www.example.com'); 12967 } catch (error) { 12968 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12969 } 12970 }) 12971 Button('resumeDownload') 12972 .onClick(() => { 12973 try { 12974 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 12975 } catch (error) { 12976 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12977 } 12978 }) 12979 Button('cancel') 12980 .onClick(() => { 12981 try { 12982 this.download.cancel(); 12983 } catch (error) { 12984 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12985 } 12986 }) 12987 Button('pause') 12988 .onClick(() => { 12989 try { 12990 this.download.pause(); 12991 } catch (error) { 12992 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12993 } 12994 }) 12995 Button('resume') 12996 .onClick(() => { 12997 try { 12998 this.download.resume(); 12999 } catch (error) { 13000 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13001 } 13002 }) 13003 Web({ src: 'www.example.com', controller: this.controller }) 13004 } 13005 } 13006} 13007``` 13008 13009### onDownloadUpdated<sup>11+</sup> 13010 13011onDownloadUpdated(callback: Callback\<WebDownloadItem>): void 13012 13013Invoked when the download progress is updated. 13014 13015**System capability**: SystemCapability.Web.Webview.Core 13016 13017**Parameters** 13018 13019| Name | Type | Mandatory| Description | 13020| ------- | ------ | ---- | :------------- | 13021| callback | Callback\<[WebDownloadItem](#webdownloaditem11)> | Yes | Callback invoked when the downloaded progress is updated.| 13022 13023**Example** 13024 13025```ts 13026// xxx.ets 13027import { webview } from '@kit.ArkWeb'; 13028import { BusinessError } from '@kit.BasicServicesKit'; 13029 13030@Entry 13031@Component 13032struct WebComponent { 13033 controller: webview.WebviewController = new webview.WebviewController(); 13034 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13035 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13036 failedData: Uint8Array = new Uint8Array(); 13037 13038 build() { 13039 Column() { 13040 Button('setDownloadDelegate') 13041 .onClick(() => { 13042 try { 13043 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13044 console.log("will start a download."); 13045 // Pass in a download path and start the download. 13046 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13047 }) 13048 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13049 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13050 this.download = webDownloadItem; 13051 }) 13052 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13053 console.log("download failed guid: " + webDownloadItem.getGuid()); 13054 // Serialize the failed download to a byte array. 13055 this.failedData = webDownloadItem.serialize(); 13056 }) 13057 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13058 console.log("download finish guid: " + webDownloadItem.getGuid()); 13059 }) 13060 this.controller.setDownloadDelegate(this.delegate); 13061 } catch (error) { 13062 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13063 } 13064 }) 13065 Button('startDownload') 13066 .onClick(() => { 13067 try { 13068 this.controller.startDownload('https://www.example.com'); 13069 } catch (error) { 13070 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13071 } 13072 }) 13073 Button('resumeDownload') 13074 .onClick(() => { 13075 try { 13076 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13077 } catch (error) { 13078 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13079 } 13080 }) 13081 Button('cancel') 13082 .onClick(() => { 13083 try { 13084 this.download.cancel(); 13085 } catch (error) { 13086 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13087 } 13088 }) 13089 Button('pause') 13090 .onClick(() => { 13091 try { 13092 this.download.pause(); 13093 } catch (error) { 13094 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13095 } 13096 }) 13097 Button('resume') 13098 .onClick(() => { 13099 try { 13100 this.download.resume(); 13101 } catch (error) { 13102 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13103 } 13104 }) 13105 Web({ src: 'www.example.com', controller: this.controller }) 13106 } 13107 } 13108} 13109``` 13110 13111### onDownloadFinish<sup>11+</sup> 13112 13113onDownloadFinish(callback: Callback\<WebDownloadItem>): void 13114 13115Invoked when the download is complete. 13116 13117**System capability**: SystemCapability.Web.Webview.Core 13118 13119**Parameters** 13120 13121| Name | Type | Mandatory| Description | 13122| ------- | ------ | ---- | :------------- | 13123| callback | Callback\<[WebDownloadItem](#webdownloaditem11)> | Yes | Callback invoked when the download is complete.| 13124 13125**Example** 13126 13127```ts 13128// xxx.ets 13129import { webview } from '@kit.ArkWeb'; 13130import { BusinessError } from '@kit.BasicServicesKit'; 13131 13132@Entry 13133@Component 13134struct WebComponent { 13135 controller: webview.WebviewController = new webview.WebviewController(); 13136 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13137 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13138 failedData: Uint8Array = new Uint8Array(); 13139 13140 build() { 13141 Column() { 13142 Button('setDownloadDelegate') 13143 .onClick(() => { 13144 try { 13145 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13146 console.log("will start a download."); 13147 // Pass in a download path and start the download. 13148 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13149 }) 13150 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13151 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13152 this.download = webDownloadItem; 13153 }) 13154 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13155 console.log("download failed guid: " + webDownloadItem.getGuid()); 13156 // Serialize the failed download to a byte array. 13157 this.failedData = webDownloadItem.serialize(); 13158 }) 13159 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13160 console.log("download finish guid: " + webDownloadItem.getGuid()); 13161 }) 13162 this.controller.setDownloadDelegate(this.delegate); 13163 } catch (error) { 13164 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13165 } 13166 }) 13167 Button('startDownload') 13168 .onClick(() => { 13169 try { 13170 this.controller.startDownload('https://www.example.com'); 13171 } catch (error) { 13172 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13173 } 13174 }) 13175 Button('resumeDownload') 13176 .onClick(() => { 13177 try { 13178 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13179 } catch (error) { 13180 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13181 } 13182 }) 13183 Button('cancel') 13184 .onClick(() => { 13185 try { 13186 this.download.cancel(); 13187 } catch (error) { 13188 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13189 } 13190 }) 13191 Button('pause') 13192 .onClick(() => { 13193 try { 13194 this.download.pause(); 13195 } catch (error) { 13196 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13197 } 13198 }) 13199 Button('resume') 13200 .onClick(() => { 13201 try { 13202 this.download.resume(); 13203 } catch (error) { 13204 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13205 } 13206 }) 13207 Web({ src: 'www.example.com', controller: this.controller }) 13208 } 13209 } 13210} 13211``` 13212 13213### onDownloadFailed<sup>11+</sup> 13214 13215onDownloadFailed(callback: Callback\<WebDownloadItem>): void 13216 13217Invoked when the download fails. 13218 13219**System capability**: SystemCapability.Web.Webview.Core 13220 13221**Parameters** 13222 13223| Name | Type | Mandatory| Description | 13224| ------- | ------ | ---- | :------------- | 13225| callback | Callback\<[WebDownloadItem](#webdownloaditem11)> | Yes | Callback invoked when the download fails.| 13226 13227**Example** 13228 13229```ts 13230// xxx.ets 13231import { webview } from '@kit.ArkWeb'; 13232import { BusinessError } from '@kit.BasicServicesKit'; 13233 13234@Entry 13235@Component 13236struct WebComponent { 13237 controller: webview.WebviewController = new webview.WebviewController(); 13238 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13239 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13240 failedData: Uint8Array = new Uint8Array(); 13241 13242 build() { 13243 Column() { 13244 Button('setDownloadDelegate') 13245 .onClick(() => { 13246 try { 13247 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13248 console.log("will start a download."); 13249 // Pass in a download path and start the download. 13250 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13251 }) 13252 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13253 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13254 this.download = webDownloadItem; 13255 }) 13256 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13257 console.log("download failed guid: " + webDownloadItem.getGuid()); 13258 // Serialize the failed download to a byte array. 13259 this.failedData = webDownloadItem.serialize(); 13260 }) 13261 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13262 console.log("download finish guid: " + webDownloadItem.getGuid()); 13263 }) 13264 this.controller.setDownloadDelegate(this.delegate); 13265 } catch (error) { 13266 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13267 } 13268 }) 13269 Button('startDownload') 13270 .onClick(() => { 13271 try { 13272 this.controller.startDownload('https://www.example.com'); 13273 } catch (error) { 13274 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13275 } 13276 }) 13277 Button('resumeDownload') 13278 .onClick(() => { 13279 try { 13280 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13281 } catch (error) { 13282 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13283 } 13284 }) 13285 Button('cancel') 13286 .onClick(() => { 13287 try { 13288 this.download.cancel(); 13289 } catch (error) { 13290 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13291 } 13292 }) 13293 Button('pause') 13294 .onClick(() => { 13295 try { 13296 this.download.pause(); 13297 } catch (error) { 13298 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13299 } 13300 }) 13301 Button('resume') 13302 .onClick(() => { 13303 try { 13304 this.download.resume(); 13305 } catch (error) { 13306 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13307 } 13308 }) 13309 Web({ src: 'www.example.com', controller: this.controller }) 13310 } 13311 } 13312} 13313``` 13314 13315## WebDownloadManager<sup>11+</sup> 13316 13317Implements a **WebDownloadManager** class. You can use the APIs of this class to resume failed download tasks. 13318 13319### setDownloadDelegate<sup>11+</sup> 13320 13321static setDownloadDelegate(delegate: WebDownloadDelegate): void 13322 13323Sets the delegate used to receive download progress triggered from **WebDownloadManager**. 13324 13325**System capability**: SystemCapability.Web.Webview.Core 13326 13327**Parameters** 13328 13329| Name | Type | Mandatory | Description | 13330| ---------------| ------- | ---- | ------------- | 13331| delegate | [WebDownloadDelegate](#webdownloaddelegate11) | Yes | Delegate used to receive the download progress.| 13332 13333**Example** 13334 13335```ts 13336// xxx.ets 13337import { webview } from '@kit.ArkWeb'; 13338import { BusinessError } from '@kit.BasicServicesKit'; 13339 13340@Entry 13341@Component 13342struct WebComponent { 13343 controller: webview.WebviewController = new webview.WebviewController(); 13344 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13345 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13346 failedData: Uint8Array = new Uint8Array(); 13347 13348 build() { 13349 Column() { 13350 Button('setDownloadDelegate') 13351 .onClick(() => { 13352 try { 13353 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13354 console.log("will start a download."); 13355 // Pass in a download path and start the download. 13356 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13357 }) 13358 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13359 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13360 this.download = webDownloadItem; 13361 }) 13362 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13363 console.log("download failed guid: " + webDownloadItem.getGuid()); 13364 // Serialize the failed download to a byte array. 13365 this.failedData = webDownloadItem.serialize(); 13366 }) 13367 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13368 console.log("download finish guid: " + webDownloadItem.getGuid()); 13369 }) 13370 this.controller.setDownloadDelegate(this.delegate); 13371 webview.WebDownloadManager.setDownloadDelegate(this.delegate); 13372 } catch (error) { 13373 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13374 } 13375 }) 13376 Button('startDownload') 13377 .onClick(() => { 13378 try { 13379 this.controller.startDownload('https://www.example.com'); 13380 } catch (error) { 13381 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13382 } 13383 }) 13384 Button('resumeDownload') 13385 .onClick(() => { 13386 try { 13387 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13388 } catch (error) { 13389 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13390 } 13391 }) 13392 Button('cancel') 13393 .onClick(() => { 13394 try { 13395 this.download.cancel(); 13396 } catch (error) { 13397 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13398 } 13399 }) 13400 Button('pause') 13401 .onClick(() => { 13402 try { 13403 this.download.pause(); 13404 } catch (error) { 13405 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13406 } 13407 }) 13408 Button('resume') 13409 .onClick(() => { 13410 try { 13411 this.download.resume(); 13412 } catch (error) { 13413 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13414 } 13415 }) 13416 Web({ src: 'www.example.com', controller: this.controller }) 13417 } 13418 } 13419} 13420``` 13421 13422### resumeDownload<sup>11+</sup> 13423 13424static resumeDownload(webDownloadItem: WebDownloadItem): void 13425 13426Resumes a failed download task. 13427 13428**System capability**: SystemCapability.Web.Webview.Core 13429 13430**Parameters** 13431 13432| Name | Type | Mandatory | Description | 13433| ---------------| ------- | ---- | ------------- | 13434| webDownloadItem | [WebDownloadItem](#webdownloaditem11) | Yes | Download task to resume.| 13435 13436**Error codes** 13437 13438For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 13439 13440| ID| Error Message | 13441| -------- | ------------------------------------- | 13442| 17100018 | No WebDownloadDelegate has been set yet. | 13443 13444**Example** 13445 13446```ts 13447// xxx.ets 13448import { webview } from '@kit.ArkWeb'; 13449import { BusinessError } from '@kit.BasicServicesKit'; 13450 13451@Entry 13452@Component 13453struct WebComponent { 13454 controller: webview.WebviewController = new webview.WebviewController(); 13455 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13456 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13457 failedData: Uint8Array = new Uint8Array(); 13458 13459 build() { 13460 Column() { 13461 Button('setDownloadDelegate') 13462 .onClick(() => { 13463 try { 13464 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13465 console.log("will start a download."); 13466 // Pass in a download path and start the download. 13467 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13468 }) 13469 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13470 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13471 this.download = webDownloadItem; 13472 }) 13473 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13474 console.log("download failed guid: " + webDownloadItem.getGuid()); 13475 // Serialize the failed download to a byte array. 13476 this.failedData = webDownloadItem.serialize(); 13477 }) 13478 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13479 console.log("download finish guid: " + webDownloadItem.getGuid()); 13480 }) 13481 this.controller.setDownloadDelegate(this.delegate); 13482 webview.WebDownloadManager.setDownloadDelegate(this.delegate); 13483 } catch (error) { 13484 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13485 } 13486 }) 13487 Button('startDownload') 13488 .onClick(() => { 13489 try { 13490 this.controller.startDownload('https://www.example.com'); 13491 } catch (error) { 13492 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13493 } 13494 }) 13495 Button('resumeDownload') 13496 .onClick(() => { 13497 try { 13498 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13499 } catch (error) { 13500 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13501 } 13502 }) 13503 Button('cancel') 13504 .onClick(() => { 13505 try { 13506 this.download.cancel(); 13507 } catch (error) { 13508 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13509 } 13510 }) 13511 Button('pause') 13512 .onClick(() => { 13513 try { 13514 this.download.pause(); 13515 } catch (error) { 13516 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13517 } 13518 }) 13519 Button('resume') 13520 .onClick(() => { 13521 try { 13522 this.download.resume(); 13523 } catch (error) { 13524 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13525 } 13526 }) 13527 Web({ src: 'www.example.com', controller: this.controller }) 13528 } 13529 } 13530} 13531``` 13532 13533## getLastJavascriptProxyCallingFrameUrl<sup>12+</sup> 13534 13535getLastJavascriptProxyCallingFrameUrl(): string 13536 13537Obtains the URL of the frame from which the last JavaScript proxy object was called. You can inject a JavaScript object into the window object using APIs like [registerJavaScriptProxy](#registerjavascriptproxy) or [javaScriptProxy](ts-basic-components-web.md#javascriptproxy). 13538 13539**System capability**: SystemCapability.Web.Webview.Core 13540 13541**Error codes** 13542 13543For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 13544 13545| ID| Error Message | 13546| -------- | ------------------------------------------------------------ | 13547| 17100001 | Init error. The WebviewController must be associated with a Web component. | 13548 13549**Example** 13550 13551```ts 13552// xxx.ets 13553import { webview } from '@kit.ArkWeb'; 13554import { BusinessError } from '@kit.BasicServicesKit'; 13555 13556class TestObj { 13557 mycontroller: webview.WebviewController; 13558 13559 constructor(controller: webview.WebviewController) { 13560 this.mycontroller = controller; 13561 } 13562 13563 test(testStr: string): string { 13564 console.log('Web Component str' + testStr + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 13565 return testStr; 13566 } 13567 13568 toString(): void { 13569 console.log('Web Component toString ' + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 13570 } 13571 13572 testNumber(testNum: number): number { 13573 console.log('Web Component number' + testNum + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 13574 return testNum; 13575 } 13576 13577 testBool(testBol: boolean): boolean { 13578 console.log('Web Component boolean' + testBol + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 13579 return testBol; 13580 } 13581} 13582 13583class WebObj { 13584 mycontroller: webview.WebviewController; 13585 13586 constructor(controller: webview.WebviewController) { 13587 this.mycontroller = controller; 13588 } 13589 13590 webTest(): string { 13591 console.log('Web test ' + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 13592 return "Web test"; 13593 } 13594 13595 webString(): void { 13596 console.log('Web test toString ' + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 13597 } 13598} 13599 13600@Entry 13601@Component 13602struct Index { 13603 controller: webview.WebviewController = new webview.WebviewController(); 13604 @State testObjtest: TestObj = new TestObj(this.controller); 13605 @State webTestObj: WebObj = new WebObj(this.controller); 13606 13607 build() { 13608 Column() { 13609 Button('refresh') 13610 .onClick(() => { 13611 try { 13612 this.controller.refresh(); 13613 } catch (error) { 13614 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13615 } 13616 }) 13617 Button('Register JavaScript To Window') 13618 .onClick(() => { 13619 try { 13620 this.controller.registerJavaScriptProxy(this.testObjtest, "objName", ["test", "toString", "testNumber", "testBool"]); 13621 this.controller.registerJavaScriptProxy(this.webTestObj, "objTestName", ["webTest", "webString"]); 13622 } catch (error) { 13623 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13624 } 13625 }) 13626 Web({ src: $rawfile('index.html'), controller: this.controller }) 13627 .javaScriptAccess(true) 13628 } 13629 } 13630} 13631``` 13632 13633HTML file to be loaded: 13634```html 13635<!-- index.html --> 13636<!DOCTYPE html> 13637<html> 13638 <meta charset="utf-8"> 13639 <body> 13640 <button type="button" onclick="htmlTest()">Click Me!</button> 13641 <p id="demo"></p> 13642 <p id="webDemo"></p> 13643 </body> 13644 <script type="text/javascript"> 13645 function htmlTest() { 13646 // This function call expects to return "ArkUI Web Component" 13647 let str=objName.test("webtest data"); 13648 objName.testNumber(1); 13649 objName.testBool(true); 13650 document.getElementById("demo").innerHTML=str; 13651 console.log('objName.test result:'+ str) 13652 13653 // This function call expects to return "Web test" 13654 let webStr = objTestName.webTest(); 13655 document.getElementById("webDemo").innerHTML=webStr; 13656 console.log('objTestName.webTest result:'+ webStr) 13657 } 13658</script> 13659</html> 13660``` 13661## WebHttpBodyStream<sup>12+</sup> 13662 13663Represents the body of the data being sent in POST and PUT requests. It accepts data of the BYTES, FILE, BLOB, and CHUNKED types. Note that other APIs in this class can be called only after [initialize](#initialize12) is called successfully. 13664 13665### initialize<sup>12+</sup> 13666 13667initialize(): Promise\<void\> 13668 13669Initializes this **WebHttpBodyStream** instance. 13670 13671**System capability**: SystemCapability.Web.Webview.Core 13672 13673**Return value** 13674 13675| Type | Description | 13676| ------ | ------------------------- | 13677| Promise\<void\> | Promise used to return the result.| 13678 13679**Error codes** 13680 13681For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 13682 13683| ID| Error Message | 13684| -------- | ------------------------------------- | 13685| 17100022 | Failed to initialize the HTTP body stream. | 13686 13687**Example** 13688 13689```ts 13690// xxx.ets 13691import { webview } from '@kit.ArkWeb'; 13692import { BusinessError } from '@kit.BasicServicesKit'; 13693import { buffer } from '@kit.ArkTS'; 13694import { WebNetErrorList } from '@ohos.web.netErrorList' 13695 13696@Entry 13697@Component 13698struct WebComponent { 13699 controller: webview.WebviewController = new webview.WebviewController(); 13700 schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); 13701 htmlData: string = "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>"; 13702 13703 build() { 13704 Column() { 13705 Button('postUrl') 13706 .onClick(() => { 13707 try { 13708 let postData = buffer.from(this.htmlData); 13709 this.controller.postUrl('https://www.example.com', postData.buffer); 13710 } catch (error) { 13711 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13712 } 13713 }) 13714 Web({ src: 'https://www.example.com', controller: this.controller }) 13715 .onControllerAttached(() => { 13716 try { 13717 this.schemeHandler.onRequestStart((request: webview.WebSchemeHandlerRequest, resourceHandler: webview.WebResourceHandler) => { 13718 console.log("[schemeHandler] onRequestStart"); 13719 try { 13720 let stream = request.getHttpBodyStream(); 13721 if (stream) { 13722 stream.initialize().then(() => { 13723 if (!stream) { 13724 return; 13725 } 13726 console.log("[schemeHandler] onRequestStart postDataStream size:" + stream.getSize()); 13727 console.log("[schemeHandler] onRequestStart postDataStream position:" + stream.getPosition()); 13728 console.log("[schemeHandler] onRequestStart postDataStream isChunked:" + stream.isChunked()); 13729 console.log("[schemeHandler] onRequestStart postDataStream isEof:" + stream.isEof()); 13730 console.log("[schemeHandler] onRequestStart postDataStream isInMemory:" + stream.isInMemory()); 13731 stream.read(stream.getSize()).then((buffer) => { 13732 if (!stream) { 13733 return; 13734 } 13735 console.log("[schemeHandler] onRequestStart postDataStream readlength:" + buffer.byteLength); 13736 console.log("[schemeHandler] onRequestStart postDataStream isEof:" + stream.isEof()); 13737 console.log("[schemeHandler] onRequestStart postDataStream position:" + stream.getPosition()); 13738 }).catch((error: BusinessError) => { 13739 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 13740 }) 13741 }).catch((error: BusinessError) => { 13742 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 13743 }) 13744 } else { 13745 console.log("[schemeHandler] onRequestStart has no http body stream"); 13746 } 13747 } catch (error) { 13748 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13749 } 13750 13751 return false; 13752 }) 13753 13754 this.schemeHandler.onRequestStop((request: webview.WebSchemeHandlerRequest) => { 13755 console.log("[schemeHandler] onRequestStop"); 13756 }); 13757 13758 this.controller.setWebSchemeHandler('https', this.schemeHandler); 13759 } catch (error) { 13760 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13761 } 13762 }) 13763 .javaScriptAccess(true) 13764 .domStorageAccess(true) 13765 } 13766 } 13767} 13768 13769``` 13770 13771### read<sup>12+</sup> 13772 13773read(size: number): Promise\<ArrayBuffer\> 13774 13775Reads data from this **WebHttpBodyStream** instance. 13776 13777**System capability**: SystemCapability.Web.Webview.Core 13778 13779**Parameters** 13780 13781| Name | Type | Mandatory | Description | 13782| --------| ------- | ---- | ---------------------------| 13783| size | number | Yes | Number of bytes obtained from the **WebHttpBodyStream** instance.| 13784 13785**Return value** 13786 13787| Type | Description | 13788| ------ | ------------------------- | 13789| Promise\<ArrayBuffer\> | Promise used to return the result.| 13790 13791**Error codes** 13792 13793For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 13794 13795| ID| Error Message | 13796| -------- | ------------------------------------- | 13797| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 13798 13799**Example** 13800 13801For the complete sample code, see [initialize](#initialize12)). 13802 13803### getSize<sup>12+</sup> 13804 13805getSize(): number 13806 13807Obtains the size of data in this **WebHttpBodyStream** instance. This API always returns zero when chunked transfer is used. 13808 13809**System capability**: SystemCapability.Web.Webview.Core 13810 13811**Return value** 13812 13813| Type | Description | 13814| ------ | ------------------------- | 13815| number | Size of data in the current **WebHttpBodyStream** instance.| 13816 13817**Example** 13818 13819For the complete sample code, see [initialize](#initialize12)). 13820 13821### getPosition<sup>12+</sup> 13822 13823getPosition(): number 13824 13825Reads the current read position in this **WebHttpBodyStream** instance. 13826 13827**System capability**: SystemCapability.Web.Webview.Core 13828 13829**Return value** 13830 13831| Type | Description | 13832| ------ | ------------------------- | 13833| number | Current read position in the **WebHttpBodyStream** instance.| 13834 13835**Example** 13836 13837For the complete sample code, see [initialize](#initialize12)). 13838 13839### isChunked<sup>12+</sup> 13840 13841isChunked(): boolean 13842 13843Checks whether this **WebHttpBodyStream** instance is transmitted by chunk. 13844 13845**System capability**: SystemCapability.Web.Webview.Core 13846 13847**Return value** 13848 13849| Type | Description | 13850| ------ | ------------------------- | 13851| boolean | Whether the **WebHttpBodyStream** instance is transmitted by chunk.| 13852 13853**Example** 13854 13855For the complete sample code, see [initialize](#initialize12)). 13856 13857### isEof<sup>12+</sup> 13858 13859isEof(): boolean 13860 13861Checks whether all data in this **WebHttpBodyStream** instance has been read. This API returns **true** if all data in the **httpBodyStream** instance is read. It returns **false** before the first read attempt is made for the **WebHttpBodyStream** instance that uses chunked transfer. 13862 13863**System capability**: SystemCapability.Web.Webview.Core 13864 13865**Return value** 13866 13867| Type | Description | 13868| ------ | ------------------------- | 13869| boolean | Whether all data in the **WebHttpBodyStream** instance has been read.| 13870 13871**Example** 13872 13873For the complete sample code, see [initialize](#initialize12)). 13874 13875### isInMemory<sup>12+</sup> 13876 13877isInMemory(): boolean 13878 13879Checks whether the uploaded data in this **httpBodyStream** instance is in memory. This API returns **true** if all the upload data in the **httpBodyStream** instance is in memory and all read requests will be completed synchronously. It returns **false** if the data is chunked to transfer. 13880 13881**System capability**: SystemCapability.Web.Webview.Core 13882 13883**Return value** 13884 13885| Type | Description | 13886| ------ | ------------------------- | 13887| boolean | Whether the uploaded data in the **WebHttpBodyStream** instance is stored in memory.| 13888 13889**Example** 13890 13891For the complete sample code, see [initialize](#initialize12)). 13892 13893## WebSchemeHandlerRequest<sup>12+</sup> 13894 13895Represents a request intercepted by the **WebSchemeHandler** object. 13896 13897### getHeader<sup>12+</sup> 13898 13899getHeader(): Array\<WebHeader\> 13900 13901Obtains the information about the resource request header. 13902 13903**System capability**: SystemCapability.Web.Webview.Core 13904 13905**Return value** 13906 13907| Type | Description | 13908| -------------------------- | ---------- | 13909| Array\<[WebHeader](#webheader)\> | Information about the resource request header.| 13910 13911**Example** 13912 13913For the complete sample code, see [onRequestStart](#onrequeststart12). 13914 13915### getRequestUrl<sup>12+</sup> 13916 13917getRequestUrl(): string 13918 13919Obtains the URL of the resource request. 13920 13921**System capability**: SystemCapability.Web.Webview.Core 13922 13923**Return value** 13924 13925| Type | Description | 13926| ------ | ------------- | 13927| string | URL of the resource request.| 13928 13929**Example** 13930 13931For the complete sample code, see [onRequestStart](#onrequeststart12). 13932 13933### getRequestMethod<sup>12+</sup> 13934 13935getRequestMethod(): string 13936 13937Obtains the request method. 13938 13939**System capability**: SystemCapability.Web.Webview.Core 13940 13941**Return value** 13942 13943| Type | Description | 13944| ------ | ------------- | 13945| string | Request method.| 13946 13947**Example** 13948 13949For the complete sample code, see [onRequestStart](#onrequeststart12). 13950 13951### getReferrer<sup>12+</sup> 13952 13953getReferrer(): string 13954 13955Obtains the referrer. 13956 13957**System capability**: SystemCapability.Web.Webview.Core 13958 13959**Return value** 13960 13961| Type | Description | 13962| ------ | ------------- | 13963| string | Obtained referrer.| 13964 13965**Example** 13966 13967For the complete sample code, see [onRequestStart](#onrequeststart12). 13968 13969### isMainFrame<sup>12+</sup> 13970 13971isMainFrame(): boolean 13972 13973Checks whether the resource request is for the main frame. 13974 13975**System capability**: SystemCapability.Web.Webview.Core 13976 13977**Return value** 13978 13979| Type | Description | 13980| ------ | ------------- | 13981| boolean | Whether the resource request is for the main frame.| 13982 13983**Example** 13984 13985For the complete sample code, see [onRequestStart](#onrequeststart12). 13986 13987### hasGesture<sup>12+</sup> 13988 13989hasGesture(): boolean 13990 13991Checks whether the resource request is associated with a gesture (for example, a tap). 13992 13993**System capability**: SystemCapability.Web.Webview.Core 13994 13995**Return value** 13996 13997| Type | Description | 13998| ------ | ------------- | 13999| boolean | Whether the resource request is associated with a gesture (for example, a tap).| 14000 14001**Example** 14002 14003For the complete sample code, see [onRequestStart](#onrequeststart12). 14004 14005### getHttpBodyStream<sup>12+</sup> 14006 14007getHttpBodyStream(): WebHttpBodyStream | null 14008 14009Obtains the **WebHttpBodyStream** instance in this resource request. 14010 14011**System capability**: SystemCapability.Web.Webview.Core 14012 14013**Return value** 14014 14015| Type | Description | 14016| ------ | ------------- | 14017| [WebHttpBodyStream](#webhttpbodystream12) \| null | **WebHttpBodyStream** instance in the resource request. If there is no **WebHttpBodyStream** instance, **null** is returned.| 14018 14019**Example** 14020 14021For the complete sample code, see [onRequestStart](#onrequeststart12). 14022 14023### getRequestResourceType<sup>12+</sup> 14024 14025getRequestResourceType(): WebResourceType 14026 14027Obtains the resource type of this resource request. 14028 14029**System capability**: SystemCapability.Web.Webview.Core 14030 14031**Return value** 14032 14033| Type | Description | 14034| ------ | ------------- | 14035| [WebResourceType](#webresourcetype12) | Resource type of the resource request.| 14036 14037**Example** 14038 14039For the complete sample code, see [onRequestStart](#onrequeststart12). 14040 14041### getFrameUrl<sup>12+</sup> 14042 14043getFrameUrl(): string 14044 14045Obtains the URL of the frame that triggers this request. 14046 14047**System capability**: SystemCapability.Web.Webview.Core 14048 14049**Return value** 14050 14051| Type | Description | 14052| ------ | ------------- | 14053| string | URL of the frame that triggers the request.| 14054 14055**Example** 14056 14057For the complete sample code, see [onRequestStart](#onrequeststart12). 14058 14059## WebSchemeHandlerResponse<sup>12+</sup> 14060 14061Represents a request response. You can create a response for an intercepted request, fill in custom content, and return the response to the **Web** component. 14062 14063### constructor<sup>12+</sup> 14064 14065constructor() 14066 14067A constructor used to create a **Response** object. 14068 14069**System capability**: SystemCapability.Web.Webview.Core 14070 14071**Example** 14072 14073```ts 14074// xxx.ets 14075import { webview } from '@kit.ArkWeb'; 14076import { BusinessError } from '@kit.BasicServicesKit'; 14077import { WebNetErrorList } from '@ohos.web.netErrorList'; 14078 14079@Entry 14080@Component 14081struct WebComponent { 14082 controller: webview.WebviewController = new webview.WebviewController(); 14083 schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); 14084 14085 build() { 14086 Column() { 14087 Button('response').onClick(() => { 14088 let response = new webview.WebSchemeHandlerResponse(); 14089 try { 14090 response.setUrl("http://www.example.com") 14091 response.setStatus(200) 14092 response.setStatusText("OK") 14093 response.setMimeType("text/html") 14094 response.setEncoding("utf-8") 14095 response.setHeaderByName("header1", "value1", false) 14096 response.setNetErrorCode(WebNetErrorList.NET_OK) 14097 console.log("[schemeHandler] getUrl:" + response.getUrl()) 14098 console.log("[schemeHandler] getStatus:" + response.getStatus()) 14099 console.log("[schemeHandler] getStatusText:" + response.getStatusText()) 14100 console.log("[schemeHandler] getMimeType:" + response.getMimeType()) 14101 console.log("[schemeHandler] getEncoding:" + response.getEncoding()) 14102 console.log("[schemeHandler] getHeaderByValue:" + response.getHeaderByName("header1")) 14103 console.log("[schemeHandler] getNetErrorCode:" + response.getNetErrorCode()) 14104 14105 } catch (error) { 14106 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14107 } 14108 }) 14109 Web({ src: 'https://www.example.com', controller: this.controller }) 14110 } 14111 } 14112} 14113 14114``` 14115 14116### setUrl<sup>12+</sup> 14117 14118setUrl(url: string): void 14119 14120Sets the redirection URL or the URL changed due to HSTS for this response. After the URL is set, a redirection to the new URL is triggered. 14121 14122**System capability**: SystemCapability.Web.Webview.Core 14123 14124**Parameters** 14125 14126| Name | Type | Mandatory | Description | 14127| --------| ------- | ---- | ---------------------------| 14128| url | string | Yes | URL to be redirected to.| 14129 14130**Example** 14131 14132For the complete sample code, see [constructor](#constructor12). 14133 14134**Error codes** 14135 14136For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14137 14138| ID| Error Message | 14139| -------- | ----------------------- | 14140| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 14141 14142### setNetErrorCode<sup>12+</sup> 14143 14144setNetErrorCode(code: WebNetErrorList): void 14145 14146Sets the network error code for this response. 14147 14148**System capability**: SystemCapability.Web.Webview.Core 14149 14150**Parameters** 14151 14152| Name | Type | Mandatory | Description | 14153| --------| ------- | ---- | ---------------------------| 14154| code | [WebNetErrorList](js-apis-netErrorList.md#webneterrorlist) | Yes | Network error code.| 14155 14156**Error codes** 14157 14158For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14159 14160| ID| Error Message | 14161| -------- | ----------------------- | 14162| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 14163 14164**Example** 14165 14166For the complete sample code, see [constructor](#constructor12). 14167 14168### setStatus<sup>12+</sup> 14169 14170setStatus(code: number): void 14171 14172Sets the HTTP status code for this response. 14173 14174**System capability**: SystemCapability.Web.Webview.Core 14175 14176**Parameters** 14177 14178| Name | Type | Mandatory | Description | 14179| --------| ------- | ---- | ---------------------------| 14180| code | number | Yes | HTTP status code.| 14181 14182**Error codes** 14183 14184For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14185 14186| ID| Error Message | 14187| -------- | ----------------------- | 14188| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 14189 14190**Example** 14191 14192For the complete sample code, see [constructor](#constructor12). 14193 14194### setStatusText<sup>12+</sup> 14195 14196setStatusText(text: string): void 14197 14198Sets the status text for this response. 14199 14200**System capability**: SystemCapability.Web.Webview.Core 14201 14202**Parameters** 14203 14204| Name | Type | Mandatory | Description | 14205| --------| ------- | ---- | ---------------------------| 14206| text | string | Yes | Status text.| 14207 14208**Error codes** 14209 14210For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14211 14212| ID| Error Message | 14213| -------- | ----------------------- | 14214| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 14215 14216**Example** 14217 14218For the complete sample code, see [constructor](#constructor12). 14219 14220### setMimeType<sup>12+</sup> 14221 14222setMimeType(type: string): void 14223 14224Sets the MIME type for this response. 14225 14226**System capability**: SystemCapability.Web.Webview.Core 14227 14228**Parameters** 14229 14230| Name | Type | Mandatory | Description | 14231| --------| ------- | ---- | ---------------------------| 14232| type | string | Yes | MIME type.| 14233 14234**Error codes** 14235 14236For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14237 14238| ID| Error Message | 14239| -------- | ----------------------- | 14240| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 14241 14242**Example** 14243 14244For the complete sample code, see [constructor](#constructor12). 14245 14246### setEncoding<sup>12+</sup> 14247 14248setEncoding(encoding: string): void 14249 14250Sets the character set for this response. 14251 14252**System capability**: SystemCapability.Web.Webview.Core 14253 14254**Parameters** 14255 14256| Name | Type | Mandatory | Description | 14257| --------| ------- | ---- | ---------------------------| 14258| encoding | string | Yes | Character set.| 14259 14260**Error codes** 14261 14262For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14263 14264| ID| Error Message | 14265| -------- | ----------------------- | 14266| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 14267 14268**Example** 14269 14270For the complete sample code, see [constructor](#constructor12). 14271 14272### setHeaderByName<sup>12+</sup> 14273 14274setHeaderByName(name: string, value: string, overwrite: boolean): void 14275 14276Sets the header information for this response. 14277 14278**System capability**: SystemCapability.Web.Webview.Core 14279 14280**Parameters** 14281 14282| Name | Type | Mandatory | Description | 14283| --------| ------- | ---- | ---------------------------| 14284| name | string | Yes | Name of the header.| 14285| value | string | Yes | Value of the header.| 14286| overwrite | boolean | Yes | Whether to override the existing header. The value **true** means to override the existing header, and **false** means the opposite.| 14287 14288**Error codes** 14289 14290For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14291 14292| ID| Error Message | 14293| -------- | ----------------------- | 14294| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 14295 14296**Example** 14297 14298For the complete sample code, see [constructor](#constructor12). 14299 14300### getUrl<sup>12+</sup> 14301 14302getUrl(): string 14303 14304Obtains the redirection URL or the URL changed due to HSTS. 14305Caution: To obtain the URL for JavaScriptProxy communication API authentication, use [getLastJavascriptProxyCallingFrameUrl<sup>12+</sup>](#getlastjavascriptproxycallingframeurl12). 14306 14307**System capability**: SystemCapability.Web.Webview.Core 14308 14309**Return value** 14310 14311| Type | Description | 14312| ------- | --------------------------------------- | 14313| string | Redirection URL or the URL changed due to HSTS.| 14314 14315**Example** 14316 14317For the complete sample code, see [constructor](#constructor12). 14318 14319### getNetErrorCode<sup>12+</sup> 14320 14321getNetErrorCode(): WebNetErrorList 14322 14323Obtains the network error code of this response. 14324 14325**System capability**: SystemCapability.Web.Webview.Core 14326 14327**Return value** 14328 14329| Type | Description | 14330| ------- | --------------------------------------- | 14331| [WebNetErrorList](js-apis-netErrorList.md#webneterrorlist) | Network error code of the response.| 14332 14333**Example** 14334 14335For the complete sample code, see [constructor](#constructor12). 14336 14337### getStatus<sup>12+</sup> 14338 14339getStatus(): number 14340 14341Obtains the HTTP status code of this response. 14342 14343**System capability**: SystemCapability.Web.Webview.Core 14344 14345**Return value** 14346 14347| Type | Description | 14348| ------- | --------------------------------------- | 14349| number | HTTP status code of the response.| 14350 14351**Example** 14352 14353For the complete sample code, see [constructor](#constructor12). 14354 14355### getStatusText<sup>12+</sup> 14356 14357getStatusText(): string 14358 14359Obtains the status text of this response. 14360 14361**System capability**: SystemCapability.Web.Webview.Core 14362 14363**Return value** 14364 14365| Type | Description | 14366| ------- | --------------------------------------- | 14367| string | Status text.| 14368 14369**Example** 14370 14371For the complete sample code, see [constructor](#constructor12). 14372 14373### getMimeType<sup>12+</sup> 14374 14375getMimeType(): string 14376 14377Obtains the MIME type of this response. 14378 14379**System capability**: SystemCapability.Web.Webview.Core 14380 14381**Return value** 14382 14383| Type | Description | 14384| ------- | --------------------------------------- | 14385| string | MIME type.| 14386 14387**Example** 14388 14389For the complete sample code, see [constructor](#constructor12). 14390 14391### getEncoding<sup>12+</sup> 14392 14393getEncoding(): string 14394 14395Obtains the character set of this response. 14396 14397**System capability**: SystemCapability.Web.Webview.Core 14398 14399**Return value** 14400 14401| Type | Description | 14402| ------- | --------------------------------------- | 14403| string | Character set.| 14404 14405**Example** 14406 14407For the complete sample code, see [constructor](#constructor12). 14408 14409### getHeaderByName<sup>12+</sup> 14410 14411getHeaderByName(name: string): string 14412 14413Obtains the character set of this response. 14414 14415**System capability**: SystemCapability.Web.Webview.Core 14416 14417**Parameters** 14418 14419| Name | Type | Mandatory| Description | 14420| ------- | ---------------- | ---- | -------------------- | 14421| name | string | Yes | Name of the header. | 14422 14423 14424**Return value** 14425 14426| Type | Description | 14427| ------- | --------------------------------------- | 14428| string | Value of the header.| 14429 14430**Example** 14431 14432For the complete sample code, see [constructor](#constructor12). 14433 14434## WebResourceHandler<sup>12+</sup> 14435 14436Represents a **WebResourceHandler** object, which can return custom response headers and response bodies to the **Web** component. 14437 14438### didReceiveResponse<sup>12+</sup> 14439 14440didReceiveResponse(response: WebSchemeHandlerResponse): void 14441 14442Sends a response header for this request. 14443 14444**System capability**: SystemCapability.Web.Webview.Core 14445 14446**Parameters** 14447 14448| Name | Type | Mandatory | Description | 14449| ---------------| ------- | ---- | ------------- | 14450| response | [WebSchemeHandlerResponse](#webschemehandlerresponse12) | Yes | Response to send.| 14451 14452**Error codes** 14453 14454For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14455 14456| ID| Error Message | 14457| -------- | ------------------------------------- | 14458| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 14459| 17100021 | The resource handler is invalid. | 14460 14461**Example** 14462 14463See [OnRequestStart](#onrequeststart12). 14464 14465### didReceiveResponseBody<sup>12+</sup> 14466 14467didReceiveResponseBody(data: ArrayBuffer): void 14468 14469Sends a response body for this request. 14470 14471**System capability**: SystemCapability.Web.Webview.Core 14472 14473**Parameters** 14474 14475| Name | Type | Mandatory | Description | 14476| ---------------| ------- | ---- | ------------- | 14477| data | ArrayBuffer | Yes | Response body.| 14478 14479**Error codes** 14480 14481For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14482 14483| ID| Error Message | 14484| -------- | ------------------------------------- | 14485| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 14486| 17100021 | The resource handler is invalid. | 14487 14488**Example** 14489 14490See [OnRequestStart](#onrequeststart12). 14491 14492### didFinish<sup>12+</sup> 14493 14494didFinish(): void 14495 14496Notifies the **Web** component that this request is completed and that no more data is available. Before calling this API, you need to call [didReceiveResponse](#didreceiveresponse12) to send a response header for this request. 14497 14498**System capability**: SystemCapability.Web.Webview.Core 14499 14500**Error codes** 14501 14502For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14503 14504| ID| Error Message | 14505| -------- | ------------------------------------- | 14506| 17100021 | The resource handler is invalid. | 14507 14508**Example** 14509 14510See [OnRequestStart](#onrequeststart12). 14511 14512### didFail<sup>12+</sup> 14513 14514didFail(code: WebNetErrorList): void 14515 14516Notifies the ArkWeb kernel that this request fails. Before calling this API, call [didReceiveResponse](#didreceiveresponse12) to send a response header to this request. 14517 14518**System capability**: SystemCapability.Web.Webview.Core 14519 14520**Parameters** 14521 14522| Name | Type | Mandatory | Description | 14523| --------| ------- | ---- | ---------------------------| 14524| code | [WebNetErrorList](js-apis-netErrorList.md#webneterrorlist) | Yes | Network error code.| 14525 14526**Error codes** 14527 14528For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14529 14530| ID| Error Message | 14531| -------- | ------------------------------------- | 14532| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 14533| 17100021 | The resource handler is invalid. | 14534 14535**System capability**: SystemCapability.Web.Webview.Core 14536 14537**Example** 14538 14539See [OnRequestStart](#onrequeststart12). 14540 14541## WebSchemeHandler<sup>12+</sup> 14542 14543Represents a **WebSchemeHandler** object used to intercept requests for a specific scheme. 14544 14545### onRequestStart<sup>12+</sup> 14546 14547onRequestStart(callback: (request: WebSchemeHandlerRequest, handler: WebResourceHandler) => boolean): void 14548 14549Called when a request starts. In this callback, you can determine whether to intercept the request. If **false** is returned, the request is not intercepted and the handler is invalid. If **true** is returned, the request is intercepted. 14550 14551**System capability**: SystemCapability.Web.Webview.Core 14552 14553**Parameters** 14554 14555| Name | Type | Mandatory| Description | 14556| -------- | -------------------- | ---- | ---------- | 14557| callback | (request: [WebSchemeHandlerRequest](#webschemehandlerrequest12), handler: [WebResourceHandler](#webresourcehandler12)) => boolean | Yes| Callback invoked when a request for the specified scheme starts. **request** represents a request. **handler** provides the custom response header and response body for the **Web** component. The return value indicates whether the request is intercepted.| 14558 14559**Error codes** 14560 14561For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14562 14563| ID| Error Message | 14564| -------- | ------------------------------------- | 14565| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 14566 14567**Example** 14568 14569```ts 14570// xxx.ets 14571import { webview } from '@kit.ArkWeb'; 14572import { BusinessError } from '@kit.BasicServicesKit'; 14573import { buffer } from '@kit.ArkTS'; 14574import { WebNetErrorList } from '@ohos.web.netErrorList'; 14575 14576@Entry 14577@Component 14578struct WebComponent { 14579 controller: webview.WebviewController = new webview.WebviewController(); 14580 schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); 14581 htmlData: string = "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>"; 14582 14583 build() { 14584 Column() { 14585 Web({ src: 'https://www.example.com', controller: this.controller }) 14586 .onControllerAttached(() => { 14587 try { 14588 this.schemeHandler.onRequestStart((request: webview.WebSchemeHandlerRequest, resourceHandler: webview.WebResourceHandler) => { 14589 console.log("[schemeHandler] onRequestStart"); 14590 try { 14591 console.log("[schemeHandler] onRequestStart url:" + request.getRequestUrl()); 14592 console.log("[schemeHandler] onRequestStart method:" + request.getRequestMethod()); 14593 console.log("[schemeHandler] onRequestStart referrer:" + request.getReferrer()); 14594 console.log("[schemeHandler] onRequestStart isMainFrame:" + request.isMainFrame()); 14595 console.log("[schemeHandler] onRequestStart hasGesture:" + request.hasGesture()); 14596 console.log("[schemeHandler] onRequestStart header size:" + request.getHeader().length); 14597 console.log("[schemeHandler] onRequestStart resource type:" + request.getRequestResourceType()); 14598 console.log("[schemeHandler] onRequestStart frame url:" + request.getFrameUrl()); 14599 let header = request.getHeader(); 14600 for (let i = 0; i < header.length; i++) { 14601 console.log("[schemeHandler] onRequestStart header:" + header[i].headerKey + " " + header[i].headerValue); 14602 } 14603 let stream = request.getHttpBodyStream(); 14604 if (stream) { 14605 console.log("[schemeHandler] onRequestStart has http body stream"); 14606 } else { 14607 console.log("[schemeHandler] onRequestStart has no http body stream"); 14608 } 14609 } catch (error) { 14610 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14611 } 14612 14613 if (request.getRequestUrl().endsWith("example.com")) { 14614 return false; 14615 } 14616 14617 let response = new webview.WebSchemeHandlerResponse(); 14618 try { 14619 response.setNetErrorCode(WebNetErrorList.NET_OK); 14620 response.setStatus(200); 14621 response.setStatusText("OK"); 14622 response.setMimeType("text/html"); 14623 response.setEncoding("utf-8"); 14624 response.setHeaderByName("header1", "value1", false); 14625 } catch (error) { 14626 console.error(`[schemeHandler] ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14627 } 14628 14629 // Before calling didFinish or didFail, call didReceiveResponse to send a response header to this request. 14630 let buf = buffer.from(this.htmlData) 14631 try { 14632 if (buf.length == 0) { 14633 console.log("[schemeHandler] length 0"); 14634 resourceHandler.didReceiveResponse(response); 14635 resourceHandler.didReceiveResponseBody(buf.buffer); 14636 resourceHandler.didFail(WebNetErrorList.ERR_FAILED); 14637 } else { 14638 console.log("[schemeHandler] length 1"); 14639 resourceHandler.didReceiveResponse(response); 14640 resourceHandler.didReceiveResponseBody(buf.buffer); 14641 resourceHandler.didFinish(); 14642 } 14643 } catch (error) { 14644 console.error(`[schemeHandler] ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14645 } 14646 return true; 14647 }) 14648 14649 this.schemeHandler.onRequestStop((request: webview.WebSchemeHandlerRequest) => { 14650 console.log("[schemeHandler] onRequestStop"); 14651 }); 14652 14653 this.controller.setWebSchemeHandler('https', this.schemeHandler); 14654 } catch (error) { 14655 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14656 } 14657 }) 14658 .javaScriptAccess(true) 14659 .domStorageAccess(true) 14660 } 14661 } 14662} 14663``` 14664### onRequestStop<sup>12+</sup> 14665 14666onRequestStop(callback: Callback\<WebSchemeHandlerRequest\>): void 14667 14668Called when a request is complete, under the prerequisite that the request is indicated as intercepted in the **onRequestStart** callback. Specifically, this callback is invoked in the following cases: 14669 146701. The **WebResourceHandler** object calls **didFail** or **didFinish**. 14671 146722. The request is interrupted due to other reasons. 14673 14674**System capability**: SystemCapability.Web.Webview.Core 14675 14676**Parameters** 14677 14678| Name | Type | Mandatory| Description | 14679| -------- | -------------------- | ---- | ---------- | 14680| callback | Callback\<[WebSchemeHandlerRequest](#webschemehandlerrequest12)\> | Yes | Callback invoked when the request is complete.| 14681 14682**Error codes** 14683 14684For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14685 14686| ID| Error Message | 14687| -------- | ------------------------------------- | 14688| 401 | Invalid input parameter. | 14689 14690**Example** 14691 14692For the complete sample code, see [onRequestStart](#onrequeststart12). 14693 14694## CacheOptions<sup>12+</sup> 14695 14696Represents a configuration object for precompiling JavaScript in the **Web** component to generate bytecode cache, which is designed to control the updating of the bytecode cache. 14697 14698**System capability**: SystemCapability.Web.Webview.Core 14699 14700| Name | Type | Readable| Writable|Description | 14701| ----------- | ------ | -----|------|------------------- | 14702| responseHeaders | Array<[WebHeader](#webheader)> | Yes| Yes| Array of response headers from the server when a JavaScript file is requested. They include information such as E-Tag or Last-Modified to identify the file version and determine whether the bytecode cache needs to be refreshed. | 14703 14704## PlaybackStatus<sup>12+</sup> 14705 14706Represents the playback status of the player, functioning as a parameter in [handleStatusChanged](#handlestatuschanged12). 14707 14708**System capability**: SystemCapability.Web.Webview.Core 14709 14710| Name| Value| Description| 14711|------|----|------| 14712| PAUSED | 0 | Playing.| 14713| PLAYING | 1 | Paused.| 14714 14715## NetworkState<sup>12+<sup> 14716 14717Describes the network status of the player. 14718 14719**System capability**: SystemCapability.Web.Webview.Core 14720 14721| Name| Value| Description| 14722|------|----|------| 14723| EMPTY | 0 | The player has not started downloading data.| 14724| IDLE | 1 | The player's network activity is idle. This could mean that the download of a media segment is complete, and the player is waiting to start downloading the next segment.| 14725| LOADING | 2 | The player is downloading media data.| 14726| NETWORK_ERROR | 3 | A network error occurs.| 14727 14728## ReadyState<sup>12+<sup> 14729 14730Enumerates the cache states of the player. 14731 14732**System capability**: SystemCapability.Web.Webview.Core 14733 14734| Name| Value| Description| 14735|------|----|------| 14736| HAVE_NOTHING | 0 | There is no data cached.| 14737| HAVE_METADATA | 1 | Only media metadata is cached.| 14738| HAVE_CURRENT_DATA | 2 | Data up to the current playback position is cached.| 14739| HAVE_FUTURE_DATA | 3 | Data beyond the current playback position is cached, but there might still be stutters during playback.| 14740| HAVE_ENOUGH_DATA | 4 | Sufficient data has been cached to ensure smooth playback.| 14741 14742## MediaError<sup>12+<sup> 14743 14744Enumerates the error types of the player. 14745 14746**System capability**: SystemCapability.Web.Webview.Core 14747 14748| Name| Value| Description| 14749|------|----|------| 14750| NETWORK_ERROR | 1 | Network error.| 14751| FORMAT_ERROR | 2 | Media format error.| 14752| DECODE_ERROR | 3 | Decoding error.| 14753 14754## NativeMediaPlayerHandler<sup>12+<sup> 14755 14756Represents a **NativeMediaPlayerHandler** object used as the parameter of the [CreateNativeMediaPlayerCallback](#createnativemediaplayercallback12) callback. 14757The application uses this object to report the player status to the ArkWeb engine. 14758 14759### handleStatusChanged<sup>12+<sup> 14760 14761handleStatusChanged(status: PlaybackStatus): void 14762 14763Called to notify the ArkWeb engine of the playback status of the player when the playback status changes. 14764 14765**System capability**: SystemCapability.Web.Webview.Core 14766 14767**Parameters** 14768 14769| Name| Type| Mandatory| Description| 14770|--------|------|------|------| 14771| status | [PlaybackStatus](#playbackstatus12) | Yes| Player status.| 14772 14773**Example** 14774 14775For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 14776 14777### handleVolumeChanged<sup>12+<sup> 14778 14779handleVolumeChanged(volume: number): void 14780 14781Called to notify the ArkWeb engine of the volume of the player when the volume changes. 14782 14783**System capability**: SystemCapability.Web.Webview.Core 14784 14785**Parameters** 14786 14787| Name| Type| Mandatory| Description| 14788|--------|------|------|------| 14789| volume | number | Yes| Volume of the player.| 14790 14791**Example** 14792 14793For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 14794 14795### handleMutedChanged<sup>12+<sup> 14796 14797handleMutedChanged(muted: boolean): void 14798 14799Called to notify the ArkWeb engine of the muted status of the player when the muted status changes. 14800 14801**System capability**: SystemCapability.Web.Webview.Core 14802 14803**Parameters** 14804 14805| Name| Type| Mandatory| Description| 14806|--------|------|------|------| 14807| muted | boolean | Yes| Whether the player is muted.| 14808 14809**Example** 14810 14811For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 14812 14813### handlePlaybackRateChanged<sup>12+<sup> 14814 14815handlePlaybackRateChanged(playbackRate: number): void 14816 14817Called to notify the ArkWeb engine of the playback rate of the player when the playback rate changes. 14818 14819**System capability**: SystemCapability.Web.Webview.Core 14820 14821**Parameters** 14822 14823| Name| Type| Mandatory| Description| 14824|--------|------|------|------| 14825| playbackRate | number | Yes| Playback rate.| 14826 14827**Example** 14828 14829For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 14830 14831### handleDurationChanged<sup>12+<sup> 14832 14833handleDurationChanged(duration: number): void 14834 14835Called to notify the ArkWeb engine of the total duration of the media. 14836 14837**System capability**: SystemCapability.Web.Webview.Core 14838 14839**Parameters** 14840 14841| Name| Type| Mandatory| Description| 14842|--------|------|------|------| 14843| duration | number | Yes| Total duration of the media. Unit: second.| 14844 14845**Example** 14846 14847For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 14848 14849### handleTimeUpdate<sup>12+<sup> 14850 14851handleTimeUpdate(currentPlayTime: number): void 14852 14853Called to notify the ArkWeb engine of the playback progress when the playback progress changes. 14854 14855**System capability**: SystemCapability.Web.Webview.Core 14856 14857**Parameters** 14858 14859| Name| Type| Mandatory| Description| 14860|--------|------|------|------| 14861| currentPlayTime | number | Yes| Current progress. Unit: second. | 14862 14863**Example** 14864 14865For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 14866 14867### handleBufferedEndTimeChanged<sup>12+<sup> 14868 14869handleBufferedEndTimeChanged(bufferedEndTime: number): void 14870 14871Called to notify the ArkWeb engine of the buffer time when the buffer time changes. 14872 14873**System capability**: SystemCapability.Web.Webview.Core 14874 14875**Parameters** 14876 14877| Name| Type| Mandatory| Description| 14878|--------|------|------|------| 14879| bufferedEndTime | number | Yes| Duration of media data in the buffer.| 14880 14881**Example** 14882 14883For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 14884 14885### handleEnded<sup>12+<sup> 14886 14887handleEnded(): void 14888 14889Called to notify the ArkWeb engine that the media playback ends. 14890 14891**System capability**: SystemCapability.Web.Webview.Core 14892 14893**Example** 14894 14895For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 14896 14897### handleNetworkStateChanged<sup>12+<sup> 14898 14899handleNetworkStateChanged(state: NetworkState): void 14900 14901Called to notify the ArkWeb engine of the network status of the player when the network status changes. 14902 14903**System capability**: SystemCapability.Web.Webview.Core 14904 14905**Parameters** 14906 14907| Name| Type| Mandatory| Description| 14908|--------|------|------|------| 14909| state | [NetworkState](#networkstate12) | Yes| Network status of the player.| 14910 14911**Example** 14912 14913For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 14914 14915### handleReadyStateChanged<sup>12+<sup> 14916 14917handleReadyStateChanged(state: ReadyState): void 14918 14919Called to notify the ArkWeb engine of the cache status of the player when the cache status changes. 14920 14921**System capability**: SystemCapability.Web.Webview.Core 14922 14923**Parameters** 14924 14925| Name| Type| Mandatory| Description| 14926|--------|------|------|------| 14927| state | [ReadyState](#readystate12) | Yes| Cache status of the player.| 14928 14929**Example** 14930 14931For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 14932 14933### handleFullscreenChanged<sup>12+<sup> 14934 14935handleFullscreenChanged(fullscreen: boolean): void 14936 14937Called to notify the ArkWeb engine of the full screen status of the player when the full screen status changes. 14938 14939**System capability**: SystemCapability.Web.Webview.Core 14940 14941**Parameters** 14942 14943| Name| Type| Mandatory| Description| 14944|--------|------|------|------| 14945| fullscreen | boolean | Yes| Whether the player is in full screen.| 14946 14947**Example** 14948 14949For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 14950 14951### handleSeeking<sup>12+<sup> 14952 14953handleSeeking(): void 14954 14955Called to notify the ArkWeb engine that the player enters the seek state. 14956 14957**System capability**: SystemCapability.Web.Webview.Core 14958 14959**Example** 14960 14961For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 14962 14963### handleSeekFinished<sup>12+<sup> 14964 14965handleSeekFinished(): void 14966 14967Called to notify the ArkWeb engine that the seek operation is complete. 14968 14969**System capability**: SystemCapability.Web.Webview.Core 14970 14971**Example** 14972 14973For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 14974 14975### handleError<sup>12+<sup> 14976 14977handleError(error: MediaError, errorMessage: string): void 14978 14979Called to notify the ArkWeb engine that an error occurs with the player. 14980 14981**System capability**: SystemCapability.Web.Webview.Core 14982 14983**Parameters** 14984 14985| Name| Type| Mandatory| Description| 14986|--------|------|------|------| 14987| error | [MediaError](#mediaerror12) | Yes| Error object type.| 14988| errorMessage | string | Yes| Error message.| 14989 14990**Example** 14991 14992For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 14993 14994### handleVideoSizeChanged<sup>12+<sup> 14995 14996handleVideoSizeChanged(width: number, height: number): void 14997 14998Called to notify the ArkWeb engine of the video size of the player. 14999 15000**System capability**: SystemCapability.Web.Webview.Core 15001 15002**Parameters** 15003 15004| Name| Type| Mandatory| Description| 15005|--------|------|------|------| 15006| width | number | Yes| Video width.| 15007| height | number | Yes| Video height.| 15008 15009**Example** 15010 15011For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15012 15013## SuspendType<sup>12+<sup> 15014 15015Enumerates the suspension types of the player. 15016 15017**System capability**: SystemCapability.Web.Webview.Core 15018 15019| Name| Value| Description| 15020|------|----|------| 15021| ENTER_BACK_FORWARD_CACHE | 0 | The page enters the BFCache.| 15022| ENTER_BACKGROUND | 1 | The page is displayed in the background.| 15023| AUTO_CLEANUP | 2 | The page is automatically cleaned up by the system.| 15024 15025## NativeMediaPlayerBridge<sup>12+<sup> 15026 15027Implements a **NativeMediaPlayerBridge** object, which is the return value of the [CreateNativeMediaPlayerCallback](#createnativemediaplayercallback12) callback. 15028It is an interface class that acts as a bridge between the web media player and the ArkWeb engine. 15029The ArkWeb engine uses an object of this interface class to control the player created by the application to take over web page media. 15030 15031### updateRect<sup>12+<sup> 15032 15033updateRect(x: number, y: number, width: number, height: number): void 15034 15035Updates the surface position information. 15036 15037**System capability**: SystemCapability.Web.Webview.Core 15038 15039**Parameters** 15040 15041| Name| Type| Mandatory| Description| 15042|--------|------|------|------| 15043| x | number | Yes| X coordinate of the surface relative to the web component.| 15044| y | number | Yes| Y coordinate of the surface relative to the web component.| 15045| width | number | Yes| Width of the surface.| 15046| height | number | Yes| Height of the surface.| 15047 15048**Example** 15049 15050For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15051 15052### play<sup>12+<sup> 15053 15054play(): void 15055 15056Plays this video. 15057 15058**System capability**: SystemCapability.Web.Webview.Core 15059 15060**Example** 15061 15062For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15063 15064### pause<sup>12+<sup> 15065 15066pause(): void 15067 15068Pauses playback. 15069 15070**System capability**: SystemCapability.Web.Webview.Core 15071 15072**Example** 15073 15074For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15075 15076### seek<sup>12+<sup> 15077 15078seek(targetTime: number): void 15079 15080Seeks to a specific time point in the media. 15081 15082**System capability**: SystemCapability.Web.Webview.Core 15083 15084**Parameters** 15085 15086| Name| Type| Mandatory| Description| 15087|--------|------|------|------| 15088| targetTime | number | Yes| Target time point. Unit: second.| 15089 15090**Example** 15091 15092For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15093 15094### setVolume<sup>12+<sup> 15095 15096setVolume(volume: number): void 15097 15098Sets the playback volume. 15099The value range is [0, 1.0]. 15100 15101**Parameters** 15102 15103| Name| Type| Mandatory| Description| 15104|--------|------|------|------| 15105| volume | number | Yes| Playback volume. The value range is [0, 1.0]. The value **0** indicates mute, and **1.0** indicates the maximum volume level.| 15106 15107**System capability**: SystemCapability.Web.Webview.Core 15108 15109**Example** 15110 15111For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15112 15113### setMuted<sup>12+<sup> 15114 15115setMuted(muted: boolean): void 15116 15117Sets the muted status. 15118 15119**System capability**: SystemCapability.Web.Webview.Core 15120 15121**Parameters** 15122 15123| Name| Type| Mandatory| Description| 15124|--------|------|------|------| 15125| muted | boolean | Yes| Whether to mute the player.| 15126 15127**Example** 15128 15129For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15130 15131### setPlaybackRate<sup>12+<sup> 15132 15133setPlaybackRate(playbackRate: number): void 15134 15135Sets the playback rate. 15136The value range is [0, 10.0]. 15137 15138**System capability**: SystemCapability.Web.Webview.Core 15139 15140**Parameters** 15141 15142| Name| Type| Mandatory| Description| 15143|--------|------|------|------| 15144| playbackRate | number | Yes| Playback rate. The value range is [0, 10.0]. The value **1** indicates the original speed of playback.| 15145 15146**Example** 15147 15148For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15149 15150### release<sup>12+<sup> 15151 15152release(): void 15153 15154Releases this player. 15155 15156**System capability**: SystemCapability.Web.Webview.Core 15157 15158**Example** 15159 15160For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15161 15162### enterFullscreen<sup>12+<sup> 15163 15164enterFullscreen(): void 15165 15166Enables the player to enter full screen mode. 15167 15168**System capability**: SystemCapability.Web.Webview.Core 15169 15170**Example** 15171 15172For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15173 15174### exitFullscreen<sup>12+<sup> 15175 15176exitFullscreen(): void 15177 15178Enables the player to exit full screen mode. 15179 15180**System capability**: SystemCapability.Web.Webview.Core 15181 15182**Example** 15183 15184For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15185 15186### resumePlayer<sup>12+<sup> 15187 15188resumePlayer?(): void 15189 15190Resumes the player and its status information. 15191 15192**System capability**: SystemCapability.Web.Webview.Core 15193 15194**Example** 15195 15196For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15197 15198### suspendPlayer<sup>12+<sup> 15199 15200suspendPlayer?(type: SuspendType): void 15201 15202Suspends the player and save its status information. 15203 15204**System capability**: SystemCapability.Web.Webview.Core 15205 15206**Parameters** 15207 15208| Name| Type| Mandatory| Description| 15209|--------|------|------|------| 15210| type | [SuspendType](#suspendtype12) | Yes| Suspension type of the player.| 15211 15212**Example** 15213 15214For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15215 15216## MediaType<sup>12+<sup> 15217 15218Enumerates the media types. 15219 15220**System capability**: SystemCapability.Web.Webview.Core 15221 15222| Name| Value| Description| 15223|------|----|------| 15224| VIDEO | 0 | Video.| 15225| AUDIO | 1 | Audio.| 15226 15227## SourceType<sup>12+<sup> 15228 15229Enumerates the media source types. 15230 15231**System capability**: SystemCapability.Web.Webview.Core 15232 15233| Name| Value| Description| 15234|------|----|------| 15235| URL | 0 | URL.| 15236| MSE | 1 | Blob.| 15237 15238## MediaSourceInfo<sup>12+<sup> 15239 15240Provides the information about the media source. 15241 15242**System capability**: SystemCapability.Web.Webview.Core 15243 15244| Name| Type| Mandatory| Description| 15245|------|------|------|------| 15246| type | [SourceType](#sourcetype12) | Yes| Type of the media source.| 15247| source | string | Yes| Address of the media source.| 15248| format | string | Yes| Format of the media source, which may be empty. You need to determine the format by yourself.| 15249 15250## NativeMediaPlayerSurfaceInfo<sup>12+<sup> 15251 15252Provides the surface information used for same-layer rendering [when the application takes over the media playback functionality of the web page](ts-basic-components-web.md#enablenativemediaplayer12). 15253 15254**System capability**: SystemCapability.Web.Webview.Core 15255 15256| Name| Type| Mandatory| Description| 15257|------|------|------|------| 15258| id | string | Yes| Surface ID, which is the **psurfaceid** of the native image used for rendering at the same layer.<br>For details, see [NativeEmbedDataInfo](ts-basic-components-web.md#nativeembeddatainfo11).| 15259| rect | [RectEvent](#rectevent12) | Yes| Position of the surface.| 15260 15261## Preload<sup>12+<sup> 15262 15263Defines how the player preloads media data. 15264 15265**System capability**: SystemCapability.Web.Webview.Core 15266 15267| Name| Value| Description| 15268|------|----|------| 15269| NONE | 0 | No media data is preloaded.| 15270| METADATA | 1 | Only the metadata of the media is preloaded.| 15271| AUTO | 2 | A sufficient amount of media data is preloaded to ensure smooth playback| 15272 15273## MediaInfo<sup>12+<sup> 15274 15275Represents a **MediaInfo** object used as a parameter of the [CreateNativeMediaPlayerCallback](#createnativemediaplayercallback12) callback. 15276The object contains information about media on the web page. The application may create, based on the information, a player that takes over media playback of the web page . 15277 15278**System capability**: SystemCapability.Web.Webview.Core 15279 15280| Name| Type| Mandatory| Description| 15281|------|------|------|------| 15282| embedID | string | Yes| ID of **\<video>** or **\<audio>** on the web page.| 15283| mediaType | [MediaType](#mediatype12) | Yes| Type of the media.| 15284| mediaSrcList | [MediaSourceInfo](#mediasourceinfo12)[] | Yes| Source of the media. There may be multiple sources. The application needs to select a supported source to play.| 15285| surfaceInfo | [NativeMediaPlayerSurfaceInfo](#nativemediaplayersurfaceinfo12) | Yes| Surface information used for same-layer rendering.| 15286| controlsShown | boolean | Yes| Whether the **controls** attribute exists in **\<video>** or **\<audio>**.| 15287| controlList | string[] | Yes| Value of the **controlslist** attribute in **\<video>** or **\<audio>**.| 15288| muted | boolean | Yes| Whether to mute the player.| 15289| posterUrl | string | Yes| URL of a poster.| 15290| preload | [Preload](#preload12) | Yes| Whether preloading is required.| 15291| headers | Record\<string, string\> | Yes| HTTP headers that need to be included in the player's request for media resources.| 15292| attributes | Record\<string, string\> | Yes| Attributes in **\<video>** or **\<audio>**.| 15293 15294 15295## CreateNativeMediaPlayerCallback<sup>12+<sup> 15296 15297type CreateNativeMediaPlayerCallback = (handler: NativeMediaPlayerHandler, mediaInfo: MediaInfo) => NativeMediaPlayerBridge 15298 15299Represents a **CreateNativeMediaPlayerCallback** object used as a parameter of the [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12) callback. 15300This object is used to create a player to take over media playback of the web page. 15301 15302**System capability**: SystemCapability.Web.Webview.Core 15303 15304**Parameters** 15305 15306| Name| Type| Mandatory| Description| 15307|--------|------|------|------| 15308| handler | [NativeMediaPlayerHandler](#nativemediaplayerhandler12) | Yes| Object used to report the player status to the ArkWeb engine.| 15309| mediaInfo | [MediaInfo](#mediainfo12) | Yes| Information about the media on the web page.| 15310 15311**Return value** 15312 15313| Type| Description| 15314|------|------| 15315| [NativeMediaPlayerBridge](#nativemediaplayerbridge12) | Instance of the interface class between the player that takes over web media and the ArkWeb kernel.<br>The application needs to implement the interface class.<br> Object used by the ArkWeb engine to control the player created by the application to take over web page media.<br>If the application returns **null**, the application does not take over the media playback, and the media will be played by the ArkWeb kernel.| 15316 15317**Example** 15318 15319For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15320 15321## OfflineResourceMap<sup>12+</sup> 15322 15323Implements an **OfflineResourceMap** object, which is used to set up information related to local offline resources that will be injected into memory cache through the [injectOfflineResources](#injectofflineresources12) API. The ArkWeb engine will generate resource caches based on this information and control the validity period of the cache accordingly. 15324 15325**System capability**: SystemCapability.Web.Webview.Core 15326 15327| Name | Type | Readable| Writable|Description | 15328| ----------- | ------ | -----|------|------------------- | 15329| urlList | Array\<string\> | Yes | Yes | List of network addresses of the local offline resources. The first item in the list is used as the resources' origin. If only one network address is provided, this single address is used for the resources' origin. The URL supports only the HTTP and HTTPS protocols and contains a maximum of 2048 characters. | 15330| resource | Uint8Array | Yes | Yes | Content of a local offline resource. | 15331| responseHeaders | Array<[WebHeader](#webheader)> | Yes | Yes | HTTP response headers corresponding to the resources. The **Cache-Control** or **Expires** response header is used to control the validity period of the resource in the memory cache. If neither of the headers is provided, a default validity time of 86400 seconds (1 day) will be applied. The **Content-Type** response header is used to define the MIME type of the resource. For resources of type MODULE_JS, a valid MIME type must be provided. For other types, the MIME type is optional, with no default value. A non-standard MIME type can lead to the resource being invalidated in the memory cache. If a **script** tag in the web page uses the **crossorigin** attribute, the **Cross-Origin** response header must be set in the **responseHeaders** parameter of the API. The value for this header should be **anonymous** or **use-credentials**. | 15332| type | [OfflineResourceType](#offlineresourcetype12) | Yes | Yes | Resource type. Currently, only the JavaScript, image, and CSS types are supported. | 15333 15334## OfflineResourceType<sup>12+</sup> 15335 15336Represents the local offline resource type corresponding to an [OfflineResourceMap](#offlineresourcemap12) object. 15337 15338**System capability**: SystemCapability.Web.Webview.Core 15339 15340| Name | Value| Description | 15341| ------------ | -- |--------------------------------- | 15342| IMAGE | 0 | Resource of the image type.| 15343| CSS | 1 | Resource of the CSS type.| 15344| CLASSIC_JS | 2 | Javascript resource loaded through the <script src="" /\> tag.| 15345| MODULE_JS | 3 |Javascript resource loaded through the <script src="" type="module" /\> tag.| 15346 15347## WebResourceType<sup>12+</sup> 15348 15349Enumerates the types of requested resources. 15350 15351**System capability**: SystemCapability.Web.Webview.Core 15352 15353| Name | Value| Description | 15354| ------------ | -- |--------------------------------- | 15355| MAIN_FRAME | 0 | Top-level page.| 15356| SUB_FRAME | 1 | Frame or Iframe.| 15357| STYLE_SHEET | 2 | CSS style sheet.| 15358| SCRIPT | 3 | External script.| 15359| IMAGE | 4 | Image (JPG, GIF, PNG, or other format).| 15360| FONT_RESOURCE | 5 | Font.| 15361| SUB_RESOURCE | 6 | Other sub-resource. If the type is unknown, it is used as the default type.| 15362| OBJECT | 7 | Object (or embed) tag of the plug-in, or the resource requested by the plug-in.| 15363| MEDIA | 8 | Media resource.| 15364| WORKER | 9 | Main resource of a dedicated worker thread.| 15365| SHARED_WORKER | 10 | Main resource of a shared worker thread.| 15366| PREFETCH | 11 | Explicit prefetch request.| 15367| FAVICON | 12 | Website icon.| 15368| XHR | 13 | XMLHttpRequest.| 15369| PING | 14 | <a ping\>/sendBeacon ping request.| 15370| SERVICE_WORKER | 15 | Main resource of a service worker.| 15371| CSP_REPORT | 16 | Report of Content Security Policy violation.| 15372| PLUGIN_RESOURCE | 17 | Resource requested by the plug-in.| 15373| NAVIGATION_PRELOAD_MAIN_FRAME | 19 | Main frame redirection request that triggers service worker preloading.| 15374| NAVIGATION_PRELOAD_SUB_FRAME | 20 | Subframe redirection request that triggers service worker preloading.| 15375 15376## RectEvent<sup>12+<sup> 15377 15378Defines a rectangle. 15379 15380**System capability**: SystemCapability.Web.Webview.Core 15381 15382| Name | Type | Readable| Writable| Description | 15383| -------------- | --------- | ---- | ---- | ---------------------------- | 15384| x | number | Yes | Yes | X-axis coordinate of the upper left corner of the rectangle. | 15385| y | number | Yes | Yes | Y-axis coordinate of the upper left corner of the rectangle. | 15386| width | number | Yes | Yes | Width of the rectangle. | 15387| height | number | Yes | Yes | Height of the rectangle. | 15388 15389## BackForwardCacheSupportedFeatures<sup>12+<sup> 15390 15391Adds a page that uses any of the following features to the back-forward cache. 15392 15393**System capability**: SystemCapability.Web.Webview.Core 15394 15395| Name| Type| Mandatory| Description| 15396|------|------|------|------| 15397| nativeEmbed | bool | Yes| Whether to add a page that uses same-layer rendering to the back-forward cache. The default value is **false**. When the value is set to **true**, you need to maintain the lifecycle of native controls created for the same-layer rendering elements to avoid resource leak.| 15398| mediaTakeOver | bool | Yes| Whether to add a page that takes over media playback to the back-forward cache. The default value is **false**. When the value is set to **true**, you need to maintain the lifecycle of native controls created for video elements to avoid resource leak.| 15399 15400## BackForwardCacheOptions<sup>12+<sup> 15401 15402Represents a configuration object for the back-forward cache, which is used to set back-forward cache options of the **Web** component. 15403 15404**System capability**: SystemCapability.Web.Webview.Core 15405 15406| Name| Type| Mandatory| Description| 15407|------|------|------|------| 15408| size | number | Yes| The maximum number of pages that can be cached in a **Web** component. The default value is **1**, and the maximum value is **50**. If this parameter is set to **0** or a negative value, the back-forward cache is disabled. The web reclaims the cache for memory pressure.| 15409| timeToLive | number | Yes| The time that a **Web** component allows a page to stay in the back-forward cache. The default value is **600**, in seconds. If this parameter is set to **0** or a negative value, the back-forward cache is disabled.| 15410 15411## AdsBlockManager<sup>12+</sup> 15412 15413Implements an **AdsBlockManager** instance to set custom ad blocking configurations in the **Web** components and disable the ad blocking feature for specific websites. Each application's **Web** components share an **AdsBlockManager** instance. 15414 15415### setAdsBlockRules<sup>12+</sup> 15416 15417static setAdsBlockRules(rulesFile: string, replace: boolean): void 15418 15419Sets a custom ad blocking rule file that conforms to the universal EasyList syntax in the **Web** components. 15420 15421> **NOTE** 15422> 15423> The ad blocking rules set by this API will be persistently stored after successful internal parsing; you do not need to set them again after the application is restarted. 15424 15425**System capability**: SystemCapability.Web.Webview.Core 15426 15427**Parameters** 15428 15429| Name | Type | Mandatory| Description | 15430| ---------- | ------ | ---- | -------------------------------- | 15431| rulesFile | string | Yes | Path to the rule file that conforms to the universal EasyList syntax. The application needs to have read permission for this file.| 15432| replace | boolean | Yes | Whether to replace the built-in default rules. The value **true** indicates that the built-in default rules will be forcibly replaced; **false** indicates that the custom rules will work alongside the built-in default rules.| 15433 15434**Error codes** 15435 15436For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15437 15438| ID| Error Message | 15439| -------- | ----------------------- | 15440| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 15441 15442**Example** 15443 15444```ts 15445// xxx.ets 15446import { webview } from '@kit.ArkWeb'; 15447import { picker, fileUri } from '@kit.CoreFileKit'; 15448 15449// This example demonstrates how to click a button to open an EasyList-compliant rule file through filepicker and set the file in the Web component. 15450@Entry 15451@Component 15452struct WebComponent { 15453 controller: webview.WebviewController = new webview.WebviewController(); 15454 15455 build() { 15456 Row() { 15457 Flex() { 15458 Button({ type: ButtonType.Capsule }) { 15459 Text("setAdsBlockRules") 15460 } 15461 .onClick(() => { 15462 try { 15463 let documentSelectionOptions: ESObject = new picker.DocumentSelectOptions(); 15464 let documentPicker: ESObject = new picker.DocumentViewPicker(); 15465 documentPicker.select(documentSelectionOptions).then((documentSelectResult: ESObject) => { 15466 if (documentSelectResult && documentSelectResult.length > 0) { 15467 let fileRealPath = new fileUri.FileUri(documentSelectResult[0]); 15468 console.info('DocumentViewPicker.select successfully, uri: ' + fileRealPath); 15469 webview.AdsBlockManager.setAdsBlockRules(fileRealPath.path, true); 15470 } 15471 }) 15472 } catch (err) { 15473 console.error('DocumentViewPicker.select failed with err:' + err); 15474 } 15475 }) 15476 } 15477 } 15478 } 15479} 15480``` 15481 15482### addAdsBlockDisallowedList<sup>12+</sup> 15483 15484static addAdsBlockDisallowedList(domainSuffixes: Array\<string\>): void 15485 15486Adds an array of domain names to the disallowed list of this **AdsBlockManager** object. When the ad blocking feature is enabled, ad blocking for these websites will be disabled. 15487 15488> **NOTE** 15489> 15490> The domain name set by this API is not persistent; they need to be set again after the application is restarted. 15491> 15492> The ad blocking feature matches website URLs based on the suffix. For example, if the disallowed list contains **'example.com'** or **'www.example.com'**, then ad blocking will be disabled for sites **https://www.example.com** and **https://m.example.com**. 15493 15494**System capability**: SystemCapability.Web.Webview.Core 15495 15496**Parameters** 15497 15498| Name | Type | Mandatory| Description | 15499| ---------- | ------ | ---- | -------------------------------- | 15500| domainSuffixes | Array\<string\> | Yes | Array of domain names, for example, ['example.com', 'abcd.efg.com'].| 15501 15502**Error codes** 15503 15504For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15505 15506| ID| Error Message | 15507| -------- | ----------------------- | 15508| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 15509 15510**Example** 15511 15512```ts 15513// xxx.ets 15514import { webview } from '@kit.ArkWeb'; 15515 15516// This example demonstrates how to click a button to add an array of domain names to the disallowed list. 15517@Entry 15518@Component 15519struct WebComponent { 15520 main_url: string = 'https://www.example.com'; 15521 text_input_controller: TextInputController = new TextInputController(); 15522 controller: webview.WebviewController = new webview.WebviewController(); 15523 @State input_text: string = 'https://www.example.com'; 15524 15525 build() { 15526 Column() { 15527 Row() { 15528 Flex() { 15529 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 15530 .id("input_url") 15531 .height(40) 15532 .margin(5) 15533 .borderColor(Color.Blue) 15534 .onChange((value: string) => { 15535 this.input_text = value; 15536 }) 15537 15538 Button({type: ButtonType.Capsule}) { Text("Go") } 15539 .onClick(() => { 15540 this.controller.loadUrl(this.input_text); 15541 }) 15542 15543 Button({type: ButtonType.Capsule}) { Text("addAdsBlockDisallowedList") } 15544 .onClick(() => { 15545 let arrDomainSuffixes = new Array<string>(); 15546 arrDomainSuffixes.push('example.com'); 15547 arrDomainSuffixes.push('abcdefg.cn'); 15548 webview.AdsBlockManager.addAdsBlockDisallowedList(arrDomainSuffixes); 15549 }) 15550 } 15551 } 15552 Web({ src: this.main_url, controller: this.controller }) 15553 .onControllerAttached(()=>{ 15554 this.controller.enableAdsBlock(true); 15555 }) 15556 } 15557 } 15558} 15559``` 15560 15561### removeAdsBlockDisallowedList<sup>12+</sup> 15562 15563static removeAdsBlockDisallowedList(domainSuffixes: Array\<string\>): void 15564 15565Removes an array of domain names from the disallowed list of this **AdsBlockManager** object. 15566 15567> **NOTE** 15568> 15569> The domain name set by this API is not persistent; they need to be set again after the application is restarted. Removing an entry that does not exist does not trigger an exception. 15570 15571**System capability**: SystemCapability.Web.Webview.Core 15572 15573**Parameters** 15574 15575| Name | Type | Mandatory| Description | 15576| ---------- | ------ | ---- | -------------------------------- | 15577| domainSuffixes | Array\<string\> | Yes | Array of domain names, for example, ['example.com', 'abcd.efg.com'].| 15578 15579**Error codes** 15580 15581For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15582 15583| ID| Error Message | 15584| -------- | ----------------------- | 15585| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 15586 15587**Example** 15588 15589```ts 15590// xxx.ets 15591import { webview } from '@kit.ArkWeb'; 15592 15593// This example demonstrates how to click a button to remove an array of domain names from the disallowed list. 15594@Entry 15595@Component 15596struct WebComponent { 15597 main_url: string = 'https://www.example.com'; 15598 text_input_controller: TextInputController = new TextInputController(); 15599 controller: webview.WebviewController = new webview.WebviewController(); 15600 @State input_text: string = 'https://www.example.com'; 15601 15602 build() { 15603 Column() { 15604 Row() { 15605 Flex() { 15606 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 15607 .id("input_url") 15608 .height(40) 15609 .margin(5) 15610 .borderColor(Color.Blue) 15611 .onChange((value: string) => { 15612 this.input_text = value; 15613 }) 15614 15615 Button({type: ButtonType.Capsule}) { Text("Go") } 15616 .onClick(() => { 15617 this.controller.loadUrl(this.input_text); 15618 }) 15619 15620 Button({type: ButtonType.Capsule}) { Text("removeAdsBlockDisallowedList") } 15621 .onClick(() => { 15622 let arrDomainSuffixes = new Array<string>(); 15623 arrDomainSuffixes.push('example.com'); 15624 arrDomainSuffixes.push('abcdefg.cn'); 15625 webview.AdsBlockManager.removeAdsBlockDisallowedList(arrDomainSuffixes); 15626 }) 15627 } 15628 } 15629 Web({ src: this.main_url, controller: this.controller }) 15630 .onControllerAttached(()=>{ 15631 this.controller.enableAdsBlock(true); 15632 }) 15633 } 15634 } 15635} 15636``` 15637 15638### clearAdsBlockDisallowedList<sup>12+</sup> 15639 15640static clearAdsBlockDisallowedList(): void 15641 15642Clears the disallowed list of this **AdsBlockManager** object. 15643 15644**System capability**: SystemCapability.Web.Webview.Core 15645 15646**Example** 15647 15648```ts 15649// xxx.ets 15650import { webview } from '@kit.ArkWeb'; 15651 15652@Entry 15653@Component 15654struct WebComponent { 15655 main_url: string = 'https://www.example.com'; 15656 text_input_controller: TextInputController = new TextInputController(); 15657 controller: webview.WebviewController = new webview.WebviewController(); 15658 @State input_text: string = 'https://www.example.com'; 15659 15660 build() { 15661 Column() { 15662 Row() { 15663 Flex() { 15664 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 15665 .id("input_url") 15666 .height(40) 15667 .margin(5) 15668 .borderColor(Color.Blue) 15669 .onChange((value: string) => { 15670 this.input_text = value; 15671 }) 15672 15673 Button({type: ButtonType.Capsule}) { Text("Go") } 15674 .onClick(() => { 15675 this.controller.loadUrl(this.input_text); 15676 }) 15677 15678 Button({type: ButtonType.Capsule}) { Text("clearAdsBlockDisallowedList") } 15679 .onClick(() => { 15680 webview.AdsBlockManager.clearAdsBlockDisallowedList(); 15681 }) 15682 } 15683 } 15684 Web({ src: this.main_url, controller: this.controller }) 15685 .onControllerAttached(()=>{ 15686 this.controller.enableAdsBlock(true); 15687 }) 15688 } 15689 } 15690} 15691``` 15692 15693### addAdsBlockAllowedList<sup>12+</sup> 15694 15695static addAdsBlockAllowedList(domainSuffixes: Array\<string\>): void 15696 15697Adds an array of domain names to the allowed list of this **AdsBlockManager** object. This API is typically used to re-enable ad blocking for certain websites that were previously added to the disallowed list. 15698 15699> **NOTE** 15700> 15701> The domain name set by this API is not persistent; they need to be set again after the application is restarted. 15702> 15703> The priority of the allowed list is higher than that of the disallowed list. For example, if the disallowed list includes **['example.com']**, all pages under the **example.com** domain will have their ad blocking disabled; to re-enable ad blocking for the subdomain **news.example.com**, you can use the **addAdsBlockAllowedList(['news.example.com'])** API. 15704 15705**System capability**: SystemCapability.Web.Webview.Core 15706 15707**Parameters** 15708 15709| Name | Type | Mandatory| Description | 15710| ---------- | ------ | ---- | -------------------------------- | 15711| domainSuffixes | Array\<string\> | Yes | Array of domain names, for example, ['example.com', 'abcd.efg.com'].| 15712 15713**Error codes** 15714 15715For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15716 15717| ID| Error Message | 15718| -------- | ----------------------- | 15719| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 15720 15721**Example** 15722 15723```ts 15724// xxx.ets 15725import { webview } from '@kit.ArkWeb'; 15726 15727// This example demonstrates how to click a button to add an array of domain names to the disallowed list. 15728@Entry 15729@Component 15730struct WebComponent { 15731 main_url: string = 'https://www.example.com'; 15732 text_input_controller: TextInputController = new TextInputController(); 15733 controller: webview.WebviewController = new webview.WebviewController(); 15734 @State input_text: string = 'https://www.example.com'; 15735 15736 build() { 15737 Column() { 15738 Row() { 15739 Flex() { 15740 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 15741 .id("input_url") 15742 .height(40) 15743 .margin(5) 15744 .borderColor(Color.Blue) 15745 .onChange((value: string) => { 15746 this.input_text = value; 15747 }) 15748 15749 Button({type: ButtonType.Capsule}) { Text("Go") } 15750 .onClick(() => { 15751 this.controller.loadUrl(this.input_text); 15752 }) 15753 15754 Button({type: ButtonType.Capsule}) { Text("addAdsBlockAllowedList") } 15755 .onClick(() => { 15756 let arrDisallowDomainSuffixes = new Array<string>(); 15757 arrDisallowDomainSuffixes.push('example.com'); 15758 webview.AdsBlockManager.addAdsBlockDisallowedList(arrDisallowDomainSuffixes); 15759 15760 let arrAllowedDomainSuffixes = new Array<string>(); 15761 arrAllowedDomainSuffixes.push('news.example.com'); 15762 webview.AdsBlockManager.addAdsBlockAllowedList(arrAllowedDomainSuffixes); 15763 }) 15764 } 15765 } 15766 Web({ src: this.main_url, controller: this.controller }) 15767 .onControllerAttached(()=>{ 15768 this.controller.enableAdsBlock(true) 15769 }) 15770 } 15771 } 15772} 15773``` 15774 15775### removeAdsBlockAllowedList<sup>12+</sup> 15776 15777static removeAdsBlockAllowedList(domainSuffixes: Array\<string\>): void 15778 15779Removes an array of domain names from the allowed list of this **AdsBlockManager** object. 15780 15781> **NOTE** 15782> 15783> The domain name set by this API is not persistent; they need to be set again after the application is restarted. Removing an entry that does not exist does not trigger an exception. 15784 15785**System capability**: SystemCapability.Web.Webview.Core 15786 15787**Parameters** 15788 15789| Name | Type | Mandatory| Description | 15790| ---------- | ------ | ---- | -------------------------------- | 15791| domainSuffixes | Array\<string\> | Yes | Array of domain names, for example, ['example.com', 'abcd.efg.com'].| 15792 15793**Error codes** 15794 15795For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15796 15797| ID| Error Message | 15798| -------- | ----------------------- | 15799| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 15800 15801**Example** 15802 15803```ts 15804// xxx.ets 15805import { webview } from '@kit.ArkWeb'; 15806 15807// This example demonstrates how to click a button to remove an array of domain names from the disallowed list. 15808@Entry 15809@Component 15810struct WebComponent { 15811 main_url: string = 'https://www.example.com'; 15812 text_input_controller: TextInputController = new TextInputController(); 15813 controller: webview.WebviewController = new webview.WebviewController(); 15814 @State input_text: string = 'https://www.example.com'; 15815 15816 build() { 15817 Column() { 15818 Row() { 15819 Flex() { 15820 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 15821 .id("input_url") 15822 .height(40) 15823 .margin(5) 15824 .borderColor(Color.Blue) 15825 .onChange((value: string) => { 15826 this.input_text = value; 15827 }) 15828 15829 Button({type: ButtonType.Capsule}) { Text("Go") } 15830 .onClick(() => { 15831 this.controller.loadUrl(this.input_text); 15832 }) 15833 15834 Button({type: ButtonType.Capsule}) { Text("removeAdsBlockAllowedList") } 15835 .onClick(() => { 15836 let arrDomainSuffixes = new Array<string>(); 15837 arrDomainSuffixes.push('example.com'); 15838 arrDomainSuffixes.push('abcdefg.cn'); 15839 webview.AdsBlockManager.removeAdsBlockAllowedList(arrDomainSuffixes); 15840 }) 15841 } 15842 } 15843 Web({ src: this.main_url, controller: this.controller }) 15844 .onControllerAttached(()=>{ 15845 this.controller.enableAdsBlock(true); 15846 }) 15847 } 15848 } 15849} 15850``` 15851 15852### clearAdsBlockAllowedList<sup>12+</sup> 15853 15854static clearAdsBlockAllowedList(): void 15855 15856Clears the allowed list of this **AdsBlockManager** object. 15857 15858**System capability**: SystemCapability.Web.Webview.Core 15859 15860**Example** 15861 15862```ts 15863// xxx.ets 15864import { webview } from '@kit.ArkWeb'; 15865 15866@Entry 15867@Component 15868struct WebComponent { 15869 main_url: string = 'https://www.example.com'; 15870 text_input_controller: TextInputController = new TextInputController(); 15871 controller: webview.WebviewController = new webview.WebviewController(); 15872 @State input_text: string = 'https://www.example.com'; 15873 15874 15875 build() { 15876 Column() { 15877 Row() { 15878 Flex() { 15879 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 15880 .id("input_url") 15881 .height(40) 15882 .margin(5) 15883 .borderColor(Color.Blue) 15884 .onChange((value: string) => { 15885 this.input_text = value; 15886 }) 15887 15888 Button({type: ButtonType.Capsule}) { Text("Go") } 15889 .onClick(() => { 15890 this.controller.loadUrl(this.input_text); 15891 }) 15892 15893 Button({type: ButtonType.Capsule}) { Text("clearAdsBlockAllowedList") } 15894 .onClick(() => { 15895 webview.AdsBlockManager.clearAdsBlockAllowedList(); 15896 }) 15897 } 15898 } 15899 Web({ src: this.main_url, controller: this.controller }) 15900 .onControllerAttached(()=>{ 15901 this.controller.enableAdsBlock(true); 15902 }) 15903 } 15904 } 15905} 15906``` 15907### enableWholeWebPageDrawing<sup>12+</sup> 15908 15909static enableWholeWebPageDrawing(): void 15910 15911Enables the full drawing capability for the web page. This API works only during **Web** component initialization. 15912 15913**System capability**: SystemCapability.Web.Webview.Core 15914 15915**Example** 15916 15917```ts 15918// xxx.ets 15919import { webview } from '@kit.ArkWeb'; 15920import { BusinessError } from '@kit.BasicServicesKit'; 15921 15922@Entry 15923@Component 15924struct WebComponent { 15925 controller: webview.WebviewController = new webview.WebviewController(); 15926 15927 aboutToAppear(): void { 15928 try { 15929 webview.WebviewController.enableWholeWebPageDrawing(); 15930 } catch (error) { 15931 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 15932 } 15933 } 15934 15935 build() { 15936 Column() { 15937 Web({ src: 'www.example.com', controller: this.controller }) 15938 } 15939 } 15940} 15941``` 15942 15943### webPageSnapshot<sup>12+</sup> 15944 15945webPageSnapshot(info: SnapshotInfo, callback: AsyncCallback\<SnapshotResult>): void 15946 15947Obtains the full drawing result of the web page. (Local resource web pages are not supported currently.) 15948 15949**System capability**: SystemCapability.Web.Webview.Core 15950 15951**Parameters** 15952 15953| Name | Type | Mandatory | Description | 15954| ----------- | ------------- | ---- | ------------------------ | 15955| info | [SnapshotInfo](#snapshotinfo12)| Yes | Information for obtaining the full drawing result.| 15956| callback | [SnapshotResult](#snapshotresult12)| Yes | Callback used to return the result.| 15957 15958**Example** 15959 15960```ts 15961// xxx.ets 15962import { webview } from '@kit.ArkWeb'; 15963import { BusinessError } from '@kit.BasicServicesKit'; 15964 15965@Entry 15966@Component 15967struct WebComponent { 15968 controller: webview.WebviewController = new webview.WebviewController(); 15969 15970 build() { 15971 Column() { 15972 Button('webPageSnapshot') 15973 .onClick(() => { 15974 try { 15975 this.controller.webPageSnapshot({ id: "1234", size: { width: 100, height: 100 } }, (error, result) => { 15976 if (error) { 15977 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 15978 return; 15979 } 15980 if (result) { 15981 console.info(`return value is:${result}`); 15982 // You can process the returned result as required. 15983 } 15984 }); 15985 } catch (error) { 15986 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 15987 } 15988 }) 15989 Web({ src: 'www.example.com', controller: this.controller }) 15990 } 15991 } 15992} 15993``` 15994## SnapshotInfo<sup>12+</sup> 15995 15996Provides information used to obtain a full drawing result. 15997 15998**System capability**: SystemCapability.Web.Webview.Core 15999 16000| Name| Type| Mandatory| Description| 16001|------|------|------|------| 16002| id | string | No| Snapshot ID.| 16003| size | [SizeOptions](../apis-arkui/arkui-ts/ts-types.md#sizeoptions) | No| Size for web rendering. The maximum size is 16000 px x 16000 px. The length unit can be px, vp, or %. The length unit must be the consistent across parameters. The default unit is vp. If the size exceeds the specifications , the maximum size is returned. Example: **width: '100px', height: '200px'** or **width: '20%', height'30%'**. If only digits are written, the unit is vp.| 16004 16005## SnapshotResult<sup>12+</sup> 16006 16007Represents a full drawing result. 16008 16009**System capability**: SystemCapability.Web.Webview.Core 16010 16011| Name| Type| Mandatory| Description| 16012|------|------|--|---------| 16013| id | string | No| Snapshot ID.| 16014| status | boolean | No| Snapshot status. The value can be **true** (normal) or **false** (failure). If the full drawing result fails to be obtained, the width and height of the returned size are both 0, and the map is empty.| 16015| size | [SizeOptions](../apis-arkui/arkui-ts/ts-types.md#sizeoptions) | No| Actual size drawn on the web page. The value is of the number type, and the unit is vp.| 16016| imagePixelMap | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | No| Full drawing result in image.pixelMap format.| 16017 16018## ScrollType<sup>12+</sup> 16019 16020Represents a scroll type, which is used in [setScrollable](#setscrollable12). 16021 16022**System capability**: SystemCapability.Web.Webview.Core 16023 16024| Name | Value| Description | 16025| ------------ | -- |--------------------------------- | 16026| EVENT | 0 | Scrolling event, indicating that a web page is scrolled by using a touchscreen, a touchpad, or a mouse.| 16027 16028## PressureLevel<sup>14+</sup> 16029 16030Represents a memory pressure level. When an application clears the cache occupied by the **Web** component, the **Web** kernel releases the cache based on the memory pressure level. 16031 16032**System capability**: SystemCapability.Web.Webview.Core 16033 16034| Name| Value| Description| 16035| ------------------------------- | - | ---------- | 16036| MEMORY_PRESSURE_LEVEL_MODERATE | 1 | Moderate memory pressure level. At this level, the **Web** kernel attempts to release the cache that has low reallocation overhead and does not need to be used immediately.| 16037| MEMORY_PRESSURE_LEVEL_CRITICAL | 2 | Critical memory pressure level. At this level, the **Web** kernel attempts to release all possible memory caches.| 16038