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## webview.once 22 23once(type: string, callback: Callback\<void\>): void 24 25Registers a one-time callback for web events of the specified type. Currently, only **webInited** is supported. This callback is triggered when the Web engine initialization is complete. 26 27When the first **Web** component is loaded in an application, the web engine is initialized. When other **Web** components are loaded in the same application, **once()** is not triggered. When the first **Web** component is loaded after the last **Web** component is destroyed in the application, the web engine will be initialized again. 28 29**System capability**: SystemCapability.Web.Webview.Core 30 31**Parameters** 32 33| Name | Type | Mandatory| Description | 34| ------- | ---------------- | ---- | -------------------- | 35| type | string | Yes | Web event type. The value can be **"webInited"**, indicating completion of web initialization. | 36| callback | Callback\<void\> | Yes | Callback to register.| 37 38**Error codes** 39 40For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 41 42| ID| Error Message | 43| -------- | ----------------------- | 44| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 45 46**Example** 47 48```ts 49// xxx.ets 50import { webview } from '@kit.ArkWeb'; 51 52webview.once("webInited", () => { 53 console.log("configCookieSync"); 54 webview.WebCookieManager.configCookieSync("https://www.example.com", "a=b"); 55}) 56 57@Entry 58@Component 59struct WebComponent { 60 controller: webview.WebviewController = new webview.WebviewController(); 61 62 build() { 63 Column() { 64 Web({ src: 'www.example.com', controller: this.controller }) 65 } 66 } 67} 68``` 69 70## WebMessagePort 71 72Implements a **WebMessagePort** object to send and receive messages. The message of the [WebMessageType](#webmessagetype10)/[WebMessage](#webmessage) type can be sent to the HTML5 side. 73 74### Properties 75 76**System capability**: SystemCapability.Web.Webview.Core 77 78| Name | Type | Readable| Writable| Description | 79| ------------ | ------ | ---- | ---- | ------------------------------------------------| 80| isExtentionType<sup>10+</sup> | boolean | Yes | Yes| Whether to use the extended APIs [postMessageEventExt](#postmessageeventext10) and [onMessageEventExt](#onmessageeventext10) when creating a **WebMessagePort**. The default value is **false**, indicating that the extended APIs are not used. | 81 82### postMessageEvent 83 84postMessageEvent(message: WebMessage): void 85 86Sends a message of the [WebMessage](#webmessage) type to the HTML5 side. The [onMessageEvent](#onmessageevent) API must be invoked first. Otherwise, the message fails to be sent. For the complete sample code, see [postMessage](#postmessage). 87 88**System capability**: SystemCapability.Web.Webview.Core 89 90**Parameters** 91 92| Name | Type | Mandatory| Description | 93| ------- | ------ | ---- | :------------- | 94| message | [WebMessage](#webmessage) | Yes | Message to send.| 95 96**Error codes** 97 98For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 99 100| ID| Error Message | 101| -------- | ------------------------------------- | 102| 17100010 | Failed to post messages through the port. | 103| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 104 105**Example** 106 107```ts 108// xxx.ets 109import { webview } from '@kit.ArkWeb'; 110import { BusinessError } from '@kit.BasicServicesKit'; 111 112@Entry 113@Component 114struct WebComponent { 115 controller: webview.WebviewController = new webview.WebviewController(); 116 ports: webview.WebMessagePort[] = []; 117 118 build() { 119 Column() { 120 Button('postMessageEvent') 121 .onClick(() => { 122 try { 123 this.ports = this.controller.createWebMessagePorts(); 124 this.controller.postMessage('__init_port__', [this.ports[0]], '*'); 125 this.ports[1].postMessageEvent("post message from ets to html5"); 126 } catch (error) { 127 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 128 } 129 }) 130 Web({ src: 'www.example.com', controller: this.controller }) 131 } 132 } 133} 134``` 135 136### onMessageEvent 137 138onMessageEvent(callback: (result: WebMessage) => void): void 139 140Registers a callback to receive messages of the [WebMessage](#webmessage) type from the HTML5 side. For the complete sample code, see [postMessage](#postmessage). 141 142**System capability**: SystemCapability.Web.Webview.Core 143 144**Parameters** 145 146| Name | Type | Mandatory| Description | 147| -------- | -------- | ---- | :------------------- | 148| callback | (result: [WebMessage](#webmessage)) => void | Yes | Message received.| 149 150**Error codes** 151 152For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 153 154| ID| Error Message | 155| -------- | ----------------------------------------------- | 156| 17100006 | Failed to register a message event for the port.| 157| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.| 158 159**Example** 160 161```ts 162// xxx.ets 163import { webview } from '@kit.ArkWeb'; 164import { BusinessError } from '@kit.BasicServicesKit'; 165 166@Entry 167@Component 168struct WebComponent { 169 controller: webview.WebviewController = new webview.WebviewController(); 170 ports: webview.WebMessagePort[] = []; 171 172 build() { 173 Column() { 174 Button('onMessageEvent') 175 .onClick(() => { 176 try { 177 this.ports = this.controller.createWebMessagePorts(); 178 this.ports[1].onMessageEvent((msg) => { 179 if (typeof (msg) == "string") { 180 console.log("received string message from html5, string is:" + msg); 181 } else if (typeof (msg) == "object") { 182 if (msg instanceof ArrayBuffer) { 183 console.log("received arraybuffer from html5, length is:" + msg.byteLength); 184 } else { 185 console.log("not support"); 186 } 187 } else { 188 console.log("not support"); 189 } 190 }) 191 } catch (error) { 192 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 193 } 194 }) 195 Web({ src: 'www.example.com', controller: this.controller }) 196 } 197 } 198} 199``` 200 201### postMessageEventExt<sup>10+</sup> 202 203postMessageEventExt(message: WebMessageExt): void 204 205Sends a message of the [WebMessageType](#webmessagetype10) type to the HTML5 side. The [onMessageEventExt](#onmessageeventext10) API must be invoked first. Otherwise, the message fails to be sent. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 206 207**System capability**: SystemCapability.Web.Webview.Core 208 209**Parameters** 210 211| Name | Type | Mandatory| Description | 212| ------- | ------ | ---- | :------------- | 213| message | [WebMessageExt](#webmessageext10) | Yes | Message to send.| 214 215**Error codes** 216 217For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 218 219| ID| Error Message | 220| -------- | ------------------------------------- | 221| 17100010 | Failed to post messages through the port. | 222| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 223 224### onMessageEventExt<sup>10+</sup> 225 226onMessageEventExt(callback: (result: WebMessageExt) => void): void 227 228Registers a callback to receive messages of the [WebMessageType](#webmessagetype10) type from the HTML5 side. 229 230**System capability**: SystemCapability.Web.Webview.Core 231 232**Parameters** 233 234| Name | Type | Mandatory| Description | 235| -------- | -------- | ---- | :------------------- | 236| callback | (result: [WebMessageExt](#webmessageext10)) => void | Yes | Message received.| 237 238**Error codes** 239 240For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 241 242| ID| Error Message | 243| -------- | ----------------------------------------------- | 244| 17100006 | Failed to register a message event for the port. | 245| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 246 247**Example** 248 249```ts 250// xxx.ets 251import { webview } from '@kit.ArkWeb'; 252import { BusinessError } from '@kit.BasicServicesKit'; 253 254class TestObj { 255 test(str: string): ArrayBuffer { 256 let buf = new ArrayBuffer(str.length); 257 let buff = new Uint8Array(buf); 258 259 for (let i = 0; i < str.length; i++) { 260 buff[i] = str.charCodeAt(i); 261 } 262 return buf; 263 } 264} 265 266// 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. 267@Entry 268@Component 269struct WebComponent { 270 controller: webview.WebviewController = new webview.WebviewController(); 271 ports: webview.WebMessagePort[] = []; 272 nativePort: webview.WebMessagePort | null = null; 273 @State msg1: string = ""; 274 @State msg2: string = ""; 275 message: webview.WebMessageExt = new webview.WebMessageExt(); 276 @State testObjtest: TestObj = new TestObj(); 277 278 build() { 279 Column() { 280 Text(this.msg1).fontSize(16) 281 Text(this.msg2).fontSize(16) 282 Button('SendToH5 setString').margin({ 283 right: 800, 284 }) 285 .onClick(() => { 286 // Use the local port to send messages to HTML5. 287 try { 288 console.log("In ArkTS side send true start"); 289 if (this.nativePort) { 290 this.message.setType(1); 291 this.message.setString("helloFromEts"); 292 this.nativePort.postMessageEventExt(this.message); 293 } 294 } 295 catch (error) { 296 console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 297 } 298 }) 299 Button('SendToH5 setNumber').margin({ 300 top: 10, 301 right: 800, 302 }) 303 .onClick(() => { 304 // Use the local port to send messages to HTML5. 305 try { 306 console.log("In ArkTS side send true start"); 307 if (this.nativePort) { 308 this.message.setType(2); 309 this.message.setNumber(12345); 310 this.nativePort.postMessageEventExt(this.message); 311 } 312 } 313 catch (error) { 314 console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 315 } 316 }) 317 Button('SendToH5 setBoolean').margin({ 318 top: -90, 319 }) 320 .onClick(() => { 321 // Use the local port to send messages to HTML5. 322 try { 323 console.log("In ArkTS side send true start"); 324 if (this.nativePort) { 325 this.message.setType(3); 326 this.message.setBoolean(true); 327 this.nativePort.postMessageEventExt(this.message); 328 } 329 } 330 catch (error) { 331 console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 332 } 333 }) 334 Button('SendToH5 setArrayBuffer').margin({ 335 top: 10, 336 }) 337 .onClick(() => { 338 // Use the local port to send messages to HTML5. 339 try { 340 console.log("In ArkTS side send true start"); 341 if (this.nativePort) { 342 this.message.setType(4); 343 this.message.setArrayBuffer(this.testObjtest.test("Name=test&Password=test")); 344 this.nativePort.postMessageEventExt(this.message); 345 } 346 } 347 catch (error) { 348 console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 349 } 350 }) 351 Button('SendToH5 setArray').margin({ 352 top: -90, 353 left: 800, 354 }) 355 .onClick(() => { 356 // Use the local port to send messages to HTML5. 357 try { 358 console.log("In ArkTS side send true start"); 359 if (this.nativePort) { 360 this.message.setType(5); 361 this.message.setArray([1, 2, 3]); 362 this.nativePort.postMessageEventExt(this.message); 363 } 364 } 365 catch (error) { 366 console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 367 } 368 }) 369 Button('SendToH5 setError').margin({ 370 top: 10, 371 left: 800, 372 }) 373 .onClick(() => { 374 // Use the local port to send messages to HTML5. 375 try { 376 console.log("In ArkTS side send true start"); 377 throw new ReferenceError("ReferenceError"); 378 } 379 catch (error) { 380 if (this.nativePort) { 381 this.message.setType(6); 382 this.message.setError(error); 383 this.nativePort.postMessageEventExt(this.message); 384 } 385 console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 386 } 387 }) 388 389 Web({ src: $rawfile('index.html'), controller: this.controller }) 390 .onPageEnd(() => { 391 console.log("In ArkTS side message onPageEnd init message channel"); 392 // 1. Create a message port. 393 this.ports = this.controller.createWebMessagePorts(true); 394 // 2. Send port 1 to HTML5. 395 this.controller.postMessage("init_web_messageport", [this.ports[1]], "*"); 396 // 3. Save port 0 to the local host. 397 this.nativePort = this.ports[0]; 398 // 4. Set the callback. 399 this.nativePort.onMessageEventExt((result) => { 400 console.log("In ArkTS side got message"); 401 try { 402 let type = result.getType(); 403 console.log("In ArkTS side getType:" + type); 404 switch (type) { 405 case webview.WebMessageType.STRING: { 406 this.msg1 = "result type:" + typeof (result.getString()); 407 this.msg2 = "result getString:" + ((result.getString())); 408 break; 409 } 410 case webview.WebMessageType.NUMBER: { 411 this.msg1 = "result type:" + typeof (result.getNumber()); 412 this.msg2 = "result getNumber:" + ((result.getNumber())); 413 break; 414 } 415 case webview.WebMessageType.BOOLEAN: { 416 this.msg1 = "result type:" + typeof (result.getBoolean()); 417 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 418 break; 419 } 420 case webview.WebMessageType.ARRAY_BUFFER: { 421 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 422 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 423 break; 424 } 425 case webview.WebMessageType.ARRAY: { 426 this.msg1 = "result type:" + typeof (result.getArray()); 427 this.msg2 = "result getArray:" + result.getArray(); 428 break; 429 } 430 case webview.WebMessageType.ERROR: { 431 this.msg1 = "result type:" + typeof (result.getError()); 432 this.msg2 = "result getError:" + result.getError(); 433 break; 434 } 435 default: { 436 this.msg1 = "default break, type:" + type; 437 break; 438 } 439 } 440 } 441 catch (error) { 442 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 443 } 444 }); 445 }) 446 } 447 } 448} 449``` 450 451HTML file to be loaded: 452```html 453<!--index.html--> 454<!DOCTYPE html> 455<html lang="en-gb"> 456<head> 457 <title>WebView MessagePort Demo</title> 458</head> 459 460<body> 461<h1>Html5 Send and Receive Message</h1> 462<h3 id="msg">Receive string:</h3> 463<h3 id="msg2">Receive arraybuffer:</h3> 464<div style="font-size: 10pt; text-align: center;"> 465 <input type="button" value="Send String" onclick="postStringToApp();" /><br/> 466</div> 467</body> 468<script src="index.js"></script> 469</html> 470``` 471 472```js 473//index.js 474var h5Port; 475window.addEventListener('message', function(event) { 476 if (event.data == 'init_web_messageport') { 477 if(event.ports[0] != null) { 478 h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side. 479 h5Port.onmessage = function(event) { 480 console.log("hwd In html got message"); 481 // 2. Receive the message sent from the eTS side. 482 var result = event.data; 483 console.log("In html got message, typeof: ", typeof(result)); 484 console.log("In html got message, result: ", (result)); 485 if (typeof(result) == "string") { 486 console.log("In html got message, String: ", result); 487 document.getElementById("msg").innerHTML = "String:" + result; 488 } else if (typeof(result) == "number") { 489 console.log("In html side got message, number: ", result); 490 document.getElementById("msg").innerHTML = "Number:" + result; 491 } else if (typeof(result) == "boolean") { 492 console.log("In html side got message, boolean: ", result); 493 document.getElementById("msg").innerHTML = "Boolean:" + result; 494 } else if (typeof(result) == "object") { 495 if (result instanceof ArrayBuffer) { 496 document.getElementById("msg2").innerHTML = "ArrayBuffer:" + result.byteLength; 497 console.log("In html got message, byteLength: ", result.byteLength); 498 } else if (result instanceof Error) { 499 console.log("In html error message, err:" + (result)); 500 console.log("In html error message, typeof err:" + typeof(result)); 501 document.getElementById("msg2").innerHTML = "Error:" + result.name + ", msg:" + result.message; 502 } else if (result instanceof Array) { 503 console.log("In html got message, Array"); 504 console.log("In html got message, Array length:" + result.length); 505 console.log("In html got message, Array[0]:" + (result[0])); 506 console.log("In html got message, typeof Array[0]:" + typeof(result[0])); 507 document.getElementById("msg2").innerHTML = "Array len:" + result.length + ", value:" + result; 508 } else { 509 console.log("In html got message, not any instance of support type"); 510 document.getElementById("msg").innerHTML = "not any instance of support type"; 511 } 512 } else { 513 console.log("In html got message, not support type"); 514 document.getElementById("msg").innerHTML = "not support type"; 515 } 516 } 517 h5Port.onmessageerror = (event) => { 518 console.error(`hwd In html Error receiving message: ${event}`); 519 }; 520 } 521 } 522}) 523 524// Use h5Port to send a message of the string type to the ets side. 525function postStringToApp() { 526 if (h5Port) { 527 console.log("In html send string message"); 528 h5Port.postMessage("hello"); 529 console.log("In html send string message end"); 530 } else { 531 console.error("In html h5port is null, please init first"); 532 } 533} 534``` 535 536### close 537 538close(): void 539 540Closes this message port when messages do not need to be sent. To use this API, a message port must first be created using [createWebMessagePorts](#createwebmessageports). 541 542**System capability**: SystemCapability.Web.Webview.Core 543 544**Example** 545 546```ts 547// xxx.ets 548import { webview } from '@kit.ArkWeb'; 549import { BusinessError } from '@kit.BasicServicesKit'; 550 551@Entry 552@Component 553struct WebComponent { 554 controller: webview.WebviewController = new webview.WebviewController(); 555 msgPort: webview.WebMessagePort[] = []; 556 557 build() { 558 Column() { 559 // Use createWebMessagePorts to create a message port. 560 Button('createWebMessagePorts') 561 .onClick(() => { 562 try { 563 this.msgPort = this.controller.createWebMessagePorts(); 564 console.log("createWebMessagePorts size:" + this.msgPort.length) 565 } catch (error) { 566 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 567 } 568 }) 569 Button('close') 570 .onClick(() => { 571 try { 572 if (this.msgPort && this.msgPort.length == 2) { 573 this.msgPort[1].close(); 574 } else { 575 console.error("msgPort is null, Please initialize first"); 576 } 577 } catch (error) { 578 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 579 } 580 }) 581 Web({ src: 'www.example.com', controller: this.controller }) 582 } 583 } 584} 585``` 586 587## WebviewController 588 589Implements 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. 590 591### constructor<sup>11+</sup> 592 593constructor(webTag?: string) 594 595Constructor used to create a **WebviewController** object. 596 597> **NOTE** 598> 599> When no parameter is passed in **new webview.WebviewController()**, it indicates that the constructor is empty. If the C API is not used, no parameter needs to be passed. 600> 601> When a valid string is passed in, **new webview.WebviewController("xxx")** can be used to distinguish multiple instances and invoke the methods of the corresponding instance. 602> 603> When an empty parameter is passed in, such as **new webview.WebviewController("")** or **new webview.WebviewController(undefined)**, the parameter is meaningless that multiple instances cannot be distinguished and **undefined** is returned. You need to check whether the return value is normal. 604 605**System capability**: SystemCapability.Web.Webview.Core 606 607**Parameters** 608 609| Name | Type | Mandatory| Description | 610| ---------- | ------ | ---- | -------------------------------- | 611| webTag | string | No | Name of the **Web** component.| 612 613**Example** 614 615```ts 616// xxx.ets 617import { webview } from '@kit.ArkWeb'; 618import { BusinessError } from '@kit.BasicServicesKit'; 619 620class WebObj { 621 constructor() { 622 } 623 624 webTest(): string { 625 console.log('Web test'); 626 return "Web test"; 627 } 628 629 webString(): void { 630 console.log('Web test toString'); 631 } 632} 633 634@Entry 635@Component 636struct WebComponent { 637 controller: webview.WebviewController = new webview.WebviewController() 638 @State webTestObj: WebObj = new WebObj(); 639 640 build() { 641 Column() { 642 Button('refresh') 643 .onClick(() => { 644 try { 645 this.controller.refresh(); 646 } catch (error) { 647 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 648 } 649 }) 650 Button('deleteJavaScriptRegister') 651 .onClick(() => { 652 try { 653 this.controller.deleteJavaScriptRegister("objTestName"); 654 } catch (error) { 655 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 656 } 657 }) 658 Web({ src: '', controller: this.controller }) 659 .javaScriptAccess(true) 660 .onControllerAttached(() => { 661 this.controller.loadUrl($rawfile("index.html")); 662 this.controller.registerJavaScriptProxy(this.webTestObj, "objTestName", ["webTest", "webString"]); 663 }) 664 } 665 } 666} 667``` 668 669HTML file to be loaded: 670```html 671<!-- index.html --> 672<!DOCTYPE html> 673<html> 674 <meta charset="utf-8"> 675 <body> 676 <button type="button" onclick="htmlTest()">Click Me!</button> 677 <p id="demo"></p> 678 <p id="webDemo"></p> 679 </body> 680 <script type="text/javascript"> 681 function htmlTest() { 682 // This function call expects to return "Web test" 683 let webStr = objTestName.webTest(); 684 document.getElementById("webDemo").innerHTML=webStr; 685 console.log('objTestName.webTest result:'+ webStr) 686 } 687</script> 688</html> 689``` 690 691### initializeWebEngine 692 693static initializeWebEngine(): void 694 695Loads 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. The frequently visited websites are automatically pre-connected. 696 697> **NOTE** 698> 699> - **initializeWebEngine** cannot be called in an asynchronous thread. Otherwise, the system breaks down. 700> - **initializeWebEngine** takes effect globally and needs to be called only once in an application lifecycle. 701 702**System capability**: SystemCapability.Web.Webview.Core 703 704**Example** 705 706The following code snippet exemplifies calling this API after the EntryAbility is created. 707 708```ts 709// xxx.ets 710import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 711import { webview } from '@kit.ArkWeb'; 712 713export default class EntryAbility extends UIAbility { 714 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 715 console.log("EntryAbility onCreate") 716 webview.WebviewController.initializeWebEngine() 717 console.log("EntryAbility onCreate done") 718 } 719} 720``` 721 722### setHttpDns<sup>10+</sup> 723 724static setHttpDns(secureDnsMode:SecureDnsMode, secureDnsConfig:string): void 725 726Sets how the Web component uses HTTPDNS for DNS resolution. 727 728**System capability**: SystemCapability.Web.Webview.Core 729 730**Parameters** 731 732| Name | Type | Mandatory | Description| 733| ------------------ | ------- | ---- | ------------- | 734| secureDnsMode | [SecureDnsMode](#securednsmode10) | Yes | Mode in which HTTPDNS is used.| 735| secureDnsConfig | string | Yes| Information about the HTTPDNS server to use, which must use HTTPS. Only one HTTPDNS server can be configured.| 736 737**Error codes** 738 739For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 740 741| ID| Error Message | 742| -------- | ----------------------- | 743| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 744 745**Example** 746 747```ts 748// xxx.ets 749import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 750import { webview } from '@kit.ArkWeb'; 751import { BusinessError } from '@kit.BasicServicesKit'; 752 753export default class EntryAbility extends UIAbility { 754 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 755 console.log("EntryAbility onCreate") 756 try { 757 webview.WebviewController.setHttpDns(webview.SecureDnsMode.AUTO, "https://example1.test") 758 } catch (error) { 759 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 760 } 761 762 AppStorage.setOrCreate("abilityWant", want); 763 console.log("EntryAbility onCreate done") 764 } 765} 766``` 767 768### setWebDebuggingAccess 769 770static setWebDebuggingAccess(webDebuggingAccess: boolean): void 771 772Sets 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). 773 774NOTE: 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. 775 776**System capability**: SystemCapability.Web.Webview.Core 777 778**Parameters** 779 780| Name | Type | Mandatory | Description| 781| ------------------ | ------- | ---- | ------------- | 782| webDebuggingAccess | boolean | Yes | Sets whether to enable web debugging.| 783 784**Error codes** 785 786For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 787 788| ID | Error Message | 789| -------- | ------------------------------------------------------------ | 790| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 791 792**Example** 793 794```ts 795// xxx.ets 796import { webview } from '@kit.ArkWeb'; 797import { BusinessError } from '@kit.BasicServicesKit'; 798 799@Entry 800@Component 801struct WebComponent { 802 controller: webview.WebviewController = new webview.WebviewController(); 803 804 aboutToAppear(): void { 805 try { 806 webview.WebviewController.setWebDebuggingAccess(true); 807 } catch (error) { 808 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 809 } 810 } 811 812 build() { 813 Column() { 814 Web({ src: 'www.example.com', controller: this.controller }) 815 } 816 } 817} 818``` 819 820### loadUrl 821 822loadUrl(url: string | Resource, headers?: Array\<WebHeader>): void 823 824Loads a specified URL. 825 826**System capability**: SystemCapability.Web.Webview.Core 827 828**Parameters** 829 830| Name | Type | Mandatory| Description | 831| ------- | ---------------- | ---- | :-------------------- | 832| url | string \| Resource | Yes | URL to load. | 833| headers | Array\<[WebHeader](#webheader)> | No | Additional HTTP request header of the URL.| 834 835**Error codes** 836 837For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 838 839| ID| Error Message | 840| -------- | ------------------------------------------------------------ | 841| 17100001 | Init error. The WebviewController must be associated with a Web component. | 842| 17100002 | Invalid url. | 843| 17100003 | Invalid resource path or file type. | 844| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 845 846**Example** 847 848```ts 849// xxx.ets 850import { webview } from '@kit.ArkWeb'; 851import { BusinessError } from '@kit.BasicServicesKit'; 852 853@Entry 854@Component 855struct WebComponent { 856 controller: webview.WebviewController = new webview.WebviewController(); 857 858 build() { 859 Column() { 860 Button('loadUrl') 861 .onClick(() => { 862 try { 863 // The URL to be loaded is of the string type. 864 this.controller.loadUrl('www.example.com'); 865 } catch (error) { 866 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 867 } 868 }) 869 Web({ src: 'www.example.com', controller: this.controller }) 870 } 871 } 872} 873``` 874 875```ts 876// xxx.ets 877import { webview } from '@kit.ArkWeb'; 878import { BusinessError } from '@kit.BasicServicesKit'; 879 880@Entry 881@Component 882struct WebComponent { 883 controller: webview.WebviewController = new webview.WebviewController(); 884 885 build() { 886 Column() { 887 Button('loadUrl') 888 .onClick(() => { 889 try { 890 // The headers parameter is passed. 891 this.controller.loadUrl('www.example.com', [{ headerKey: "headerKey", headerValue: "headerValue" }]); 892 } catch (error) { 893 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 894 } 895 }) 896 Web({ src: 'www.example.com', controller: this.controller }) 897 } 898 } 899} 900``` 901 902There are three methods for loading local resource files: 903 9041. Using $rawfile 905```ts 906// xxx.ets 907import { webview } from '@kit.ArkWeb'; 908import { BusinessError } from '@kit.BasicServicesKit'; 909 910@Entry 911@Component 912struct WebComponent { 913 controller: webview.WebviewController = new webview.WebviewController(); 914 915 build() { 916 Column() { 917 Button('loadUrl') 918 .onClick(() => { 919 try { 920 // Load a local resource file through $rawfile. 921 this.controller.loadUrl($rawfile('index.html')); 922 } catch (error) { 923 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 924 } 925 }) 926 Web({ src: 'www.example.com', controller: this.controller }) 927 } 928 } 929} 930``` 931 9322. Using the resources protocol, which can be used by WebView to load links with a hash (#). 933```ts 934// xxx.ets 935import { webview } from '@kit.ArkWeb'; 936import { BusinessError } from '@kit.BasicServicesKit'; 937 938@Entry 939@Component 940struct WebComponent { 941 controller: webview.WebviewController = new webview.WebviewController(); 942 943 build() { 944 Column() { 945 Button('loadUrl') 946 .onClick(() => { 947 try { 948 // Load local resource files through the resource protocol. 949 this.controller.loadUrl("resource://rawfile/index.html"); 950 } catch (error) { 951 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 952 } 953 }) 954 Web({ src: 'www.example.com', controller: this.controller }) 955 } 956 } 957} 958``` 959 9603. 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). 961 962HTML file to be loaded: 963```html 964<!-- index.html --> 965<!DOCTYPE html> 966<html> 967 <body> 968 <p>Hello World</p> 969 </body> 970</html> 971``` 972 973### loadData 974 975loadData(data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string): void 976 977Loads specified data. 978 979When both **baseUrl** and **historyUrl** are empty, 980 981if **encoding** is not base64 (including null values), ASCII encoding is used for octets within the secure URL character range, and the standard %xx hexadecimal encoding of the URL is used for octets outside the secure URL character range. 982 983**data** must be encoded using Base64 or any hash (#) in the content must be encoded as %23. Otherwise, hash (#) is considered as the end of the content, and the remaining text is used as the document fragment identifier. 984 985**System capability**: SystemCapability.Web.Webview.Core 986 987**Parameters** 988 989| Name | Type | Mandatory| Description | 990| ---------- | ------ | ---- | ------------------------------------------------------------ | 991| data | string | Yes | String obtained after being base64 or URL encoded. | 992| mimeType | string | Yes | Media type (MIME). | 993| encoding | string | Yes | Encoding type, which can be base64 or URL. | 994| baseUrl | string | No | URL (HTTP/HTTPS/data compliant), which is assigned by the **Web** component to **window.origin**. If a large number of HTML files need to be loaded, set this parameter to **data**.| 995| 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.| 996 997> **NOTE** 998> 999> To load a local image, you can assign a space to either **baseUrl** or **historyUrl**. For details, see the sample code. 1000> In the scenario of loading a local image, **baseUrl** and **historyUrl** cannot be both empty. Otherwise, the image cannot be loaded. 1001> 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. 1002 1003**Error codes** 1004 1005For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1006 1007| ID| Error Message | 1008| -------- | ------------------------------------------------------------ | 1009| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1010| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1011 1012**Example** 1013 1014When both **baseUrl** and **historyUrl** are empty: 1015```ts 1016// xxx.ets 1017import { webview } from '@kit.ArkWeb'; 1018import { BusinessError } from '@kit.BasicServicesKit'; 1019 1020@Entry 1021@Component 1022struct WebComponent { 1023 controller: webview.WebviewController = new webview.WebviewController(); 1024 1025 build() { 1026 Column() { 1027 Button('loadData') 1028 .onClick(() => { 1029 try { 1030 this.controller.loadData( 1031 "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>", 1032 "text/html", 1033 // UTF-8 is charset. 1034 "UTF-8" 1035 ); 1036 } catch (error) { 1037 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1038 } 1039 }) 1040 Web({ src: 'www.example.com', controller: this.controller }) 1041 } 1042 } 1043} 1044``` 1045 1046```ts 1047// xxx.ets 1048import { webview } from '@kit.ArkWeb'; 1049import { BusinessError } from '@kit.BasicServicesKit'; 1050 1051@Entry 1052@Component 1053struct WebComponent { 1054 controller: webview.WebviewController = new webview.WebviewController(); 1055 1056 build() { 1057 Column() { 1058 Button('loadData') 1059 .onClick(() => { 1060 try { 1061 this.controller.loadData( 1062 // Coding tests: string encoded using base64. 1063 "Q29kaW5nIHRlc3Rz", 1064 "text/html", 1065 "base64" 1066 ); 1067 } catch (error) { 1068 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1069 } 1070 }) 1071 Web({ src: 'www.example.com', controller: this.controller }) 1072 } 1073 } 1074} 1075``` 1076 1077Example of loading local resource: 1078```ts 1079// xxx.ets 1080import { webview } from '@kit.ArkWeb'; 1081import { BusinessError } from '@kit.BasicServicesKit'; 1082 1083@Entry 1084@Component 1085struct WebComponent { 1086 controller: webview.WebviewController = new webview.WebviewController(); 1087 updataContent: string = '<body><div><image src=resource://rawfile/xxx.png alt="image -- end" width="500" height="250"></image></div></body>' 1088 1089 build() { 1090 Column() { 1091 Button('loadData') 1092 .onClick(() => { 1093 try { 1094 // UTF-8 is charset. 1095 this.controller.loadData(this.updataContent, "text/html", "UTF-8", " ", " "); 1096 } catch (error) { 1097 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1098 } 1099 }) 1100 Web({ src: 'www.example.com', controller: this.controller }) 1101 } 1102 } 1103} 1104``` 1105 1106### accessForward 1107 1108accessForward(): boolean 1109 1110Checks whether going to the next page can be performed on the current page. 1111 1112You can use [getBackForwardEntries](#getbackforwardentries) to obtain the historical information list of the current WebView and use [accessStep](#accessstep) to determine whether to move forward or backward based on the specified number of steps. 1113 1114**System capability**: SystemCapability.Web.Webview.Core 1115 1116**Return value** 1117 1118| Type | Description | 1119| ------- | --------------------------------- | 1120| boolean | Returns **true** if going to the next page can be performed on the current page; returns **false** otherwise.| 1121 1122**Error codes** 1123 1124For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1125 1126| ID| Error Message | 1127| -------- | ------------------------------------------------------------ | 1128| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1129 1130**Example** 1131 1132```ts 1133// xxx.ets 1134import { webview } from '@kit.ArkWeb'; 1135import { BusinessError } from '@kit.BasicServicesKit'; 1136 1137@Entry 1138@Component 1139struct WebComponent { 1140 controller: webview.WebviewController = new webview.WebviewController(); 1141 1142 build() { 1143 Column() { 1144 Button('accessForward') 1145 .onClick(() => { 1146 try { 1147 let result = this.controller.accessForward(); 1148 console.log('result:' + result); 1149 } catch (error) { 1150 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1151 } 1152 }) 1153 Web({ src: 'www.example.com', controller: this.controller }) 1154 } 1155 } 1156} 1157``` 1158 1159### forward 1160 1161forward(): void 1162 1163Moves to the next page based on the history stack. This API is generally used together with **accessForward**. 1164 1165**System capability**: SystemCapability.Web.Webview.Core 1166 1167**Error codes** 1168 1169For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1170 1171| ID| Error Message | 1172| -------- | ------------------------------------------------------------ | 1173| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1174 1175**Example** 1176 1177```ts 1178// xxx.ets 1179import { webview } from '@kit.ArkWeb'; 1180import { BusinessError } from '@kit.BasicServicesKit'; 1181 1182@Entry 1183@Component 1184struct WebComponent { 1185 controller: webview.WebviewController = new webview.WebviewController(); 1186 1187 build() { 1188 Column() { 1189 Button('forward') 1190 .onClick(() => { 1191 try { 1192 this.controller.forward(); 1193 } catch (error) { 1194 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1195 } 1196 }) 1197 Web({ src: 'www.example.com', controller: this.controller }) 1198 } 1199 } 1200} 1201``` 1202 1203### accessBackward 1204 1205accessBackward(): boolean 1206 1207Checks whether going to the previous page can be performed on the current page. 1208 1209You can use [getBackForwardEntries](#getbackforwardentries) to obtain the historical information list of the current WebView and use [accessStep](#accessstep) to determine whether to move forward or backward based on the specified number of steps. 1210 1211> **NOTE** 1212> 1213> If [setCustomUserAgent](#setcustomuseragent10) is called when the **Web** component is loaded for the first time, the value of **accessBackForward** may be **false** when there are multiple historical entries. That is, there is no backward entry. You are advised to call the **setCustomUserAgent** method to set a user agent before using **loadUrl** to load a specific page. 1214> 1215> Causes: When the **Web** component is loaded for the first time, calling [setCustomUserAgent](#setcustomuseragent10) causes the component to reload and retain the initial history entry. Then the new entry replaces the initial history entry and no new history entry is generated. As a result, the value of **accessBackward** is false. 1216 1217**System capability**: SystemCapability.Web.Webview.Core 1218 1219**Return value** 1220 1221| Type | Description | 1222| ------- | -------------------------------- | 1223| boolean | Returns **true** if going to the previous page can be performed on the current page; returns **false** otherwise.| 1224 1225**Error codes** 1226 1227For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1228 1229| ID| Error Message | 1230| -------- | ------------------------------------------------------------ | 1231| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1232 1233**Example** 1234 1235```ts 1236// xxx.ets 1237import { webview } from '@kit.ArkWeb'; 1238import { BusinessError } from '@kit.BasicServicesKit'; 1239 1240@Entry 1241@Component 1242struct WebComponent { 1243 controller: webview.WebviewController = new webview.WebviewController(); 1244 1245 build() { 1246 Column() { 1247 Button('accessBackward') 1248 .onClick(() => { 1249 try { 1250 let result = this.controller.accessBackward(); 1251 console.log('result:' + result); 1252 } catch (error) { 1253 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1254 } 1255 }) 1256 Web({ src: 'www.example.com', controller: this.controller }) 1257 } 1258 } 1259} 1260``` 1261 1262### backward 1263 1264backward(): void 1265 1266Moves to the previous page based on the history stack. This API is generally used together with **accessBackward**. 1267 1268**System capability**: SystemCapability.Web.Webview.Core 1269 1270**Error codes** 1271 1272For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1273 1274| ID| Error Message | 1275| -------- | ------------------------------------------------------------ | 1276| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1277 1278**Example** 1279 1280```ts 1281// xxx.ets 1282import { webview } from '@kit.ArkWeb'; 1283import { BusinessError } from '@kit.BasicServicesKit'; 1284 1285@Entry 1286@Component 1287struct WebComponent { 1288 controller: webview.WebviewController = new webview.WebviewController(); 1289 1290 build() { 1291 Column() { 1292 Button('backward') 1293 .onClick(() => { 1294 try { 1295 this.controller.backward(); 1296 } catch (error) { 1297 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1298 } 1299 }) 1300 Web({ src: 'www.example.com', controller: this.controller }) 1301 } 1302 } 1303} 1304``` 1305 1306### onActive 1307 1308onActive(): void 1309 1310Called when the **Web** component enters the active state. 1311<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). 1312 1313**System capability**: SystemCapability.Web.Webview.Core 1314 1315**Error codes** 1316 1317For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1318 1319| ID| Error Message | 1320| -------- | ------------------------------------------------------------ | 1321| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1322 1323**Example** 1324 1325```ts 1326// xxx.ets 1327import { webview } from '@kit.ArkWeb'; 1328import { BusinessError } from '@kit.BasicServicesKit'; 1329 1330@Entry 1331@Component 1332struct WebComponent { 1333 controller: webview.WebviewController = new webview.WebviewController(); 1334 1335 build() { 1336 Column() { 1337 Button('onActive') 1338 .onClick(() => { 1339 try { 1340 this.controller.onActive(); 1341 } catch (error) { 1342 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1343 } 1344 }) 1345 Web({ src: 'www.example.com', controller: this.controller }) 1346 } 1347 } 1348} 1349``` 1350 1351### onInactive 1352 1353onInactive(): void 1354 1355Called when the **Web** component enters the inactive state. You can implement the behavior to perform after the application loses focus. 1356 1357When 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). 1358 1359**System capability**: SystemCapability.Web.Webview.Core 1360 1361**Error codes** 1362 1363For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1364 1365| ID| Error Message | 1366| -------- | ------------------------------------------------------------ | 1367| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1368 1369**Example** 1370 1371```ts 1372// xxx.ets 1373import { webview } from '@kit.ArkWeb'; 1374import { BusinessError } from '@kit.BasicServicesKit'; 1375 1376@Entry 1377@Component 1378struct WebComponent { 1379 controller: webview.WebviewController = new webview.WebviewController(); 1380 1381 build() { 1382 Column() { 1383 Button('onInactive') 1384 .onClick(() => { 1385 try { 1386 this.controller.onInactive(); 1387 } catch (error) { 1388 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1389 } 1390 }) 1391 Web({ src: 'www.example.com', controller: this.controller }) 1392 } 1393 } 1394} 1395``` 1396 1397### refresh 1398refresh(): void 1399 1400Called when the **Web** component refreshes the web page. 1401 1402**System capability**: SystemCapability.Web.Webview.Core 1403 1404**Error codes** 1405 1406For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1407 1408| ID| Error Message | 1409| -------- | ------------------------------------------------------------ | 1410| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1411 1412**Example** 1413 1414```ts 1415// xxx.ets 1416import { webview } from '@kit.ArkWeb'; 1417import { BusinessError } from '@kit.BasicServicesKit'; 1418 1419@Entry 1420@Component 1421struct WebComponent { 1422 controller: webview.WebviewController = new webview.WebviewController(); 1423 1424 build() { 1425 Column() { 1426 Button('refresh') 1427 .onClick(() => { 1428 try { 1429 this.controller.refresh(); 1430 } catch (error) { 1431 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1432 } 1433 }) 1434 Web({ src: 'www.example.com', controller: this.controller }) 1435 } 1436 } 1437} 1438``` 1439 1440### accessStep 1441 1442accessStep(step: number): boolean 1443 1444Checks whether a specific number of steps forward or backward can be performed on the current page. 1445 1446**System capability**: SystemCapability.Web.Webview.Core 1447 1448**Parameters** 1449 1450| Name| Type| Mandatory| Description | 1451| ------ | -------- | ---- | ------------------------------------------ | 1452| step | number | Yes | Number of the steps to take. A positive number means to move forward, and a negative number means to move backward.| 1453 1454**Return value** 1455 1456| Type | Description | 1457| ------- | ------------------ | 1458| boolean | Whether moving forward or backward is performed on the current page.| 1459 1460**Error codes** 1461 1462For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1463 1464| ID| Error Message | 1465| -------- | ------------------------------------------------------------ | 1466| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1467| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1468 1469**Example** 1470 1471```ts 1472// xxx.ets 1473import { webview } from '@kit.ArkWeb'; 1474import { BusinessError } from '@kit.BasicServicesKit'; 1475 1476@Entry 1477@Component 1478struct WebComponent { 1479 controller: webview.WebviewController = new webview.WebviewController(); 1480 @State steps: number = 2; 1481 1482 build() { 1483 Column() { 1484 Button('accessStep') 1485 .onClick(() => { 1486 try { 1487 let result = this.controller.accessStep(this.steps); 1488 console.log('result:' + result); 1489 } catch (error) { 1490 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1491 } 1492 }) 1493 Web({ src: 'www.example.com', controller: this.controller }) 1494 } 1495 } 1496} 1497``` 1498 1499### clearHistory 1500 1501clearHistory(): void 1502 1503Clears the browsing history. You are not advised to call **clearHistory()** in **onErrorReceive()** and **onPageBegin()**. Otherwise, abnormal exit occurs. 1504 1505**System capability**: SystemCapability.Web.Webview.Core 1506 1507**Error codes** 1508 1509For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1510 1511| ID| Error Message | 1512| -------- | ------------------------------------------------------------ | 1513| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1514 1515**Example** 1516 1517```ts 1518// xxx.ets 1519import { webview } from '@kit.ArkWeb'; 1520import { BusinessError } from '@kit.BasicServicesKit'; 1521 1522@Entry 1523@Component 1524struct WebComponent { 1525 controller: webview.WebviewController = new webview.WebviewController(); 1526 1527 build() { 1528 Column() { 1529 Button('clearHistory') 1530 .onClick(() => { 1531 try { 1532 this.controller.clearHistory(); 1533 } catch (error) { 1534 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1535 } 1536 }) 1537 Web({ src: 'www.example.com', controller: this.controller }) 1538 } 1539 } 1540} 1541``` 1542 1543### getHitTest<sup>(deprecated)</sup> 1544 1545getHitTest(): WebHitTestType 1546 1547Obtains the element type of the area being clicked. 1548 1549> **NOTE** 1550> 1551> This API is supported since API version 11 and deprecated since API version 18. You are advised to use [getLastHitTest](#getlasthittest18) instead. 1552 1553**System capability**: SystemCapability.Web.Webview.Core 1554 1555**Return value** 1556 1557| Type | Description | 1558| ------------------------------------------------------------ | ---------------------- | 1559| [WebHitTestType](#webhittesttype)| Element type of the area being clicked.| 1560 1561**Error codes** 1562 1563For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1564 1565| ID| Error Message | 1566| -------- | ------------------------------------------------------------ | 1567| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1568 1569**Example** 1570 1571```ts 1572// xxx.ets 1573import { webview } from '@kit.ArkWeb'; 1574import { BusinessError } from '@kit.BasicServicesKit'; 1575 1576@Entry 1577@Component 1578struct WebComponent { 1579 controller: webview.WebviewController = new webview.WebviewController(); 1580 1581 build() { 1582 Column() { 1583 Button('getHitTest') 1584 .onClick(() => { 1585 try { 1586 let hitTestType = this.controller.getHitTest(); 1587 console.log("hitTestType: " + hitTestType); 1588 } catch (error) { 1589 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1590 } 1591 }) 1592 Web({ src: 'www.example.com', controller: this.controller }) 1593 } 1594 } 1595} 1596``` 1597 1598### registerJavaScriptProxy 1599 1600registerJavaScriptProxy(object: object, name: string, methodList: Array\<string>, asyncMethodList?: Array\<string>, permission?: string): void 1601 1602Registers a proxy for interaction between the application and web pages loaded by the **Web** component. 1603<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. 1604 1605> **NOTE** 1606> 1607> - The **registerJavaScriptProxy** API must be used together with the **deleteJavaScriptRegister** API to prevent memory leak. 1608> - 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. 1609> - After **registerJavaScriptProxy** is called, the application exposes the registered JavaScript object to all page frames. 1610> - If a **registerJavaScriptProxy** is both registered in the synchronous and asynchronous lists, it is called asynchronously by default. 1611> - You should register **registerJavaScriptProxy** either in synchronous list or in asynchronous list. Otherwise, this API fails to be registered. 1612 1613**System capability**: SystemCapability.Web.Webview.Core 1614 1615**Parameters** 1616 1617| Name | Type | Mandatory| Description | 1618| ---------- | -------------- | ---- | ------------------------------------------------------------ | 1619| object | object | Yes | Application-side JavaScript object to be registered. Methods and attributes can be declared separately, but cannot be registered and used at the same time. If an object contains only attributes, HTML5 can access the attributes in the object. If an object contains only methods, HTML5 can access the methods in the object.<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).| 1620| 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.| 1621| methodList | Array\<string> | Yes | Synchronous methods of the JavaScript object to be registered at the application side. | 1622| 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. | 1623| 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).| 1624 1625**Error codes** 1626 1627For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1628 1629| ID| Error Message | 1630| -------- | ------------------------------------------------------------ | 1631| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1632| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1633 1634**Example** 1635 1636```ts 1637// xxx.ets 1638import { webview } from '@kit.ArkWeb'; 1639import { BusinessError } from '@kit.BasicServicesKit'; 1640 1641class TestObj { 1642 constructor() { 1643 } 1644 1645 test(testStr: string): string { 1646 console.log('Web Component str' + testStr); 1647 return testStr; 1648 } 1649 1650 toString(): void { 1651 console.log('Web Component toString'); 1652 } 1653 1654 testNumber(testNum: number): number { 1655 console.log('Web Component number' + testNum); 1656 return testNum; 1657 } 1658 1659 asyncTestBool(testBol: boolean): void { 1660 console.log('Web Component boolean' + testBol); 1661 } 1662} 1663 1664class WebObj { 1665 constructor() { 1666 } 1667 1668 webTest(): string { 1669 console.log('Web test'); 1670 return "Web test"; 1671 } 1672 1673 webString(): void { 1674 console.log('Web test toString'); 1675 } 1676} 1677 1678class AsyncObj { 1679 constructor() { 1680 } 1681 1682 asyncTest(): void { 1683 console.log('Async test'); 1684 } 1685 1686 asyncString(testStr: string): void { 1687 console.log('Web async string' + testStr); 1688 } 1689} 1690 1691@Entry 1692@Component 1693struct Index { 1694 controller: webview.WebviewController = new webview.WebviewController(); 1695 @State testObjtest: TestObj = new TestObj(); 1696 @State webTestObj: WebObj = new WebObj(); 1697 @State asyncTestObj: AsyncObj = new AsyncObj(); 1698 1699 build() { 1700 Column() { 1701 Button('refresh') 1702 .onClick(() => { 1703 try { 1704 this.controller.refresh(); 1705 } catch (error) { 1706 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1707 } 1708 }) 1709 Button('Register JavaScript To Window') 1710 .onClick(() => { 1711 try { 1712 // Register both synchronous and asynchronous functions. 1713 this.controller.registerJavaScriptProxy(this.testObjtest, "objName", ["test", "toString", "testNumber"], ["asyncTestBool"]); 1714 // Register only the synchronous function. 1715 this.controller.registerJavaScriptProxy(this.webTestObj, "objTestName", ["webTest", "webString"]); 1716 // Register only the asynchronous function. 1717 this.controller.registerJavaScriptProxy(this.asyncTestObj, "objAsyncName", [], ["asyncTest", "asyncString"]); 1718 } catch (error) { 1719 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1720 } 1721 }) 1722 Button('deleteJavaScriptRegister') 1723 .onClick(() => { 1724 try { 1725 this.controller.deleteJavaScriptRegister("objName"); 1726 this.controller.deleteJavaScriptRegister("objTestName"); 1727 this.controller.deleteJavaScriptRegister("objAsyncName"); 1728 } catch (error) { 1729 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1730 } 1731 }) 1732 Web({ src: $rawfile('index.html'), controller: this.controller }) 1733 .javaScriptAccess(true) 1734 } 1735 } 1736} 1737``` 1738 1739HTML file to be loaded: 1740```html 1741<!-- index.html --> 1742<!DOCTYPE html> 1743<html> 1744 <meta charset="utf-8"> 1745 <body> 1746 <button type="button" onclick="htmlTest()">Click Me!</button> 1747 <p id="demo"></p> 1748 <p id="webDemo"></p> 1749 <p id="asyncDemo"></p> 1750 </body> 1751 <script type="text/javascript"> 1752 function htmlTest() { 1753 // This function call expects to return "ArkUI Web Component" 1754 let str=objName.test("webtest data"); 1755 objName.testNumber(1); 1756 objName.asyncTestBool(true); 1757 document.getElementById("demo").innerHTML=str; 1758 console.log('objName.test result:'+ str) 1759 1760 // This function call expects to return "Web test" 1761 let webStr = objTestName.webTest(); 1762 document.getElementById("webDemo").innerHTML=webStr; 1763 console.log('objTestName.webTest result:'+ webStr) 1764 1765 objAsyncName.asyncTest(); 1766 objAsyncName.asyncString("async test data"); 1767 } 1768</script> 1769</html> 1770``` 1771For more examples, see [Invoking Application Functions on the Frontend Page](../../web/web-in-page-app-function-invoking.md). 1772 1773### runJavaScript 1774 1775runJavaScript(script: string, callback : AsyncCallback\<string>): void 1776 1777Executes 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**. 1778 1779> **NOTE** 1780> 1781> The offscreen component does not trigger **runJavaScript()**. 1782 1783**System capability**: SystemCapability.Web.Webview.Core 1784 1785**Parameters** 1786 1787| Name | Type | Mandatory| Description | 1788| -------- | -------------------- | ---- | ---------------------------- | 1789| script | string | Yes | JavaScript script. | 1790| 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.| 1791 1792**Error codes** 1793 1794For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1795 1796| ID| Error Message | 1797| -------- | ------------------------------------------------------------ | 1798| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1799| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1800 1801**Example** 1802 1803```ts 1804import { webview } from '@kit.ArkWeb'; 1805import { BusinessError } from '@kit.BasicServicesKit'; 1806 1807@Entry 1808@Component 1809struct WebComponent { 1810 controller: webview.WebviewController = new webview.WebviewController(); 1811 @State webResult: string = ''; 1812 1813 build() { 1814 Column() { 1815 Text(this.webResult).fontSize(20) 1816 Web({ src: $rawfile('index.html'), controller: this.controller }) 1817 .javaScriptAccess(true) 1818 .onPageEnd(e => { 1819 try { 1820 this.controller.runJavaScript( 1821 'test()', 1822 (error, result) => { 1823 if (error) { 1824 console.error(`run JavaScript error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1825 return; 1826 } 1827 if (result) { 1828 this.webResult = result; 1829 console.info(`The test() return value is: ${result}`); 1830 } 1831 }); 1832 if (e) { 1833 console.info('url: ', e.url); 1834 } 1835 } catch (error) { 1836 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1837 } 1838 }) 1839 } 1840 } 1841} 1842``` 1843 1844HTML file to be loaded: 1845```html 1846<!-- index.html --> 1847<!DOCTYPE html> 1848<html> 1849 <meta charset="utf-8"> 1850 <body> 1851 Hello world! 1852 </body> 1853 <script type="text/javascript"> 1854 function test() { 1855 console.log('Ark WebComponent') 1856 return "This value is from index.html" 1857 } 1858 </script> 1859</html> 1860``` 1861 1862### runJavaScript 1863 1864runJavaScript(script: string): Promise\<string> 1865 1866Executes 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**. 1867 1868**System capability**: SystemCapability.Web.Webview.Core 1869 1870**Parameters** 1871 1872| Name| Type| Mandatory| Description | 1873| ------ | -------- | ---- | ---------------- | 1874| script | string | Yes | JavaScript script.| 1875 1876**Return value** 1877 1878| Type | Description | 1879| --------------- | --------------------------------------------------- | 1880| Promise\<string> | Promise used to return the result if the operation is successful and null otherwise.| 1881 1882**Error codes** 1883 1884For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1885 1886| ID| Error Message | 1887| -------- | ------------------------------------------------------------ | 1888| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1889| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1890 1891**Example** 1892 1893```ts 1894// xxx.ets 1895import { webview } from '@kit.ArkWeb'; 1896import { BusinessError } from '@kit.BasicServicesKit'; 1897 1898@Entry 1899@Component 1900struct WebComponent { 1901 controller: webview.WebviewController = new webview.WebviewController(); 1902 1903 build() { 1904 Column() { 1905 Web({ src: $rawfile('index.html'), controller: this.controller }) 1906 .javaScriptAccess(true) 1907 .onPageEnd(e => { 1908 try { 1909 this.controller.runJavaScript('test()') 1910 .then((result) => { 1911 console.log('result: ' + result); 1912 }) 1913 .catch((error: BusinessError) => { 1914 console.error("error: " + error); 1915 }) 1916 if (e) { 1917 console.info('url: ', e.url); 1918 } 1919 } catch (error) { 1920 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1921 } 1922 }) 1923 } 1924 } 1925} 1926``` 1927 1928HTML file to be loaded: 1929```html 1930<!-- index.html --> 1931<!DOCTYPE html> 1932<html> 1933 <meta charset="utf-8"> 1934 <body> 1935 Hello world! 1936 </body> 1937 <script type="text/javascript"> 1938 function test() { 1939 console.log('Ark WebComponent') 1940 return "This value is from index.html" 1941 } 1942 </script> 1943</html> 1944``` 1945 1946### runJavaScriptExt<sup>10+</sup> 1947 1948runJavaScriptExt(script: string | ArrayBuffer, callback : AsyncCallback\<JsMessageExt>): void 1949 1950Executes 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**. 1951 1952**System capability**: SystemCapability.Web.Webview.Core 1953 1954**Parameters** 1955 1956| Name | Type | Mandatory| Description | 1957| -------- | -------------------- | ---- | ---------------------------- | 1958| script | string \| ArrayBuffer<sup>12+</sup> | Yes | JavaScript script.| 1959| callback | AsyncCallback\<[JsMessageExt](#jsmessageext10)\> | Yes | Callback used to return the result.| 1960 1961**Error codes** 1962 1963For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1964 1965| ID| Error Message | 1966| -------- | ------------------------------------------------------------ | 1967| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1968| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1969 1970**Example** 1971 1972```ts 1973import { webview } from '@kit.ArkWeb'; 1974import { BusinessError } from '@kit.BasicServicesKit'; 1975 1976@Entry 1977@Component 1978struct WebComponent { 1979 controller: webview.WebviewController = new webview.WebviewController(); 1980 @State msg1: string = ''; 1981 @State msg2: string = ''; 1982 1983 build() { 1984 Column() { 1985 Text(this.msg1).fontSize(20) 1986 Text(this.msg2).fontSize(20) 1987 Web({ src: $rawfile('index.html'), controller: this.controller }) 1988 .javaScriptAccess(true) 1989 .onPageEnd(e => { 1990 try { 1991 this.controller.runJavaScriptExt( 1992 'test()', 1993 (error, result) => { 1994 if (error) { 1995 console.error(`run JavaScript error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`) 1996 return; 1997 } 1998 if (result) { 1999 try { 2000 let type = result.getType(); 2001 switch (type) { 2002 case webview.JsMessageType.STRING: { 2003 this.msg1 = "result type:" + typeof (result.getString()); 2004 this.msg2 = "result getString:" + ((result.getString())); 2005 break; 2006 } 2007 case webview.JsMessageType.NUMBER: { 2008 this.msg1 = "result type:" + typeof (result.getNumber()); 2009 this.msg2 = "result getNumber:" + ((result.getNumber())); 2010 break; 2011 } 2012 case webview.JsMessageType.BOOLEAN: { 2013 this.msg1 = "result type:" + typeof (result.getBoolean()); 2014 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 2015 break; 2016 } 2017 case webview.JsMessageType.ARRAY_BUFFER: { 2018 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 2019 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 2020 break; 2021 } 2022 case webview.JsMessageType.ARRAY: { 2023 this.msg1 = "result type:" + typeof (result.getArray()); 2024 this.msg2 = "result getArray:" + result.getArray(); 2025 break; 2026 } 2027 default: { 2028 this.msg1 = "default break, type:" + type; 2029 break; 2030 } 2031 } 2032 } 2033 catch (resError) { 2034 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2035 } 2036 } 2037 }); 2038 if (e) { 2039 console.info('url: ', e.url); 2040 } 2041 } catch (error) { 2042 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2043 } 2044 }) 2045 } 2046 } 2047} 2048``` 2049 2050```ts 2051// Use the ArrayBuffer input parameter to obtain the JavaScript script data from the file. 2052import { webview } from '@kit.ArkWeb'; 2053import { BusinessError } from '@kit.BasicServicesKit'; 2054import { fileIo } from '@kit.CoreFileKit'; 2055import { common } from '@kit.AbilityKit'; 2056 2057@Entry 2058@Component 2059struct WebComponent { 2060 controller: webview.WebviewController = new webview.WebviewController(); 2061 @State msg1: string = '' 2062 @State msg2: string = '' 2063 2064 build() { 2065 Column() { 2066 Text(this.msg1).fontSize(20) 2067 Text(this.msg2).fontSize(20) 2068 Button('runJavaScriptExt') 2069 .onClick(() => { 2070 try { 2071 let context = getContext(this) as common.UIAbilityContext; 2072 let filePath = context.filesDir + 'test.txt'; 2073 // Create a file and open it. 2074 let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); 2075 // Write data to the file. 2076 fileIo.writeSync(file.fd, "test()"); 2077 // Read data from the file. 2078 let arrayBuffer: ArrayBuffer = new ArrayBuffer(6); 2079 fileIo.readSync(file.fd, arrayBuffer, { offset: 0, length: arrayBuffer.byteLength }); 2080 // Close the file. 2081 fileIo.closeSync(file); 2082 this.controller.runJavaScriptExt( 2083 arrayBuffer, 2084 (error, result) => { 2085 if (error) { 2086 console.error(`run JavaScript error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`) 2087 return; 2088 } 2089 if (result) { 2090 try { 2091 let type = result.getType(); 2092 switch (type) { 2093 case webview.JsMessageType.STRING: { 2094 this.msg1 = "result type:" + typeof (result.getString()); 2095 this.msg2 = "result getString:" + ((result.getString())); 2096 break; 2097 } 2098 case webview.JsMessageType.NUMBER: { 2099 this.msg1 = "result type:" + typeof (result.getNumber()); 2100 this.msg2 = "result getNumber:" + ((result.getNumber())); 2101 break; 2102 } 2103 case webview.JsMessageType.BOOLEAN: { 2104 this.msg1 = "result type:" + typeof (result.getBoolean()); 2105 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 2106 break; 2107 } 2108 case webview.JsMessageType.ARRAY_BUFFER: { 2109 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 2110 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 2111 break; 2112 } 2113 case webview.JsMessageType.ARRAY: { 2114 this.msg1 = "result type:" + typeof (result.getArray()); 2115 this.msg2 = "result getArray:" + result.getArray(); 2116 break; 2117 } 2118 default: { 2119 this.msg1 = "default break, type:" + type; 2120 break; 2121 } 2122 } 2123 } 2124 catch (resError) { 2125 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2126 } 2127 } 2128 }); 2129 } catch (error) { 2130 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2131 } 2132 }) 2133 Web({ src: $rawfile('index.html'), controller: this.controller }) 2134 .javaScriptAccess(true) 2135 } 2136 } 2137} 2138``` 2139 2140HTML file to be loaded: 2141```html 2142<!-- index.html --> 2143<!DOCTYPE html> 2144<html lang="en-gb"> 2145<body> 2146<h1>run JavaScript Ext demo</h1> 2147</body> 2148<script type="text/javascript"> 2149function test() { 2150 return "hello, world"; 2151} 2152</script> 2153</html> 2154``` 2155 2156### runJavaScriptExt<sup>10+</sup> 2157 2158runJavaScriptExt(script: string | ArrayBuffer): Promise\<JsMessageExt> 2159 2160Executes 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**. 2161 2162**System capability**: SystemCapability.Web.Webview.Core 2163 2164**Parameters** 2165 2166| Name| Type| Mandatory| Description | 2167| ------ | -------- | ---- | ---------------- | 2168| script | string \| ArrayBuffer<sup>12+</sup> | Yes | JavaScript script.| 2169 2170**Return value** 2171 2172| Type | Description | 2173| --------------- | --------------------------------------------------- | 2174| Promise\<[JsMessageExt](#jsmessageext10)> | Promise used to return the script execution result.| 2175 2176**Error codes** 2177 2178For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2179 2180| ID| Error Message | 2181| -------- | ------------------------------------------------------------ | 2182| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2183| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2184 2185**Example** 2186 2187```ts 2188// xxx.ets 2189import { webview } from '@kit.ArkWeb'; 2190import { BusinessError } from '@kit.BasicServicesKit'; 2191 2192@Entry 2193@Component 2194struct WebComponent { 2195 controller: webview.WebviewController = new webview.WebviewController(); 2196 @State webResult: string = ''; 2197 @State msg1: string = ''; 2198 @State msg2: string = ''; 2199 2200 build() { 2201 Column() { 2202 Text(this.webResult).fontSize(20) 2203 Text(this.msg1).fontSize(20) 2204 Text(this.msg2).fontSize(20) 2205 Web({ src: $rawfile('index.html'), controller: this.controller }) 2206 .javaScriptAccess(true) 2207 .onPageEnd(() => { 2208 this.controller.runJavaScriptExt('test()') 2209 .then((result) => { 2210 try { 2211 let type = result.getType(); 2212 switch (type) { 2213 case webview.JsMessageType.STRING: { 2214 this.msg1 = "result type:" + typeof (result.getString()); 2215 this.msg2 = "result getString:" + ((result.getString())); 2216 break; 2217 } 2218 case webview.JsMessageType.NUMBER: { 2219 this.msg1 = "result type:" + typeof (result.getNumber()); 2220 this.msg2 = "result getNumber:" + ((result.getNumber())); 2221 break; 2222 } 2223 case webview.JsMessageType.BOOLEAN: { 2224 this.msg1 = "result type:" + typeof (result.getBoolean()); 2225 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 2226 break; 2227 } 2228 case webview.JsMessageType.ARRAY_BUFFER: { 2229 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 2230 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 2231 break; 2232 } 2233 case webview.JsMessageType.ARRAY: { 2234 this.msg1 = "result type:" + typeof (result.getArray()); 2235 this.msg2 = "result getArray:" + result.getArray(); 2236 break; 2237 } 2238 default: { 2239 this.msg1 = "default break, type:" + type; 2240 break; 2241 } 2242 } 2243 } 2244 catch (resError) { 2245 console.error(`ErrorCode: ${(resError as BusinessError).code}, Message: ${(resError as BusinessError).message}`); 2246 } 2247 }).catch((error: BusinessError) => { 2248 console.error("error: " + error); 2249 }) 2250 }) 2251 } 2252 } 2253} 2254``` 2255 2256```ts 2257// Use the ArrayBuffer input parameter to obtain the JavaScript script data from the file. 2258import { webview } from '@kit.ArkWeb'; 2259import { BusinessError } from '@kit.BasicServicesKit'; 2260import { fileIo } from '@kit.CoreFileKit'; 2261import { common } from '@kit.AbilityKit'; 2262 2263@Entry 2264@Component 2265struct WebComponent { 2266 controller: webview.WebviewController = new webview.WebviewController(); 2267 @State msg1: string = ''; 2268 @State msg2: string = ''; 2269 2270 build() { 2271 Column() { 2272 Text(this.msg1).fontSize(20) 2273 Text(this.msg2).fontSize(20) 2274 Button('runJavaScriptExt') 2275 .onClick(() => { 2276 try { 2277 let context = getContext(this) as common.UIAbilityContext; 2278 let filePath = context.filesDir + 'test.txt'; 2279 // Create a file and open it. 2280 let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); 2281 // Write data to the file. 2282 fileIo.writeSync(file.fd, "test()"); 2283 // Read data from the file. 2284 let arrayBuffer: ArrayBuffer = new ArrayBuffer(6); 2285 fileIo.readSync(file.fd, arrayBuffer, { offset: 0, length: arrayBuffer.byteLength }); 2286 // Close the file. 2287 fileIo.closeSync(file); 2288 this.controller.runJavaScriptExt(arrayBuffer) 2289 .then((result) => { 2290 try { 2291 let type = result.getType(); 2292 switch (type) { 2293 case webview.JsMessageType.STRING: { 2294 this.msg1 = "result type:" + typeof (result.getString()); 2295 this.msg2 = "result getString:" + ((result.getString())); 2296 break; 2297 } 2298 case webview.JsMessageType.NUMBER: { 2299 this.msg1 = "result type:" + typeof (result.getNumber()); 2300 this.msg2 = "result getNumber:" + ((result.getNumber())); 2301 break; 2302 } 2303 case webview.JsMessageType.BOOLEAN: { 2304 this.msg1 = "result type:" + typeof (result.getBoolean()); 2305 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 2306 break; 2307 } 2308 case webview.JsMessageType.ARRAY_BUFFER: { 2309 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 2310 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 2311 break; 2312 } 2313 case webview.JsMessageType.ARRAY: { 2314 this.msg1 = "result type:" + typeof (result.getArray()); 2315 this.msg2 = "result getArray:" + result.getArray(); 2316 break; 2317 } 2318 default: { 2319 this.msg1 = "default break, type:" + type; 2320 break; 2321 } 2322 } 2323 } 2324 catch (resError) { 2325 console.error(`ErrorCode: ${(resError as BusinessError).code}, Message: ${(resError as BusinessError).message}`); 2326 } 2327 }) 2328 .catch((error: BusinessError) => { 2329 console.error("error: " + error); 2330 }) 2331 } catch (error) { 2332 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2333 } 2334 }) 2335 Web({ src: $rawfile('index.html'), controller: this.controller }) 2336 .javaScriptAccess(true) 2337 } 2338 } 2339} 2340``` 2341 2342HTML file to be loaded: 2343```html 2344<!-- index.html --> 2345<!DOCTYPE html> 2346<html lang="en-gb"> 2347<body> 2348<h1>run JavaScript Ext demo</h1> 2349</body> 2350<script type="text/javascript"> 2351function test() { 2352 return "hello, world"; 2353} 2354</script> 2355</html> 2356``` 2357 2358### deleteJavaScriptRegister 2359 2360deleteJavaScriptRegister(name: string): void 2361 2362Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. After the deletion, the [refresh](#refresh) API must be called. 2363 2364**System capability**: SystemCapability.Web.Webview.Core 2365 2366**Parameters** 2367 2368| Name| Type| Mandatory| Description | 2369| ------ | -------- | ---- | ---- | 2370| 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.| 2371 2372**Error codes** 2373 2374For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2375 2376| ID| Error Message | 2377| -------- | ------------------------------------------------------------ | 2378| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2379| 17100008 | Failed to delete JavaScriptProxy because it does not exist. | 2380| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2381 2382**Example** 2383 2384```ts 2385// xxx.ets 2386import { webview } from '@kit.ArkWeb'; 2387import { BusinessError } from '@kit.BasicServicesKit'; 2388 2389class TestObj { 2390 constructor() { 2391 } 2392 2393 test(): string { 2394 return "ArkUI Web Component"; 2395 } 2396 2397 toString(): void { 2398 console.log('Web Component toString'); 2399 } 2400} 2401 2402@Entry 2403@Component 2404struct WebComponent { 2405 controller: webview.WebviewController = new webview.WebviewController(); 2406 @State testObjtest: TestObj = new TestObj(); 2407 @State name: string = 'objName'; 2408 build() { 2409 Column() { 2410 Button('refresh') 2411 .onClick(() => { 2412 try { 2413 this.controller.refresh(); 2414 } catch (error) { 2415 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2416 } 2417 }) 2418 Button('Register JavaScript To Window') 2419 .onClick(() => { 2420 try { 2421 this.controller.registerJavaScriptProxy(this.testObjtest, this.name, ["test", "toString"]); 2422 } catch (error) { 2423 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2424 } 2425 }) 2426 Button('deleteJavaScriptRegister') 2427 .onClick(() => { 2428 try { 2429 this.controller.deleteJavaScriptRegister(this.name); 2430 } catch (error) { 2431 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2432 } 2433 }) 2434 Web({ src: $rawfile('index.html'), controller: this.controller }) 2435 .javaScriptAccess(true) 2436 } 2437 } 2438} 2439``` 2440 2441HTML file to be loaded: 2442```html 2443<!-- index.html --> 2444<!DOCTYPE html> 2445<html> 2446 <meta charset="utf-8"> 2447 <body> 2448 <button type="button" onclick="htmlTest()">Click Me!</button> 2449 <p id="demo"></p> 2450 </body> 2451 <script type="text/javascript"> 2452 function htmlTest() { 2453 let str=objName.test(); 2454 document.getElementById("demo").innerHTML=str; 2455 console.log('objName.test result:'+ str) 2456 } 2457</script> 2458</html> 2459``` 2460 2461### zoom 2462 2463zoom(factor: number): void 2464 2465Zooms in or out of this web page. This API is effective only when [zoomAccess](ts-basic-components-web.md#zoomaccess) is **true**. 2466 2467**System capability**: SystemCapability.Web.Webview.Core 2468 2469**Parameters** 2470 2471| Name| Type| Mandatory| Description| 2472| ------ | -------- | ---- | ------------------------------------------------------------ | 2473| 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.| 2474 2475**Error codes** 2476 2477For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2478 2479| ID| Error Message | 2480| -------- | ------------------------------------------------------------ | 2481| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2482| 17100004 | Function not enabled. | 2483| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2484 2485**Example** 2486 2487```ts 2488// xxx.ets 2489import { webview } from '@kit.ArkWeb'; 2490import { BusinessError } from '@kit.BasicServicesKit'; 2491 2492@Entry 2493@Component 2494struct WebComponent { 2495 controller: webview.WebviewController = new webview.WebviewController(); 2496 @State factor: number = 1; 2497 2498 build() { 2499 Column() { 2500 Button('zoom') 2501 .onClick(() => { 2502 try { 2503 this.controller.zoom(this.factor); 2504 } catch (error) { 2505 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2506 } 2507 }) 2508 Web({ src: 'www.example.com', controller: this.controller }) 2509 .zoomAccess(true) 2510 } 2511 } 2512} 2513``` 2514 2515### searchAllAsync 2516 2517searchAllAsync(searchString: string): void 2518 2519Searches 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). 2520 2521**System capability**: SystemCapability.Web.Webview.Core 2522 2523**Parameters** 2524 2525| Name | Type| Mandatory| Description | 2526| ------------ | -------- | ---- | -------------- | 2527| searchString | string | Yes | Search keyword.| 2528 2529**Error codes** 2530 2531For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2532 2533| ID| Error Message | 2534| -------- | ------------------------------------------------------------ | 2535| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2536| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2537 2538**Example** 2539 2540```ts 2541// xxx.ets 2542import { webview } from '@kit.ArkWeb'; 2543import { BusinessError } from '@kit.BasicServicesKit'; 2544 2545@Entry 2546@Component 2547struct WebComponent { 2548 controller: webview.WebviewController = new webview.WebviewController(); 2549 @State searchString: string = "Hello World"; 2550 2551 build() { 2552 Column() { 2553 Button('searchString') 2554 .onClick(() => { 2555 try { 2556 this.controller.searchAllAsync(this.searchString); 2557 } catch (error) { 2558 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2559 } 2560 }) 2561 Web({ src: $rawfile('index.html'), controller: this.controller }) 2562 .onSearchResultReceive(ret => { 2563 if (ret) { 2564 console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal + 2565 "[total]" + ret.numberOfMatches + "[isDone]" + ret.isDoneCounting); 2566 } 2567 }) 2568 } 2569 } 2570} 2571``` 2572 2573HTML file to be loaded: 2574```html 2575<!-- index.html --> 2576<!DOCTYPE html> 2577<html> 2578 <body> 2579 <p>Hello World Highlight Hello World</p> 2580 </body> 2581</html> 2582``` 2583 2584### clearMatches 2585 2586clearMatches(): void 2587 2588Clears the matches found through [searchAllAsync](#searchallasync). 2589 2590**System capability**: SystemCapability.Web.Webview.Core 2591 2592**Error codes** 2593 2594For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2595 2596| ID| Error Message | 2597| -------- | ------------------------------------------------------------ | 2598| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2599 2600**Example** 2601 2602```ts 2603// xxx.ets 2604import { webview } from '@kit.ArkWeb'; 2605import { BusinessError } from '@kit.BasicServicesKit'; 2606 2607@Entry 2608@Component 2609struct WebComponent { 2610 controller: webview.WebviewController = new webview.WebviewController(); 2611 2612 build() { 2613 Column() { 2614 Button('clearMatches') 2615 .onClick(() => { 2616 try { 2617 this.controller.clearMatches(); 2618 } catch (error) { 2619 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2620 } 2621 }) 2622 Web({ src: $rawfile('index.html'), controller: this.controller }) 2623 } 2624 } 2625} 2626``` 2627 2628For details about the HTML file loaded, see the HMTL file loaded using [searchAllAsync](#searchallasync). 2629 2630### searchNext 2631 2632searchNext(forward: boolean): void 2633 2634Searches for and highlights the next match. 2635 2636**System capability**: SystemCapability.Web.Webview.Core 2637 2638**Parameters** 2639 2640| Name | Type| Mandatory| Description | 2641| ------- | -------- | ---- | ---------------------- | 2642| forward | boolean | Yes | Whether to search forward.| 2643 2644**Error codes** 2645 2646For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2647 2648| ID| Error Message | 2649| -------- | ------------------------------------------------------------ | 2650| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2651| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2652 2653**Example** 2654 2655```ts 2656// xxx.ets 2657import { webview } from '@kit.ArkWeb'; 2658import { BusinessError } from '@kit.BasicServicesKit'; 2659 2660@Entry 2661@Component 2662struct WebComponent { 2663 controller: webview.WebviewController = new webview.WebviewController(); 2664 2665 build() { 2666 Column() { 2667 Button('searchNext') 2668 .onClick(() => { 2669 try { 2670 this.controller.searchNext(true); 2671 } catch (error) { 2672 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2673 } 2674 }) 2675 Web({ src: $rawfile('index.html'), controller: this.controller }) 2676 } 2677 } 2678} 2679``` 2680 2681For details about the HTML file loaded, see the HMTL file loaded using [searchAllAsync](#searchallasync). 2682 2683### clearSslCache 2684 2685clearSslCache(): void 2686 2687Clears the user operation corresponding to the SSL certificate error event recorded by the **Web** component. 2688 2689**System capability**: SystemCapability.Web.Webview.Core 2690 2691**Error codes** 2692 2693For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2694 2695| ID| Error Message | 2696| -------- | ------------------------------------------------------------ | 2697| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2698 2699**Example** 2700 2701```ts 2702// xxx.ets 2703import { webview } from '@kit.ArkWeb'; 2704import { BusinessError } from '@kit.BasicServicesKit'; 2705 2706@Entry 2707@Component 2708struct WebComponent { 2709 controller: webview.WebviewController = new webview.WebviewController(); 2710 2711 build() { 2712 Column() { 2713 Button('clearSslCache') 2714 .onClick(() => { 2715 try { 2716 this.controller.clearSslCache(); 2717 } catch (error) { 2718 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2719 } 2720 }) 2721 Web({ src: 'www.example.com', controller: this.controller }) 2722 } 2723 } 2724} 2725``` 2726 2727### clearClientAuthenticationCache 2728 2729clearClientAuthenticationCache(): void 2730 2731Clears the user operation corresponding to the client certificate request event recorded by the **Web** component. 2732 2733**System capability**: SystemCapability.Web.Webview.Core 2734 2735**Error codes** 2736 2737For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2738 2739| ID| Error Message | 2740| -------- | ------------------------------------------------------------ | 2741| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2742 2743**Example** 2744 2745```ts 2746// xxx.ets 2747import { webview } from '@kit.ArkWeb'; 2748import { BusinessError } from '@kit.BasicServicesKit'; 2749 2750@Entry 2751@Component 2752struct WebComponent { 2753 controller: webview.WebviewController = new webview.WebviewController(); 2754 2755 build() { 2756 Column() { 2757 Button('clearClientAuthenticationCache') 2758 .onClick(() => { 2759 try { 2760 this.controller.clearClientAuthenticationCache(); 2761 } catch (error) { 2762 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2763 } 2764 }) 2765 Web({ src: 'www.example.com', controller: this.controller }) 2766 } 2767 } 2768} 2769``` 2770 2771### createWebMessagePorts 2772 2773createWebMessagePorts(isExtentionType?: boolean): Array\<WebMessagePort> 2774 2775Creates web message ports. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 2776 2777**System capability**: SystemCapability.Web.Webview.Core 2778 2779**Parameters** 2780 2781| Name| Type | Mandatory| Description | 2782| ------ | ---------------------- | ---- | :------------------------------| 2783| 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.| 2784 2785**Return value** 2786 2787| Type | Description | 2788| ---------------------- | ----------------- | 2789| Array\<[WebMessagePort](#webmessageport)> | List of web message ports.| 2790 2791**Error codes** 2792 2793For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2794 2795| ID| Error Message | 2796| -------- | ------------------------------------------------------------ | 2797| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2798| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2799 2800**Example** 2801 2802```ts 2803// xxx.ets 2804import { webview } from '@kit.ArkWeb'; 2805import { BusinessError } from '@kit.BasicServicesKit'; 2806 2807@Entry 2808@Component 2809struct WebComponent { 2810 controller: webview.WebviewController = new webview.WebviewController(); 2811 ports: webview.WebMessagePort[] = []; 2812 2813 build() { 2814 Column() { 2815 Button('createWebMessagePorts') 2816 .onClick(() => { 2817 try { 2818 this.ports = this.controller.createWebMessagePorts(); 2819 console.log("createWebMessagePorts size:" + this.ports.length); 2820 } catch (error) { 2821 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2822 } 2823 }) 2824 Web({ src: 'www.example.com', controller: this.controller }) 2825 } 2826 } 2827} 2828``` 2829 2830### postMessage 2831 2832postMessage(name: string, ports: Array\<WebMessagePort>, uri: string): void 2833 2834Sends a web message to an HTML window. 2835 2836**System capability**: SystemCapability.Web.Webview.Core 2837 2838**Parameters** 2839 2840| Name| Type | Mandatory| Description | 2841| ------ | ---------------------- | ---- | :------------------------------- | 2842| name | string | Yes | Name of the message to send. | 2843| ports | Array\<[WebMessagePort](#webmessageport)> | Yes | Message ports for sending the message. | 2844| uri | string | Yes | URI for receiving the message. | 2845 2846**Error codes** 2847 2848For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2849 2850| ID| Error Message | 2851| -------- | ------------------------------------------------------------ | 2852| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2853| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2854 2855**Example** 2856 2857```ts 2858// xxx.ets 2859import { webview } from '@kit.ArkWeb'; 2860import { BusinessError } from '@kit.BasicServicesKit'; 2861 2862@Entry 2863@Component 2864struct WebComponent { 2865 controller: webview.WebviewController = new webview.WebviewController(); 2866 ports: webview.WebMessagePort[] = []; 2867 @State sendFromEts: string = 'Send this message from ets to HTML'; 2868 @State receivedFromHtml: string = 'Display received message send from HTML'; 2869 2870 build() { 2871 Column() { 2872 // Display the received HTML content. 2873 Text(this.receivedFromHtml) 2874 // Send the content in the text box to an HTML window. 2875 TextInput({ placeholder: 'Send this message from ets to HTML' }) 2876 .onChange((value: string) => { 2877 this.sendFromEts = value; 2878 }) 2879 2880 Button('postMessage') 2881 .onClick(() => { 2882 try { 2883 // 1. Create two message ports. 2884 this.ports = this.controller.createWebMessagePorts(); 2885 // 2. Register a callback on a message port (for example, port 1) on the application side. 2886 this.ports[1].onMessageEvent((result: webview.WebMessage) => { 2887 let msg = 'Got msg from HTML:'; 2888 if (typeof (result) == "string") { 2889 console.log("received string message from html5, string is:" + result); 2890 msg = msg + result; 2891 } else if (typeof (result) == "object") { 2892 if (result instanceof ArrayBuffer) { 2893 console.log("received arraybuffer from html5, length is:" + result.byteLength); 2894 msg = msg + "length is " + result.byteLength; 2895 } else { 2896 console.log("not support"); 2897 } 2898 } else { 2899 console.log("not support"); 2900 } 2901 this.receivedFromHtml = msg; 2902 }) 2903 // 3. Send another message port (for example, port 0) to the HTML side, which can then save the port for future use. 2904 this.controller.postMessage('__init_port__', [this.ports[0]], '*'); 2905 } catch (error) { 2906 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2907 } 2908 }) 2909 2910 // 4. Use the port on the application side to send messages to the port that has been sent to the HTML side. 2911 Button('SendDataToHTML') 2912 .onClick(() => { 2913 try { 2914 if (this.ports && this.ports[1]) { 2915 this.ports[1].postMessageEvent(this.sendFromEts); 2916 } else { 2917 console.error(`ports is null, Please initialize first`); 2918 } 2919 } catch (error) { 2920 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2921 } 2922 }) 2923 Web({ src: $rawfile('index.html'), controller: this.controller }) 2924 } 2925 } 2926} 2927``` 2928 2929HTML file to be loaded: 2930```html 2931<!--index.html--> 2932<!DOCTYPE html> 2933<html> 2934<head> 2935 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 2936 <title>WebView Message Port Demo</title> 2937</head> 2938 2939 <body> 2940 <h1>WebView Message Port Demo</h1> 2941 <div> 2942 <input type="button" value="SendToEts" onclick="PostMsgToEts(msgFromJS.value);"/><br/> 2943 <input id="msgFromJS" type="text" value="send this message from HTML to ets"/><br/> 2944 </div> 2945 <p class="output">display received message send from ets</p> 2946 </body> 2947 <script src="xxx.js"></script> 2948</html> 2949``` 2950 2951```js 2952//xxx.js 2953var h5Port; 2954var output = document.querySelector('.output'); 2955window.addEventListener('message', function (event) { 2956 if (event.data == '__init_port__') { 2957 if (event.ports[0] != null) { 2958 h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side. 2959 h5Port.onmessage = function (event) { 2960 // 2. Receive the message sent from the eTS side. 2961 var msg = 'Got message from ets:'; 2962 var result = event.data; 2963 if (typeof(result) == "string") { 2964 console.log("received string message from html5, string is:" + result); 2965 msg = msg + result; 2966 } else if (typeof(result) == "object") { 2967 if (result instanceof ArrayBuffer) { 2968 console.log("received arraybuffer from html5, length is:" + result.byteLength); 2969 msg = msg + "length is " + result.byteLength; 2970 } else { 2971 console.log("not support"); 2972 } 2973 } else { 2974 console.log("not support"); 2975 } 2976 output.innerHTML = msg; 2977 } 2978 } 2979 } 2980}) 2981 2982// 3. Use h5Port to send messages to the eTS side. 2983function PostMsgToEts(data) { 2984 if (h5Port) { 2985 h5Port.postMessage(data); 2986 } else { 2987 console.error("h5Port is null, Please initialize first"); 2988 } 2989} 2990``` 2991 2992### requestFocus 2993 2994requestFocus(): void 2995 2996Requests focus for this web page. 2997 2998**System capability**: SystemCapability.Web.Webview.Core 2999 3000**Error codes** 3001 3002For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3003 3004| ID| Error Message | 3005| -------- | ------------------------------------------------------------ | 3006| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3007 3008**Example** 3009 3010```ts 3011// xxx.ets 3012import { webview } from '@kit.ArkWeb'; 3013import { BusinessError } from '@kit.BasicServicesKit'; 3014 3015@Entry 3016@Component 3017struct WebComponent { 3018 controller: webview.WebviewController = new webview.WebviewController(); 3019 3020 build() { 3021 Column() { 3022 Button('requestFocus') 3023 .onClick(() => { 3024 try { 3025 this.controller.requestFocus(); 3026 } catch (error) { 3027 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3028 } 3029 }); 3030 Web({ src: 'www.example.com', controller: this.controller }) 3031 } 3032 } 3033} 3034``` 3035 3036### zoomIn 3037 3038zoomIn(): void 3039 3040Zooms in on this web page by 20%. 3041 3042**System capability**: SystemCapability.Web.Webview.Core 3043 3044**Error codes** 3045 3046For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3047 3048| ID| Error Message | 3049| -------- | ------------------------------------------------------------ | 3050| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3051| 17100004 | Function not enabled. | 3052 3053**Example** 3054 3055```ts 3056// xxx.ets 3057import { webview } from '@kit.ArkWeb'; 3058import { BusinessError } from '@kit.BasicServicesKit'; 3059 3060@Entry 3061@Component 3062struct WebComponent { 3063 controller: webview.WebviewController = new webview.WebviewController(); 3064 3065 build() { 3066 Column() { 3067 Button('zoomIn') 3068 .onClick(() => { 3069 try { 3070 this.controller.zoomIn(); 3071 } catch (error) { 3072 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3073 } 3074 }) 3075 Web({ src: 'www.example.com', controller: this.controller }) 3076 } 3077 } 3078} 3079``` 3080 3081### zoomOut 3082 3083zoomOut(): void 3084 3085Zooms out of this web page by 20%. 3086 3087**System capability**: SystemCapability.Web.Webview.Core 3088 3089**Error codes** 3090 3091For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3092 3093| ID| Error Message | 3094| -------- | ------------------------------------------------------------ | 3095| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3096| 17100004 | Function not enabled. | 3097 3098**Example** 3099 3100```ts 3101// xxx.ets 3102import { webview } from '@kit.ArkWeb'; 3103import { BusinessError } from '@kit.BasicServicesKit'; 3104 3105@Entry 3106@Component 3107struct WebComponent { 3108 controller: webview.WebviewController = new webview.WebviewController(); 3109 3110 build() { 3111 Column() { 3112 Button('zoomOut') 3113 .onClick(() => { 3114 try { 3115 this.controller.zoomOut(); 3116 } catch (error) { 3117 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3118 } 3119 }) 3120 Web({ src: 'www.example.com', controller: this.controller }) 3121 } 3122 } 3123} 3124``` 3125 3126### getHitTestValue<sup>(deprecated)</sup> 3127 3128getHitTestValue(): HitTestValue 3129 3130Obtains the element information of the area being clicked. 3131 3132> **NOTE** 3133> 3134> This API is supported since API version 11 and deprecated since API version 18. You are advised to use [getLastHitTest](#getlasthittest18) instead. 3135 3136**System capability**: SystemCapability.Web.Webview.Core 3137 3138**Return value** 3139 3140| Type | Description | 3141| ------------ | -------------------- | 3142| [HitTestValue](#hittestvalue) | Element information of the area being clicked.| 3143 3144**Error codes** 3145 3146For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3147 3148| ID| Error Message | 3149| -------- | ------------------------------------------------------------ | 3150| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3151 3152**Example** 3153 3154```ts 3155// xxx.ets 3156import { webview } from '@kit.ArkWeb'; 3157import { BusinessError } from '@kit.BasicServicesKit'; 3158 3159@Entry 3160@Component 3161struct WebComponent { 3162 controller: webview.WebviewController = new webview.WebviewController(); 3163 3164 build() { 3165 Column() { 3166 Button('getHitTestValue') 3167 .onClick(() => { 3168 try { 3169 let hitValue = this.controller.getHitTestValue(); 3170 console.log("hitType: " + hitValue.type); 3171 console.log("extra: " + hitValue.extra); 3172 } catch (error) { 3173 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3174 } 3175 }) 3176 Web({ src: 'www.example.com', controller: this.controller }) 3177 } 3178 } 3179} 3180``` 3181 3182### getWebId 3183 3184getWebId(): number 3185 3186Obtains the index value of this **Web** component, which can be used for **Web** component management. 3187 3188**System capability**: SystemCapability.Web.Webview.Core 3189 3190**Return value** 3191 3192| Type | Description | 3193| ------ | --------------------- | 3194| number | Index value of the current **Web** component.| 3195 3196**Error codes** 3197 3198For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3199 3200| ID| Error Message | 3201| -------- | ------------------------------------------------------------ | 3202| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3203 3204**Example** 3205 3206```ts 3207// xxx.ets 3208import { webview } from '@kit.ArkWeb'; 3209import { BusinessError } from '@kit.BasicServicesKit'; 3210 3211@Entry 3212@Component 3213struct WebComponent { 3214 controller: webview.WebviewController = new webview.WebviewController(); 3215 3216 build() { 3217 Column() { 3218 Button('getWebId') 3219 .onClick(() => { 3220 try { 3221 let id = this.controller.getWebId(); 3222 console.log("id: " + id); 3223 } catch (error) { 3224 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3225 } 3226 }) 3227 Web({ src: 'www.example.com', controller: this.controller }) 3228 } 3229 } 3230} 3231``` 3232 3233### getUserAgent 3234 3235getUserAgent(): string 3236 3237Obtains the default user agent of this web page. 3238 3239For details about the default **User-Agent**, see [Developing User-Agent](../../web/web-default-userAgent.md). 3240 3241**System capability**: SystemCapability.Web.Webview.Core 3242 3243**Return value** 3244 3245| Type | Description | 3246| ------ | -------------- | 3247| string | Default user agent.| 3248 3249**Error codes** 3250 3251For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3252 3253| ID| Error Message | 3254| -------- | ------------------------------------------------------------ | 3255| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3256 3257**Example** 3258 3259```ts 3260// xxx.ets 3261import { webview } from '@kit.ArkWeb'; 3262import { BusinessError } from '@kit.BasicServicesKit'; 3263 3264@Entry 3265@Component 3266struct WebComponent { 3267 controller: webview.WebviewController = new webview.WebviewController(); 3268 3269 build() { 3270 Column() { 3271 Button('getUserAgent') 3272 .onClick(() => { 3273 try { 3274 let userAgent = this.controller.getUserAgent(); 3275 console.log("userAgent: " + userAgent); 3276 } catch (error) { 3277 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3278 } 3279 }) 3280 Web({ src: 'www.example.com', controller: this.controller }) 3281 } 3282 } 3283} 3284``` 3285 3286You can define a custom user agent based on the default user agent. 3287```ts 3288// xxx.ets 3289import { webview } from '@kit.ArkWeb'; 3290import { BusinessError } from '@kit.BasicServicesKit'; 3291 3292@Entry 3293@Component 3294struct WebComponent { 3295 controller: webview.WebviewController = new webview.WebviewController(); 3296 @State ua: string = ""; 3297 3298 aboutToAppear(): void { 3299 webview.once('webInited', () => { 3300 try { 3301 // Define a custom user agent on the application side. 3302 this.ua = this.controller.getUserAgent() + 'xxx'; 3303 this.controller.setCustomUserAgent(this.ua); 3304 } catch (error) { 3305 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3306 } 3307 }) 3308 } 3309 3310 build() { 3311 Column() { 3312 Web({ src: 'www.example.com', controller: this.controller }) 3313 } 3314 } 3315} 3316``` 3317 3318### getTitle 3319 3320getTitle(): string 3321 3322Obtains the title of the current web page. 3323 3324**System capability**: SystemCapability.Web.Webview.Core 3325 3326**Return value** 3327 3328| Type | Description | 3329| ------ | -------------------- | 3330| string | Title of the current web page.| 3331 3332**Error codes** 3333 3334For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3335 3336| ID| Error Message | 3337| -------- | ------------------------------------------------------------ | 3338| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3339 3340**Example** 3341 3342```ts 3343// xxx.ets 3344import { webview } from '@kit.ArkWeb'; 3345import { BusinessError } from '@kit.BasicServicesKit'; 3346 3347@Entry 3348@Component 3349struct WebComponent { 3350 controller: webview.WebviewController = new webview.WebviewController(); 3351 3352 build() { 3353 Column() { 3354 Button('getTitle') 3355 .onClick(() => { 3356 try { 3357 let title = this.controller.getTitle(); 3358 console.log("title: " + title); 3359 } catch (error) { 3360 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3361 } 3362 }) 3363 Web({ src: 'www.example.com', controller: this.controller }) 3364 } 3365 } 3366} 3367``` 3368 3369### getPageHeight 3370 3371getPageHeight(): number 3372 3373Obtains the height of this web page. 3374 3375**System capability**: SystemCapability.Web.Webview.Core 3376 3377**Return value** 3378 3379| Type | Description | 3380| ------ | -------------------- | 3381| number | Height of the current web page. Unit: vp| 3382 3383**Error codes** 3384 3385For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3386 3387| ID| Error Message | 3388| -------- | ------------------------------------------------------------ | 3389| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3390 3391**Example** 3392 3393```ts 3394// xxx.ets 3395import { webview } from '@kit.ArkWeb'; 3396import { BusinessError } from '@kit.BasicServicesKit'; 3397 3398@Entry 3399@Component 3400struct WebComponent { 3401 controller: webview.WebviewController = new webview.WebviewController(); 3402 3403 build() { 3404 Column() { 3405 Button('getPageHeight') 3406 .onClick(() => { 3407 try { 3408 let pageHeight = this.controller.getPageHeight(); 3409 console.log("pageHeight : " + pageHeight); 3410 } catch (error) { 3411 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3412 } 3413 }) 3414 Web({ src: 'www.example.com', controller: this.controller }) 3415 } 3416 } 3417} 3418``` 3419 3420### storeWebArchive 3421 3422storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback\<string>): void 3423 3424Stores this web page. This API uses an asynchronous callback to return the result. 3425 3426**System capability**: SystemCapability.Web.Webview.Core 3427 3428**Parameters** 3429 3430| Name | Type | Mandatory| Description | 3431| -------- | --------------------- | ---- | ------------------------------------------------------------ | 3432| baseName | string | Yes | Save path of the web page. The value cannot be null. | 3433| 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.| 3434| callback | AsyncCallback\<string> | Yes | Callback used to return the save path if the operation is successful and null otherwise. | 3435 3436**Error codes** 3437 3438For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3439 3440| ID| Error Message | 3441| -------- | ------------------------------------------------------------ | 3442| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3443| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3444| 17100003 | Invalid resource path or file type. | 3445 3446**Example** 3447 3448```ts 3449// xxx.ets 3450import { webview } from '@kit.ArkWeb'; 3451import { BusinessError } from '@kit.BasicServicesKit'; 3452 3453@Entry 3454@Component 3455struct WebComponent { 3456 controller: webview.WebviewController = new webview.WebviewController(); 3457 3458 build() { 3459 Column() { 3460 Button('storeWebArchive') 3461 .onClick(() => { 3462 try { 3463 this.controller.storeWebArchive("/data/storage/el2/base/", true, (error, filename) => { 3464 if (error) { 3465 console.error(`save web archive error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3466 return; 3467 } 3468 if (filename != null) { 3469 console.info(`save web archive success: ${filename}`); 3470 } 3471 }); 3472 } catch (error) { 3473 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3474 } 3475 }) 3476 Web({ src: 'www.example.com', controller: this.controller }) 3477 } 3478 } 3479} 3480``` 3481 3482### storeWebArchive 3483 3484storeWebArchive(baseName: string, autoName: boolean): Promise\<string> 3485 3486Stores this web page. This API uses a promise to return the result. 3487 3488**System capability**: SystemCapability.Web.Webview.Core 3489 3490**Parameters** 3491 3492| Name | Type| Mandatory| Description | 3493| -------- | -------- | ---- | ------------------------------------------------------------ | 3494| baseName | string | Yes | Save path of the web page. The value cannot be null. | 3495| 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.| 3496 3497**Return value** 3498 3499| Type | Description | 3500| --------------- | ----------------------------------------------------- | 3501| Promise\<string> | Promise used to return the save path if the operation is successful and null otherwise.| 3502 3503**Error codes** 3504 3505For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3506 3507| ID| Error Message | 3508| -------- | ------------------------------------------------------------ | 3509| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3510| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3511| 17100003 | Invalid resource path or file type. | 3512 3513**Example** 3514 3515```ts 3516// xxx.ets 3517import { webview } from '@kit.ArkWeb'; 3518import { BusinessError } from '@kit.BasicServicesKit'; 3519 3520@Entry 3521@Component 3522struct WebComponent { 3523 controller: webview.WebviewController = new webview.WebviewController(); 3524 3525 build() { 3526 Column() { 3527 Button('storeWebArchive') 3528 .onClick(() => { 3529 try { 3530 this.controller.storeWebArchive("/data/storage/el2/base/", true) 3531 .then(filename => { 3532 if (filename != null) { 3533 console.info(`save web archive success: ${filename}`) 3534 } 3535 }) 3536 .catch((error: BusinessError) => { 3537 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 3538 }) 3539 } catch (error) { 3540 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3541 } 3542 }) 3543 Web({ src: 'www.example.com', controller: this.controller }) 3544 } 3545 } 3546} 3547``` 3548 3549### getUrl 3550 3551getUrl(): string 3552 3553Obtains the URL of this page. 3554 3555**System capability**: SystemCapability.Web.Webview.Core 3556 3557**Return value** 3558 3559| Type | Description | 3560| ------ | ------------------- | 3561| string | URL of the current page.| 3562 3563**Error codes** 3564 3565For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3566 3567| ID| Error Message | 3568| -------- | ------------------------------------------------------------ | 3569| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3570 3571**Example** 3572 3573```ts 3574// xxx.ets 3575import { webview } from '@kit.ArkWeb'; 3576import { BusinessError } from '@kit.BasicServicesKit'; 3577 3578@Entry 3579@Component 3580struct WebComponent { 3581 controller: webview.WebviewController = new webview.WebviewController(); 3582 3583 build() { 3584 Column() { 3585 Button('getUrl') 3586 .onClick(() => { 3587 try { 3588 let url = this.controller.getUrl(); 3589 console.log("url: " + url); 3590 } catch (error) { 3591 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3592 } 3593 }) 3594 Web({ src: 'www.example.com', controller: this.controller }) 3595 } 3596 } 3597} 3598``` 3599 3600### stop 3601 3602stop(): void 3603 3604Stops page loading. 3605 3606**System capability**: SystemCapability.Web.Webview.Core 3607 3608**Error codes** 3609 3610For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3611 3612| ID| Error Message | 3613| -------- | ------------------------------------------------------------ | 3614| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3615 3616**Example** 3617 3618```ts 3619// xxx.ets 3620import { webview } from '@kit.ArkWeb'; 3621import { BusinessError } from '@kit.BasicServicesKit'; 3622 3623@Entry 3624@Component 3625struct WebComponent { 3626 controller: webview.WebviewController = new webview.WebviewController(); 3627 3628 build() { 3629 Column() { 3630 Button('stop') 3631 .onClick(() => { 3632 try { 3633 this.controller.stop(); 3634 } catch (error) { 3635 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3636 } 3637 }); 3638 Web({ src: 'www.example.com', controller: this.controller }) 3639 } 3640 } 3641} 3642``` 3643 3644### backOrForward 3645 3646backOrForward(step: number): void 3647 3648Performs 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. 3649 3650Because the previously loaded web pages are used for the operation, no page reloading is involved. 3651 3652**System capability**: SystemCapability.Web.Webview.Core 3653 3654**Parameters** 3655 3656| Name| Type| Mandatory| Description | 3657| ------ | -------- | ---- | ---------------------- | 3658| step | number | Yes | Number of the steps to take.| 3659 3660**Error codes** 3661 3662For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3663 3664| ID| Error Message | 3665| -------- | ------------------------------------------------------------ | 3666| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3667| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3668 3669**Example** 3670 3671```ts 3672// xxx.ets 3673import { webview } from '@kit.ArkWeb'; 3674import { BusinessError } from '@kit.BasicServicesKit'; 3675 3676@Entry 3677@Component 3678struct WebComponent { 3679 controller: webview.WebviewController = new webview.WebviewController(); 3680 @State step: number = -2; 3681 3682 build() { 3683 Column() { 3684 Button('backOrForward') 3685 .onClick(() => { 3686 try { 3687 this.controller.backOrForward(this.step); 3688 } catch (error) { 3689 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3690 } 3691 }) 3692 Web({ src: 'www.example.com', controller: this.controller }) 3693 } 3694 } 3695} 3696``` 3697 3698### scrollTo 3699 3700scrollTo(x:number, y:number, duration?:number): void 3701 3702Scrolls the page to the specified absolute position within a specified period. 3703 3704**System capability**: SystemCapability.Web.Webview.Core 3705 3706**Parameters** 3707 3708| Name| Type| Mandatory| Description | 3709| ------ | -------- | ---- | ---------------------- | 3710| x | number | Yes | X coordinate of the absolute position. If the value is a negative number, the value 0 is used. Unit: vp| 3711| y | number | Yes | Y coordinate of the absolute position. If the value is a negative number, the value 0 is used. Unit: vp| 3712| duration<sup>14+</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.| 3713 3714**Error codes** 3715 3716For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3717 3718| ID| Error Message | 3719| -------- | ------------------------------------------------------------ | 3720| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3721| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3722 3723**Example** 3724 3725```ts 3726// xxx.ets 3727import { webview } from '@kit.ArkWeb'; 3728import { BusinessError } from '@kit.BasicServicesKit'; 3729 3730@Entry 3731@Component 3732struct WebComponent { 3733 controller: webview.WebviewController = new webview.WebviewController(); 3734 3735 build() { 3736 Column() { 3737 Button('scrollTo') 3738 .onClick(() => { 3739 try { 3740 this.controller.scrollTo(50, 50, 500); 3741 } catch (error) { 3742 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3743 } 3744 }) 3745 Button('stopScroll') 3746 .onClick(() => { 3747 try { 3748 this.controller.scrollBy(0, 0, 1); // If you want to stop the animation generated by the current scroll, you can generate another 1 ms animation to interrupt the animation. 3749 } catch (error) { 3750 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3751 } 3752 }) 3753 Web({ src: $rawfile('index.html'), controller: this.controller }) 3754 } 3755 } 3756} 3757``` 3758 3759HTML file to be loaded: 3760```html 3761<!--index.html--> 3762<!DOCTYPE html> 3763<html> 3764<head> 3765 <title>Demo</title> 3766 <style> 3767 body { 3768 width:2000px; 3769 height:2000px; 3770 padding-right:170px; 3771 padding-left:170px; 3772 border:5px solid blueviolet 3773 } 3774 </style> 3775</head> 3776<body> 3777Scroll Test 3778</body> 3779</html> 3780``` 3781 3782### scrollBy 3783 3784scrollBy(deltaX:number, deltaY:number,duration?:number): void 3785 3786Scrolls the page by the specified amount within a specified period. 3787 3788**System capability**: SystemCapability.Web.Webview.Core 3789 3790**Parameters** 3791 3792| Name| Type| Mandatory| Description | 3793| ------ | -------- | ---- | ---------------------- | 3794| deltaX | number | Yes | Amount to scroll by along the x-axis. The positive direction is rightward. Unit: vp| 3795| deltaY | number | Yes | Amount to scroll by along the y-axis. The positive direction is downward. Unit: vp| 3796| duration<sup>14+</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.| 3797 3798**Error codes** 3799 3800For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3801 3802| ID| Error Message | 3803| -------- | ------------------------------------------------------------ | 3804| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3805| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3806 3807> **NOTE** 3808> 3809> Calling **scrollBy** does not trigger the nested scrolling of the parent component. 3810 3811**Example** 3812 3813```ts 3814// xxx.ets 3815import { webview } from '@kit.ArkWeb'; 3816import { BusinessError } from '@kit.BasicServicesKit'; 3817 3818@Entry 3819@Component 3820struct WebComponent { 3821 controller: webview.WebviewController = new webview.WebviewController(); 3822 3823 build() { 3824 Column() { 3825 Button('scrollBy') 3826 .onClick(() => { 3827 try { 3828 this.controller.scrollBy(50, 50, 500); 3829 } catch (error) { 3830 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3831 } 3832 }) 3833 Button('stopScroll') 3834 .onClick(() => { 3835 try { 3836 this.controller.scrollBy(0, 0, 1); // If you want to stop the animation generated by the current scroll, you can generate another 1 ms animation to interrupt the animation. 3837 } catch (error) { 3838 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3839 } 3840 }) 3841 Web({ src: $rawfile('index.html'), controller: this.controller }) 3842 } 3843 } 3844} 3845``` 3846 3847HTML file to be loaded: 3848```html 3849<!--index.html--> 3850<!DOCTYPE html> 3851<html> 3852<head> 3853 <title>Demo</title> 3854 <style> 3855 body { 3856 width:2000px; 3857 height:2000px; 3858 padding-right:170px; 3859 padding-left:170px; 3860 border:5px solid blueviolet 3861 } 3862 </style> 3863</head> 3864<body> 3865Scroll Test 3866</body> 3867</html> 3868``` 3869### scrollByWithResult<sup>12+</sup> 3870 3871scrollByWithResult(deltaX: number, deltaY: number): boolean 3872 3873Scrolls the page by the specified amount and returns value to indicate whether the scrolling is successful. 3874 3875**System capability**: SystemCapability.Web.Webview.Core 3876 3877**Parameters** 3878 3879| Name| Type| Mandatory| Description | 3880| ------ | -------- | ---- | ---------------------- | 3881| deltaX | number | Yes | Amount to scroll by along the x-axis. The positive direction is rightward.| 3882| deltaY | number | Yes | Amount to scroll by along the y-axis. The positive direction is downward.| 3883 3884**Return value** 3885 3886| Type | Description | 3887| ------- | --------------------------------------- | 3888| boolean | Whether the current web page can be scrolled. The default value is **false**.| 3889 3890**Error codes** 3891 3892For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3893 3894| ID| Error Message | 3895| -------- | ------------------------------------------------------------ | 3896| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3897| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3898 3899> **NOTE** 3900> 3901> - If the web page is being touched, **false** is returned. Otherwise, **true** is returned. 3902> - If the rendering area at the same layer of the web page is being touched, **true** is returned. 3903> - Calling **scrollByWithResult** does not trigger the nested scrolling of the parent component. 3904> - This API does not support the high frame rate of scrolling performance. 3905 3906**Example** 3907 3908```ts 3909// xxx.ets 3910import { webview } from '@kit.ArkWeb'; 3911import { BusinessError } from '@kit.BasicServicesKit'; 3912 3913@Entry 3914@Component 3915struct WebComponent { 3916 controller: webview.WebviewController = new webview.WebviewController(); 3917 3918 build() { 3919 Column() { 3920 Button('scrollByWithResult') 3921 .onClick(() => { 3922 try { 3923 let result = this.controller.scrollByWithResult(50, 50); 3924 console.log("original result: " + result); 3925 } catch (error) { 3926 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3927 } 3928 }) 3929 Web({ src: $rawfile('index.html'), controller: this.controller }) 3930 } 3931 } 3932} 3933``` 3934 3935HTML file to be loaded: 3936```html 3937<!--index.html--> 3938<!DOCTYPE html> 3939<html> 3940<head> 3941 <title>Demo</title> 3942 <style> 3943 body { 3944 width:2000px; 3945 height:2000px; 3946 padding-right:170px; 3947 padding-left:170px; 3948 border:5px solid blueviolet 3949 } 3950 </style> 3951</head> 3952<body> 3953Scroll Test 3954</body> 3955</html> 3956``` 3957### slideScroll 3958 3959slideScroll(vx:number, vy:number): void 3960 3961Simulates a slide-to-scroll action on the page at the specified velocity. 3962 3963**System capability**: SystemCapability.Web.Webview.Core 3964 3965**Parameters** 3966 3967| Name| Type| Mandatory| Description | 3968| ------ | -------- | ---- | ---------------------- | 3969| vx | number | Yes | Horizontal velocity component of the slide-to-scroll action, where the positive direction is rightward. Unit: vp/ms.| 3970| vy | number | Yes | Vertical velocity component of the slide-to-scroll action, where the positive direction is downward. Unit: vp/ms.| 3971 3972**Error codes** 3973 3974For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3975 3976| ID| Error Message | 3977| -------- | ------------------------------------------------------------ | 3978| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3979| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3980 3981**Example** 3982 3983```ts 3984// xxx.ets 3985import { webview } from '@kit.ArkWeb'; 3986import { BusinessError } from '@kit.BasicServicesKit'; 3987 3988@Entry 3989@Component 3990struct WebComponent { 3991 controller: webview.WebviewController = new webview.WebviewController(); 3992 3993 build() { 3994 Column() { 3995 Button('slideScroll') 3996 .onClick(() => { 3997 try { 3998 this.controller.slideScroll(500, 500); 3999 } catch (error) { 4000 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4001 } 4002 }) 4003 Web({ src: $rawfile('index.html'), controller: this.controller }) 4004 } 4005 } 4006} 4007``` 4008 4009HTML file to be loaded: 4010```html 4011<!--index.html--> 4012<!DOCTYPE html> 4013<html> 4014<head> 4015 <title>Demo</title> 4016 <style> 4017 body { 4018 width:3000px; 4019 height:3000px; 4020 padding-right:170px; 4021 padding-left:170px; 4022 border:5px solid blueviolet 4023 } 4024 </style> 4025</head> 4026<body> 4027Scroll Test 4028</body> 4029</html> 4030``` 4031 4032### getOriginalUrl 4033 4034getOriginalUrl(): string 4035 4036Obtains the original URL of this page. 4037Risk warning: If you want to obtain the URL for JavaScriptProxy communication API authentication, use [getLastJavascriptProxyCallingFrameUrl<sup>12+</sup>](#getlastjavascriptproxycallingframeurl12). 4038 4039**System capability**: SystemCapability.Web.Webview.Core 4040 4041**Return value** 4042 4043| Type | Description | 4044| ------ | ----------------------- | 4045| string | Original URL of the current page.| 4046 4047**Error codes** 4048 4049For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4050 4051| ID| Error Message | 4052| -------- | ------------------------------------------------------------ | 4053| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4054 4055**Example** 4056 4057```ts 4058// xxx.ets 4059import { webview } from '@kit.ArkWeb'; 4060import { BusinessError } from '@kit.BasicServicesKit'; 4061 4062@Entry 4063@Component 4064struct WebComponent { 4065 controller: webview.WebviewController = new webview.WebviewController(); 4066 4067 build() { 4068 Column() { 4069 Button('getOrgUrl') 4070 .onClick(() => { 4071 try { 4072 let url = this.controller.getOriginalUrl(); 4073 console.log("original url: " + url); 4074 } catch (error) { 4075 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4076 } 4077 }) 4078 Web({ src: 'www.example.com', controller: this.controller }) 4079 } 4080 } 4081} 4082``` 4083 4084### getFavicon 4085 4086getFavicon(): image.PixelMap 4087 4088Obtains the favicon of this page. 4089 4090**System capability**: SystemCapability.Web.Webview.Core 4091 4092**Return value** 4093 4094| Type | Description | 4095| -------------------------------------- | ------------------------------- | 4096| [PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | **PixelMap** object of the favicon of the page.| 4097 4098**Error codes** 4099 4100For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4101 4102| ID| Error Message | 4103| -------- | ------------------------------------------------------------ | 4104| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4105 4106**Example** 4107 4108```ts 4109// xxx.ets 4110import { webview } from '@kit.ArkWeb'; 4111import { BusinessError } from '@kit.BasicServicesKit'; 4112import { image } from '@kit.ImageKit'; 4113 4114@Entry 4115@Component 4116struct WebComponent { 4117 controller: webview.WebviewController = new webview.WebviewController(); 4118 @State pixelmap: image.PixelMap | undefined = undefined; 4119 4120 build() { 4121 Column() { 4122 Button('getFavicon') 4123 .onClick(() => { 4124 try { 4125 this.pixelmap = this.controller.getFavicon(); 4126 } catch (error) { 4127 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4128 } 4129 }) 4130 Web({ src: 'www.example.com', controller: this.controller }) 4131 } 4132 } 4133} 4134``` 4135 4136### setNetworkAvailable 4137 4138setNetworkAvailable(enable: boolean): void 4139 4140Sets the **window.navigator.onLine** attribute in JavaScript. 4141 4142**System capability**: SystemCapability.Web.Webview.Core 4143 4144**Parameters** 4145 4146| Name| Type | Mandatory| Description | 4147| ------ | ------- | ---- | --------------------------------- | 4148| enable | boolean | Yes | Whether to enable **window.navigator.onLine**.| 4149 4150**Error codes** 4151 4152For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4153 4154| ID| Error Message | 4155| -------- | ------------------------------------------------------------ | 4156| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4157| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4158 4159**Example** 4160 4161```ts 4162// xxx.ets 4163import { webview } from '@kit.ArkWeb'; 4164import { BusinessError } from '@kit.BasicServicesKit'; 4165 4166@Entry 4167@Component 4168struct WebComponent { 4169 controller: webview.WebviewController = new webview.WebviewController(); 4170 4171 build() { 4172 Column() { 4173 Button('setNetworkAvailable') 4174 .onClick(() => { 4175 try { 4176 this.controller.setNetworkAvailable(true); 4177 } catch (error) { 4178 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4179 } 4180 }) 4181 Web({ src: $rawfile('index.html'), controller: this.controller }) 4182 } 4183 } 4184} 4185``` 4186 4187HTML file to be loaded: 4188```html 4189<!-- index.html --> 4190<!DOCTYPE html> 4191<html> 4192<body> 4193<h1>online attribute </h1> 4194<p id="demo"></p> 4195<button onclick="func()">click</button> 4196<script> 4197 let online = navigator.onLine; 4198 document.getElementById ("demo").innerHTML = "Browser online:" + online; 4199 4200 function func(){ 4201 var online = navigator.onLine; 4202 document.getElementById ("demo").innerHTML = "Browser online:" + online; 4203 } 4204</script> 4205</body> 4206</html> 4207``` 4208 4209### hasImage 4210 4211hasImage(callback: AsyncCallback\<boolean>): void 4212 4213Checks whether this page contains images. This API uses an asynchronous callback to return the result. 4214 4215**System capability**: SystemCapability.Web.Webview.Core 4216 4217**Parameters** 4218 4219| Name | Type | Mandatory| Description | 4220| -------- | ----------------------- | ---- | -------------------------- | 4221| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result.| 4222 4223**Error codes** 4224 4225For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4226 4227| ID| Error Message | 4228| -------- | ------------------------------------------------------------ | 4229| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4230| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4231 4232**Example** 4233 4234```ts 4235// xxx.ets 4236import { webview } from '@kit.ArkWeb'; 4237import { BusinessError } from '@kit.BasicServicesKit'; 4238 4239@Entry 4240@Component 4241struct WebComponent { 4242 controller: webview.WebviewController = new webview.WebviewController(); 4243 4244 build() { 4245 Column() { 4246 Button('hasImageCb') 4247 .onClick(() => { 4248 try { 4249 this.controller.hasImage((error, data) => { 4250 if (error) { 4251 console.error(`hasImage error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4252 return; 4253 } 4254 console.info("hasImage: " + data); 4255 }); 4256 } catch (error) { 4257 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4258 } 4259 }) 4260 Web({ src: 'www.example.com', controller: this.controller }) 4261 } 4262 } 4263} 4264``` 4265 4266### hasImage 4267 4268hasImage(): Promise\<boolean> 4269 4270Checks whether this page contains images. This API uses a promise to return the result. 4271 4272**System capability**: SystemCapability.Web.Webview.Core 4273 4274**Return value** 4275 4276| Type | Description | 4277| ----------------- | --------------------------------------- | 4278| Promise\<boolean> | Promise used to return the result.| 4279 4280**Error codes** 4281 4282For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4283 4284| ID| Error Message | 4285| -------- | ------------------------------------------------------------ | 4286| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4287| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 4288 4289**Example** 4290 4291```ts 4292// xxx.ets 4293import { webview } from '@kit.ArkWeb'; 4294import { BusinessError } from '@kit.BasicServicesKit'; 4295 4296@Entry 4297@Component 4298struct WebComponent { 4299 controller: webview.WebviewController = new webview.WebviewController(); 4300 4301 build() { 4302 Column() { 4303 Button('hasImagePm') 4304 .onClick(() => { 4305 try { 4306 this.controller.hasImage().then((data) => { 4307 console.info('hasImage: ' + data); 4308 }).catch((error: BusinessError) => { 4309 console.error("error: " + error); 4310 }) 4311 } catch (error) { 4312 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4313 } 4314 }) 4315 Web({ src: 'www.example.com', controller: this.controller }) 4316 } 4317 } 4318} 4319``` 4320 4321### removeCache 4322 4323removeCache(clearRom: boolean): void 4324 4325Clears the cache in the application. This API will clear the cache for all webviews in the same application. 4326 4327> **NOTE** 4328> 4329> You can view the Webview cache in the **data/storage/el2/base/cache/web/Cache** directory. 4330 4331**System capability**: SystemCapability.Web.Webview.Core 4332 4333**Parameters** 4334 4335| Name | Type | Mandatory| Description | 4336| -------- | ------- | ---- | -------------------------------------------------------- | 4337| 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.| 4338 4339**Error codes** 4340 4341For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4342 4343| ID| Error Message | 4344| -------- | ------------------------------------------------------------ | 4345| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4346| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4347 4348**Example** 4349 4350```ts 4351// xxx.ets 4352import { webview } from '@kit.ArkWeb'; 4353import { BusinessError } from '@kit.BasicServicesKit'; 4354 4355@Entry 4356@Component 4357struct WebComponent { 4358 controller: webview.WebviewController = new webview.WebviewController(); 4359 4360 build() { 4361 Column() { 4362 Button('removeCache') 4363 .onClick(() => { 4364 try { 4365 this.controller.removeCache(false); 4366 } catch (error) { 4367 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4368 } 4369 }) 4370 Web({ src: 'www.example.com', controller: this.controller }) 4371 } 4372 } 4373} 4374``` 4375 4376### removeAllCache<sup>18+</sup> 4377 4378static removeAllCache(clearRom: boolean): void 4379 4380Clears the cache in the application. This API will clear the cache for all webviews in the same application. 4381 4382> **NOTE** 4383> 4384> You can view the WebView cache files in the **data/app/el2/100/base/\<applicationPackageName\>/cache/web/** directory. 4385 4386**System capability**: SystemCapability.Web.Webview.Core 4387 4388**Parameters** 4389 4390| Name | Type | Mandatory| Description | 4391| -------- | ------- | ---- | -------------------------------------------------------- | 4392| clearRom | boolean | Yes | Whether to clear the cache files in both ROM and RAM. If this parameter is set to **true**, the cache files in both ROM and RAM are cleared. If this parameter is set to **false**, only the cache files in RAM are cleared.| 4393 4394**Error codes** 4395 4396For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4397 4398| ID| Error Message | 4399| -------- | ------------------------------------------------------------ | 4400| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4401 4402**Example** 4403 4404```ts 4405// xxx.ets 4406import { webview } from '@kit.ArkWeb'; 4407import { BusinessError } from '@kit.BasicServicesKit'; 4408 4409@Entry 4410@Component 4411struct WebComponent { 4412 controller: webview.WebviewController = new webview.WebviewController(); 4413 4414 build() { 4415 Column() { 4416 Button('removeAllCache') 4417 .onClick(() => { 4418 try { 4419 webview.WebviewController.removeAllCache(false); 4420 } catch (error) { 4421 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4422 } 4423 }) 4424 Web({ src: 'www.example.com', controller: this.controller }) 4425 } 4426 } 4427} 4428``` 4429 4430### pageUp 4431 4432pageUp(top: boolean): void 4433 4434Scrolls the page up by half the viewport or jumps to the top of the page. 4435 4436**System capability**: SystemCapability.Web.Webview.Core 4437 4438**Parameters** 4439 4440| Name| Type | Mandatory| Description | 4441| ------ | ------- | ---- | ------------------------------------------------------------ | 4442| 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.| 4443 4444**Error codes** 4445 4446For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4447 4448| ID| Error Message | 4449| -------- | ------------------------------------------------------------ | 4450| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4451| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4452 4453**Example** 4454 4455```ts 4456// xxx.ets 4457import { webview } from '@kit.ArkWeb'; 4458import { BusinessError } from '@kit.BasicServicesKit'; 4459 4460@Entry 4461@Component 4462struct WebComponent { 4463 controller: webview.WebviewController = new webview.WebviewController(); 4464 4465 build() { 4466 Column() { 4467 Button('pageUp') 4468 .onClick(() => { 4469 try { 4470 this.controller.pageUp(false); 4471 } catch (error) { 4472 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4473 } 4474 }) 4475 Web({ src: 'www.example.com', controller: this.controller }) 4476 } 4477 } 4478} 4479``` 4480 4481### pageDown 4482 4483pageDown(bottom: boolean): void 4484 4485Scrolls the page down by half the viewport or jumps to the bottom of the page. 4486 4487**System capability**: SystemCapability.Web.Webview.Core 4488 4489**Parameters** 4490 4491| Name| Type | Mandatory| Description | 4492| ------ | ------- | ---- | ------------------------------------------------------------ | 4493| 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.| 4494 4495**Error codes** 4496 4497For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4498 4499| ID| Error Message | 4500| -------- | ------------------------------------------------------------ | 4501| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4502| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4503 4504**Example** 4505 4506```ts 4507// xxx.ets 4508import { webview } from '@kit.ArkWeb'; 4509import { BusinessError } from '@kit.BasicServicesKit'; 4510 4511@Entry 4512@Component 4513struct WebComponent { 4514 controller: webview.WebviewController = new webview.WebviewController(); 4515 4516 build() { 4517 Column() { 4518 Button('pageDown') 4519 .onClick(() => { 4520 try { 4521 this.controller.pageDown(false); 4522 } catch (error) { 4523 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4524 } 4525 }) 4526 Web({ src: 'www.example.com', controller: this.controller }) 4527 } 4528 } 4529} 4530``` 4531 4532### getBackForwardEntries 4533 4534getBackForwardEntries(): BackForwardList 4535 4536Obtains the historical information list of the current webview. 4537 4538**System capability**: SystemCapability.Web.Webview.Core 4539 4540**Return value** 4541 4542| Type | Description | 4543| ----------------------------------- | --------------------------- | 4544| [BackForwardList](#backforwardlist) | The historical information list of the current webview.| 4545 4546**Error codes** 4547 4548For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4549 4550| ID| Error Message | 4551| -------- | ------------------------------------------------------------ | 4552| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4553 4554**Example** 4555 4556```ts 4557// xxx.ets 4558import { webview } from '@kit.ArkWeb'; 4559import { BusinessError } from '@kit.BasicServicesKit'; 4560 4561@Entry 4562@Component 4563struct WebComponent { 4564 controller: webview.WebviewController = new webview.WebviewController(); 4565 4566 build() { 4567 Column() { 4568 Button('getBackForwardEntries') 4569 .onClick(() => { 4570 try { 4571 let list = this.controller.getBackForwardEntries() 4572 } catch (error) { 4573 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4574 } 4575 }) 4576 Web({ src: 'www.example.com', controller: this.controller }) 4577 } 4578 } 4579} 4580``` 4581 4582### serializeWebState 4583 4584serializeWebState(): Uint8Array 4585 4586Serializes the page status history of the current Webview. 4587 4588**System capability**: SystemCapability.Web.Webview.Core 4589 4590**Return value** 4591 4592| Type | Description | 4593| ---------- | --------------------------------------------- | 4594| Uint8Array | Serialized data of the page status history of the current WebView.| 4595 4596**Error codes** 4597 4598For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4599 4600| ID| Error Message | 4601| -------- | ------------------------------------------------------------ | 4602| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4603 4604**Example** 4605 46061. 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). 4607```ts 4608// xxx.ets 4609import { webview } from '@kit.ArkWeb'; 4610import { BusinessError } from '@kit.BasicServicesKit'; 4611import { fileIo } from '@kit.CoreFileKit'; 4612 4613@Entry 4614@Component 4615struct WebComponent { 4616 controller: webview.WebviewController = new webview.WebviewController(); 4617 4618 build() { 4619 Column() { 4620 Button('serializeWebState') 4621 .onClick(() => { 4622 try { 4623 let state = this.controller.serializeWebState(); 4624 let path:string | undefined = AppStorage.get("cacheDir"); 4625 if (path) { 4626 path += '/WebState'; 4627 // Synchronously open a file. 4628 let file = fileIo.openSync(path, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); 4629 fileIo.writeSync(file.fd, state.buffer); 4630 fileIo.closeSync(file.fd); 4631 } 4632 } catch (error) { 4633 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4634 } 4635 }) 4636 Web({ src: 'www.example.com', controller: this.controller }) 4637 } 4638 } 4639} 4640``` 4641 46422. Modify the **EntryAbility.ets** file. 4643Obtain the path of the application cache file. 4644```ts 4645// xxx.ets 4646import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 4647 4648export default class EntryAbility extends UIAbility { 4649 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 4650 // Data synchronization between the UIAbility component and the page can be implemented by binding cacheDir to the AppStorage object. 4651 AppStorage.setOrCreate("cacheDir", this.context.cacheDir); 4652 } 4653} 4654``` 4655 4656### restoreWebState 4657 4658restoreWebState(state: Uint8Array): void 4659 4660Restores the page status history from the serialized data of the current WebView. 4661 4662If the value of **state** is too large, exceptions may occur. It is recommended that the page status history be not restored when the **state** value is greater than 512 KB. 4663 4664**System capability**: SystemCapability.Web.Webview.Core 4665 4666**Parameters** 4667 4668| Name| Type | Mandatory| Description | 4669| ------ | ---------- | ---- | ---------------------------- | 4670| state | Uint8Array | Yes | Serialized data of the page status history.| 4671 4672**Error codes** 4673 4674For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4675 4676| ID| Error Message | 4677| -------- | ------------------------------------------------------------ | 4678| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4679| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 4680 4681**Example** 4682 46831. 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). 4684```ts 4685// xxx.ets 4686import { webview } from '@kit.ArkWeb'; 4687import { BusinessError } from '@kit.BasicServicesKit'; 4688import { fileIo } from '@kit.CoreFileKit'; 4689 4690@Entry 4691@Component 4692struct WebComponent { 4693 controller: webview.WebviewController = new webview.WebviewController(); 4694 4695 build() { 4696 Column() { 4697 Button('RestoreWebState') 4698 .onClick(() => { 4699 try { 4700 let path: string | undefined = AppStorage.get("cacheDir"); 4701 if (path) { 4702 path += '/WebState'; 4703 // Synchronously open a file. 4704 let file = fileIo.openSync(path, fileIo.OpenMode.READ_WRITE); 4705 let stat = fileIo.statSync(path); 4706 let size = stat.size; 4707 let buf = new ArrayBuffer(size); 4708 fileIo.read(file.fd, buf, (err, readLen) => { 4709 if (err) { 4710 console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); 4711 } else { 4712 console.info("read file data succeed"); 4713 this.controller.restoreWebState(new Uint8Array(buf.slice(0, readLen))); 4714 fileIo.closeSync(file); 4715 } 4716 }); 4717 } 4718 } catch (error) { 4719 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4720 } 4721 }) 4722 Web({ src: 'www.example.com', controller: this.controller }) 4723 } 4724 } 4725} 4726``` 4727 47282. Modify the **EntryAbility.ets** file. 4729Obtain the path of the application cache file. 4730```ts 4731// xxx.ets 4732import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 4733 4734export default class EntryAbility extends UIAbility { 4735 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 4736 // Data synchronization between the UIAbility component and the page can be implemented by binding cacheDir to the AppStorage object. 4737 AppStorage.setOrCreate("cacheDir", this.context.cacheDir); 4738 } 4739} 4740``` 4741 4742### customizeSchemes 4743 4744static customizeSchemes(schemes: Array\<WebCustomScheme\>): void 4745 4746Grants 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. 4747 4748**System capability**: SystemCapability.Web.Webview.Core 4749 4750**Parameters** 4751 4752| Name | Type | Mandatory| Description | 4753| -------- | ------- | ---- | -------------------------------------- | 4754| schemes | Array\<[WebCustomScheme](#webcustomscheme)\> | Yes | Array of up to 10 custom schemes.| 4755 4756**Error codes** 4757 4758For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4759 4760| ID| Error Message | 4761| -------- | ------------------------------------------------------------ | 4762| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4763| 17100020 | Failed to register custom schemes. | 4764 4765**Example** 4766 4767```ts 4768// xxx.ets 4769import { webview } from '@kit.ArkWeb'; 4770import { BusinessError } from '@kit.BasicServicesKit'; 4771 4772@Entry 4773@Component 4774struct WebComponent { 4775 controller: webview.WebviewController = new webview.WebviewController(); 4776 responseWeb: WebResourceResponse = new WebResourceResponse(); 4777 scheme1: webview.WebCustomScheme = { schemeName: "name1", isSupportCORS: true, isSupportFetch: true }; 4778 scheme2: webview.WebCustomScheme = { schemeName: "name2", isSupportCORS: true, isSupportFetch: true }; 4779 scheme3: webview.WebCustomScheme = { schemeName: "name3", isSupportCORS: true, isSupportFetch: true }; 4780 4781 aboutToAppear(): void { 4782 try { 4783 webview.WebviewController.customizeSchemes([this.scheme1, this.scheme2, this.scheme3]); 4784 } catch (error) { 4785 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4786 } 4787 } 4788 4789 build() { 4790 Column() { 4791 Web({ src: 'www.example.com', controller: this.controller }) 4792 .onInterceptRequest((event) => { 4793 if (event) { 4794 console.log('url:' + event.request.getRequestUrl()); 4795 } 4796 return this.responseWeb; 4797 }) 4798 } 4799 } 4800} 4801``` 4802 4803### getCertificate<sup>10+</sup> 4804 4805getCertificate(): Promise<Array<cert.X509Cert>> 4806 4807Obtains 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. 4808 4809**System capability**: SystemCapability.Web.Webview.Core 4810 4811**Return value** 4812 4813| Type | Description | 4814| ---------- | --------------------------------------------- | 4815| Promise<Array<cert.X509Cert>> | Promise used to obtain the X.509 certificate array of the current HTTPS website.| 4816 4817**Error codes** 4818 4819For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4820 4821| ID| Error Message | 4822| -------- | ------------------------------------------------------------ | 4823| 17100001 | Init error. The WebviewController must be associated with a web component. | 4824 4825**Example** 4826 4827```ts 4828// xxx.ets 4829import { webview } from '@kit.ArkWeb'; 4830import { BusinessError } from '@kit.BasicServicesKit'; 4831import { cert } from '@kit.DeviceCertificateKit'; 4832 4833function Uint8ArrayToString(dataArray: Uint8Array) { 4834 let dataString = ''; 4835 for (let i = 0; i < dataArray.length; i++) { 4836 dataString += String.fromCharCode(dataArray[i]); 4837 } 4838 return dataString; 4839} 4840 4841function ParseX509CertInfo(x509CertArray: Array<cert.X509Cert>) { 4842 let res: string = 'getCertificate success: len = ' + x509CertArray.length; 4843 for (let i = 0; i < x509CertArray.length; i++) { 4844 res += ', index = ' + i + ', issuer name = ' 4845 + Uint8ArrayToString(x509CertArray[i].getIssuerName().data) + ', subject name = ' 4846 + Uint8ArrayToString(x509CertArray[i].getSubjectName().data) + ', valid start = ' 4847 + x509CertArray[i].getNotBeforeTime() 4848 + ', valid end = ' + x509CertArray[i].getNotAfterTime(); 4849 } 4850 return res; 4851} 4852 4853@Entry 4854@Component 4855struct Index { 4856 // outputStr displays debug information on the UI. 4857 @State outputStr: string = ''; 4858 webviewCtl: webview.WebviewController = new webview.WebviewController(); 4859 4860 build() { 4861 Row() { 4862 Column() { 4863 List({ space: 20, initialIndex: 0 }) { 4864 ListItem() { 4865 Button() { 4866 Text('load bad ssl') 4867 .fontSize(10) 4868 .fontWeight(FontWeight.Bold) 4869 } 4870 .type(ButtonType.Capsule) 4871 .onClick(() => { 4872 // Load an expired certificate website and view the obtained certificate information. 4873 this.webviewCtl.loadUrl('https://expired.badssl.com'); 4874 }) 4875 .height(50) 4876 } 4877 4878 ListItem() { 4879 Button() { 4880 Text('load example') 4881 .fontSize(10) 4882 .fontWeight(FontWeight.Bold) 4883 } 4884 .type(ButtonType.Capsule) 4885 .onClick(() => { 4886 // Load an HTTPS website and view the certificate information of the website. 4887 this.webviewCtl.loadUrl('https://www.example.com'); 4888 }) 4889 .height(50) 4890 } 4891 4892 ListItem() { 4893 Button() { 4894 Text('getCertificate Promise') 4895 .fontSize(10) 4896 .fontWeight(FontWeight.Bold) 4897 } 4898 .type(ButtonType.Capsule) 4899 .onClick(() => { 4900 try { 4901 this.webviewCtl.getCertificate().then((x509CertArray: Array<cert.X509Cert>) => { 4902 this.outputStr = ParseX509CertInfo(x509CertArray); 4903 }) 4904 } catch (error) { 4905 this.outputStr = 'getCertificate failed: ' + (error as BusinessError).code + ", errMsg: " + (error as BusinessError).message; 4906 } 4907 }) 4908 .height(50) 4909 } 4910 4911 ListItem() { 4912 Button() { 4913 Text('getCertificate AsyncCallback') 4914 .fontSize(10) 4915 .fontWeight(FontWeight.Bold) 4916 } 4917 .type(ButtonType.Capsule) 4918 .onClick(() => { 4919 try { 4920 this.webviewCtl.getCertificate((error: BusinessError, x509CertArray: Array<cert.X509Cert>) => { 4921 if (error) { 4922 this.outputStr = 'getCertificate failed: ' + error.code + ", errMsg: " + error.message; 4923 } else { 4924 this.outputStr = ParseX509CertInfo(x509CertArray); 4925 } 4926 }) 4927 } catch (error) { 4928 this.outputStr = 'getCertificate failed: ' + (error as BusinessError).code + ", errMsg: " + (error as BusinessError).message; 4929 } 4930 }) 4931 .height(50) 4932 } 4933 } 4934 .listDirection(Axis.Horizontal) 4935 .height('10%') 4936 4937 Text(this.outputStr) 4938 .width('100%') 4939 .fontSize(10) 4940 4941 Web({ src: 'https://www.example.com', controller: this.webviewCtl }) 4942 .fileAccess(true) 4943 .javaScriptAccess(true) 4944 .domStorageAccess(true) 4945 .onlineImageAccess(true) 4946 .onPageEnd((e) => { 4947 if (e) { 4948 this.outputStr = 'onPageEnd : url = ' + e.url; 4949 } 4950 }) 4951 .onSslErrorEventReceive((e) => { 4952 // Ignore SSL certificate errors to test websites whose certificates have expired, for example, https://expired.badssl.com. 4953 e.handler.handleConfirm(); 4954 }) 4955 .width('100%') 4956 .height('70%') 4957 } 4958 .height('100%') 4959 } 4960 } 4961} 4962``` 4963 4964### getCertificate<sup>10+</sup> 4965 4966getCertificate(callback: AsyncCallback<Array<cert.X509Cert>>): void 4967 4968Obtains 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. 4969 4970**System capability**: SystemCapability.Web.Webview.Core 4971 4972**Parameters** 4973 4974| Name | Type | Mandatory| Description | 4975| -------- | ---------------------------- | ---- | ---------------------------------------- | 4976| callback | AsyncCallback<Array<cert.X509Cert>> | Yes | Callback used to obtain the X.509 certificate array of the current website.| 4977 4978**Error codes** 4979 4980For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4981 4982| ID| Error Message | 4983| -------- | ------------------------------------------------------------ | 4984| 17100001 | Init error. The WebviewController must be associated with a web component. | 4985| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 4986 4987**Example** 4988 4989```ts 4990// xxx.ets 4991import { webview } from '@kit.ArkWeb'; 4992import { BusinessError } from '@kit.BasicServicesKit'; 4993import { cert } from '@kit.DeviceCertificateKit'; 4994 4995function Uint8ArrayToString(dataArray: Uint8Array) { 4996 let dataString = ''; 4997 for (let i = 0; i < dataArray.length; i++) { 4998 dataString += String.fromCharCode(dataArray[i]); 4999 } 5000 return dataString; 5001} 5002 5003function ParseX509CertInfo(x509CertArray: Array<cert.X509Cert>) { 5004 let res: string = 'getCertificate success: len = ' + x509CertArray.length; 5005 for (let i = 0; i < x509CertArray.length; i++) { 5006 res += ', index = ' + i + ', issuer name = ' 5007 + Uint8ArrayToString(x509CertArray[i].getIssuerName().data) + ', subject name = ' 5008 + Uint8ArrayToString(x509CertArray[i].getSubjectName().data) + ', valid start = ' 5009 + x509CertArray[i].getNotBeforeTime() 5010 + ', valid end = ' + x509CertArray[i].getNotAfterTime(); 5011 } 5012 return res; 5013} 5014 5015@Entry 5016@Component 5017struct Index { 5018 // outputStr displays debug information on the UI. 5019 @State outputStr: string = ''; 5020 webviewCtl: webview.WebviewController = new webview.WebviewController(); 5021 5022 build() { 5023 Row() { 5024 Column() { 5025 List({ space: 20, initialIndex: 0 }) { 5026 ListItem() { 5027 Button() { 5028 Text('load bad ssl') 5029 .fontSize(10) 5030 .fontWeight(FontWeight.Bold) 5031 } 5032 .type(ButtonType.Capsule) 5033 .onClick(() => { 5034 // Load an expired certificate website and view the obtained certificate information. 5035 this.webviewCtl.loadUrl('https://expired.badssl.com'); 5036 }) 5037 .height(50) 5038 } 5039 5040 ListItem() { 5041 Button() { 5042 Text('load example') 5043 .fontSize(10) 5044 .fontWeight(FontWeight.Bold) 5045 } 5046 .type(ButtonType.Capsule) 5047 .onClick(() => { 5048 // Load an HTTPS website and view the certificate information of the website. 5049 this.webviewCtl.loadUrl('https://www.example.com'); 5050 }) 5051 .height(50) 5052 } 5053 5054 ListItem() { 5055 Button() { 5056 Text('getCertificate Promise') 5057 .fontSize(10) 5058 .fontWeight(FontWeight.Bold) 5059 } 5060 .type(ButtonType.Capsule) 5061 .onClick(() => { 5062 try { 5063 this.webviewCtl.getCertificate().then((x509CertArray: Array<cert.X509Cert>) => { 5064 this.outputStr = ParseX509CertInfo(x509CertArray); 5065 }) 5066 } catch (error) { 5067 this.outputStr = 'getCertificate failed: ' + (error as BusinessError).code + ", errMsg: " + (error as BusinessError).message; 5068 } 5069 }) 5070 .height(50) 5071 } 5072 5073 ListItem() { 5074 Button() { 5075 Text('getCertificate AsyncCallback') 5076 .fontSize(10) 5077 .fontWeight(FontWeight.Bold) 5078 } 5079 .type(ButtonType.Capsule) 5080 .onClick(() => { 5081 try { 5082 this.webviewCtl.getCertificate((error: BusinessError, x509CertArray: Array<cert.X509Cert>) => { 5083 if (error) { 5084 this.outputStr = 'getCertificate failed: ' + error.code + ", errMsg: " + error.message; 5085 } else { 5086 this.outputStr = ParseX509CertInfo(x509CertArray); 5087 } 5088 }) 5089 } catch (error) { 5090 this.outputStr = 'getCertificate failed: ' + (error as BusinessError).code + ", errMsg: " + (error as BusinessError).message; 5091 } 5092 }) 5093 .height(50) 5094 } 5095 } 5096 .listDirection(Axis.Horizontal) 5097 .height('10%') 5098 5099 Text(this.outputStr) 5100 .width('100%') 5101 .fontSize(10) 5102 5103 Web({ src: 'https://www.example.com', controller: this.webviewCtl }) 5104 .fileAccess(true) 5105 .javaScriptAccess(true) 5106 .domStorageAccess(true) 5107 .onlineImageAccess(true) 5108 .onPageEnd((e) => { 5109 if (e) { 5110 this.outputStr = 'onPageEnd : url = ' + e.url; 5111 } 5112 }) 5113 .onSslErrorEventReceive((e) => { 5114 // Ignore SSL certificate errors to test websites whose certificates have expired, for example, https://expired.badssl.com. 5115 e.handler.handleConfirm(); 5116 }) 5117 .width('100%') 5118 .height('70%') 5119 } 5120 .height('100%') 5121 } 5122 } 5123} 5124``` 5125 5126### setAudioMuted<sup>10+</sup> 5127 5128setAudioMuted(mute: boolean): void 5129 5130Mutes this web page. 5131 5132**System capability**: SystemCapability.Web.Webview.Core 5133 5134**Parameters** 5135 5136| Name | Type | Mandatory| Description | 5137| -------- | ------- | ---- | -------------------------------------- | 5138| mute | boolean | Yes | Whether to mute the web page. The value **true** means to mute the web page, and **false** means the opposite.| 5139 5140**Error codes** 5141 5142For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5143 5144| ID| Error Message | 5145| -------- | ------------------------------------------------------------ | 5146| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5147| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5148 5149**Example** 5150 5151```ts 5152// xxx.ets 5153import { webview } from '@kit.ArkWeb'; 5154 5155@Entry 5156@Component 5157struct WebComponent { 5158 controller: webview.WebviewController = new webview.WebviewController(); 5159 @State muted: boolean = false; 5160 5161 build() { 5162 Column() { 5163 Button("Toggle Mute") 5164 .onClick(event => { 5165 if (event) { 5166 this.muted = !this.muted; 5167 this.controller.setAudioMuted(this.muted); 5168 } 5169 }) 5170 Web({ src: 'www.example.com', controller: this.controller }) 5171 } 5172 } 5173} 5174``` 5175 5176### prefetchPage<sup>10+</sup> 5177 5178prefetchPage(url: string, additionalHeaders?: Array\<WebHeader>): void 5179 5180Prefetches 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. 5181 5182> **NOTE** 5183> 5184> The downloaded page resources are cached for about 5 minutes. After this period, the **Web** component automatically releases the resources. 5185 5186**System capability**: SystemCapability.Web.Webview.Core 5187 5188**Parameters** 5189 5190| Name | Type | Mandatory | Description | 5191| ------------------| --------------------------------| ---- | ------------- | 5192| url | string | Yes | URL to be preloaded.| 5193| additionalHeaders | Array\<[WebHeader](#webheader)> | No | Additional HTTP headers of the URL.| 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| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5202| 17100002 | Invalid url. | 5203 5204**Example** 5205 5206```ts 5207// xxx.ets 5208import { webview } from '@kit.ArkWeb'; 5209import { BusinessError } from '@kit.BasicServicesKit'; 5210 5211@Entry 5212@Component 5213struct WebComponent { 5214 controller: webview.WebviewController = new webview.WebviewController(); 5215 5216 build() { 5217 Column() { 5218 Button('prefetchPopularPage') 5219 .onClick(() => { 5220 try { 5221 // Replace 'https://www.example.com' with a real URL for the API to work. 5222 this.controller.prefetchPage('https://www.example.com'); 5223 } catch (error) { 5224 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5225 } 5226 }) 5227 // Replace ''www.example1.com' with a real URL for the API to work. 5228 Web({ src: 'www.example1.com', controller: this.controller }) 5229 } 5230 } 5231} 5232``` 5233 5234### prefetchResource<sup>12+</sup> 5235 5236static prefetchResource(request: RequestInfo, additionalHeaders?: Array\<WebHeader>, cacheKey?: string, cacheValidTime?: number): void 5237 5238Prefetches 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. 5239 5240**System capability**: SystemCapability.Web.Webview.Core 5241 5242**Parameters** 5243 5244| Name | Type | Mandatory | Description | 5245| ------------------| ------------------------------- | ---- | ------------------------------------------------------------------ | 5246| request | [RequestInfo](#requestinfo12) | Yes | Information about the prefetched request. | 5247| additionalHeaders | Array\<[WebHeader](#webheader)> | No | Additional HTTP request header of the prefetched request. | 5248| 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.| 5249| cacheValidTime | number | No | Validity period for caching prefetched resources. Value range: (0, 2147483647] Unit: second. Default value: **300s** | 5250 5251**Error codes** 5252 5253For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5254 5255| ID | Error Message | 5256| -------- | ------------------------------------------------------------ | 5257| 401 | Invalid input parameter.Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | 5258| 17100002 | Invalid url. | 5259 5260**Example** 5261 5262```ts 5263// xxx.ets 5264import { webview } from '@kit.ArkWeb'; 5265import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 5266 5267export default class EntryAbility extends UIAbility { 5268 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 5269 console.log("EntryAbility onCreate"); 5270 webview.WebviewController.initializeWebEngine(); 5271 // Replace "https://www.example1.com/post?e=f&g=h" with the actual website address to visit. 5272 webview.WebviewController.prefetchResource( 5273 { 5274 url: "https://www.example1.com/post?e=f&g=h", 5275 method: "POST", 5276 formData: "a=x&b=y", 5277 }, 5278 [{ 5279 headerKey: "c", 5280 headerValue: "z", 5281 },], 5282 "KeyX", 500); 5283 AppStorage.setOrCreate("abilityWant", want); 5284 console.log("EntryAbility onCreate done"); 5285 } 5286} 5287``` 5288 5289### clearPrefetchedResource<sup>12+</sup> 5290 5291static clearPrefetchedResource(cacheKeyList: Array\<string>): void 5292 5293Clears 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). 5294 5295**System capability**: SystemCapability.Web.Webview.Core 5296 5297**Parameters** 5298 5299| Name | Type | Mandatory | Description | 5300| ------------------| ----------- | ---- | ------------------------------------------------------------------------- | 5301| 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.| 5302 5303**Example** 5304 5305```ts 5306// xxx.ets 5307import { webview } from '@kit.ArkWeb'; 5308 5309@Entry 5310@Component 5311struct WebComponent { 5312 controller: webview.WebviewController = new webview.WebviewController(); 5313 5314 build() { 5315 Column() { 5316 Web({ src: "https://www.example.com/", controller: this.controller }) 5317 .onAppear(() => { 5318 // Replace "https://www.example1.com/post?e=f&g=h" with the actual website address to visit. 5319 webview.WebviewController.prefetchResource( 5320 { 5321 url: "https://www.example1.com/post?e=f&g=h", 5322 method: "POST", 5323 formData: "a=x&b=y", 5324 }, 5325 [{ 5326 headerKey: "c", 5327 headerValue: "z", 5328 },], 5329 "KeyX", 500); 5330 }) 5331 .onPageEnd(() => { 5332 // Clear the prefetch cache that is no longer used. 5333 webview.WebviewController.clearPrefetchedResource(["KeyX",]); 5334 }) 5335 } 5336 } 5337} 5338``` 5339 5340### prepareForPageLoad<sup>10+</sup> 5341 5342static prepareForPageLoad(url: string, preconnectable: boolean, numSockets: number): void 5343 5344Preconnects 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. 5345 5346**System capability**: SystemCapability.Web.Webview.Core 5347 5348**Parameters** 5349 5350| Name | Type | Mandatory | Description | 5351| ---------------| ------- | ---- | ------------- | 5352| url | string | Yes | URL to be preconnected.| 5353| 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.| 5354| numSockets | number | Yes | Number of sockets to be preconnected. The value must be greater than 0. A maximum of six socket connections are allowed.| 5355 5356**Error codes** 5357 5358For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5359 5360| ID | Error Message | 5361| -------- | ------------------------------------------------------------ | 5362| 17100002 | Invalid url. | 5363| 171000013| The number of preconnect sockets is invalid. | 5364 5365**Example** 5366 5367```ts 5368// xxx.ets 5369import { webview } from '@kit.ArkWeb'; 5370import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 5371 5372export default class EntryAbility extends UIAbility { 5373 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 5374 console.log("EntryAbility onCreate"); 5375 webview.WebviewController.initializeWebEngine(); 5376 // Replace 'https://www.example.com' with a real URL for the API to work. 5377 webview.WebviewController.prepareForPageLoad("https://www.example.com", true, 2); 5378 AppStorage.setOrCreate("abilityWant", want); 5379 console.log("EntryAbility onCreate done"); 5380 } 5381} 5382``` 5383 5384### setCustomUserAgent<sup>10+</sup> 5385 5386setCustomUserAgent(userAgent: string): void 5387 5388Sets a custom user agent, which will overwrite the default user agent. 5389 5390When **src** of the **Web** component is set to a URL, set **User-Agent** in **onControllerAttached**. For details, see the following example. Avoid setting the user agent in **onLoadIntercept**. Otherwise, the setting may fail occasionally. 5391 5392When **src** of the **Web** component is set to an empty string, call **setCustomUserAgent** to set **User-Agent** and then use **loadUrl** to load a specific page. 5393 5394For details about the default **User-Agent**, see [Developing User-Agent](../../web/web-default-userAgent.md). 5395 5396> **NOTE** 5397> 5398>If a URL is set for the **Web** component **src** and **User-Agent** is not set in the **onControllerAttached** callback, calling **setCustomUserAgent** may cause mismatches between the loaded page and the intended user agent. 5399 5400**System capability**: SystemCapability.Web.Webview.Core 5401 5402**Parameters** 5403 5404| Name | Type | Mandatory | Description | 5405| ---------------| ------- | ---- | ------------- | 5406| 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.| 5407 5408**Error codes** 5409 5410For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5411 5412| ID | Error Message | 5413| -------- | ------------------------------------------------------------ | 5414| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5415| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5416 5417**Example** 5418 5419```ts 5420// xxx.ets 5421import { webview } from '@kit.ArkWeb'; 5422import { BusinessError } from '@kit.BasicServicesKit'; 5423 5424@Entry 5425@Component 5426struct WebComponent { 5427 controller: webview.WebviewController = new webview.WebviewController(); 5428 @State customUserAgent: string = ' DemoApp'; 5429 5430 build() { 5431 Column() { 5432 Web({ src: 'www.example.com', controller: this.controller }) 5433 .onControllerAttached(() => { 5434 console.log("onControllerAttached"); 5435 try { 5436 let userAgent = this.controller.getUserAgent() + this.customUserAgent; 5437 this.controller.setCustomUserAgent(userAgent); 5438 } catch (error) { 5439 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5440 } 5441 }) 5442 } 5443 } 5444} 5445``` 5446 5447### setDownloadDelegate<sup>11+</sup> 5448 5449setDownloadDelegate(delegate: WebDownloadDelegate): void 5450 5451Sets a **WebDownloadDelegate** object to receive downloads and download progress triggered from a page. 5452 5453**System capability**: SystemCapability.Web.Webview.Core 5454 5455**Parameters** 5456 5457| Name | Type | Mandatory | Description | 5458| ---------------| ------- | ---- | ------------- | 5459| delegate | [WebDownloadDelegate](#webdownloaddelegate11) | Yes | Delegate used to receive the download progress.| 5460 5461**Error codes** 5462 5463For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5464 5465| ID | Error Message | 5466| -------- | ------------------------------------------------------------ | 5467| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5468 5469**Example** 5470 5471```ts 5472// xxx.ets 5473import { webview } from '@kit.ArkWeb'; 5474import { BusinessError } from '@kit.BasicServicesKit'; 5475 5476@Entry 5477@Component 5478struct WebComponent { 5479 controller: webview.WebviewController = new webview.WebviewController(); 5480 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 5481 5482 build() { 5483 Column() { 5484 Button('setDownloadDelegate') 5485 .onClick(() => { 5486 try { 5487 this.controller.setDownloadDelegate(this.delegate); 5488 } catch (error) { 5489 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5490 } 5491 }) 5492 Web({ src: 'www.example.com', controller: this.controller }) 5493 } 5494 } 5495} 5496``` 5497 5498### startDownload<sup>11+</sup> 5499 5500startDownload(url: string): void 5501 5502Downloads a file, such as an image, from the specified URL. 5503 5504**System capability**: SystemCapability.Web.Webview.Core 5505 5506**Parameters** 5507 5508| Name | Type | Mandatory | Description | 5509| ---------------| ------- | ---- | ------------- | 5510| url | string | Yes | Download URL.| 5511 5512**Error codes** 5513 5514For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5515 5516| ID | Error Message | 5517| -------- | ------------------------------------------------------------ | 5518| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5519| 17100002 | Invalid url. | 5520 5521**Example** 5522 5523```ts 5524// xxx.ets 5525import { webview } from '@kit.ArkWeb'; 5526import { BusinessError } from '@kit.BasicServicesKit'; 5527 5528@Entry 5529@Component 5530struct WebComponent { 5531 controller: webview.WebviewController = new webview.WebviewController(); 5532 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 5533 5534 build() { 5535 Column() { 5536 Button('setDownloadDelegate') 5537 .onClick(() => { 5538 try { 5539 this.controller.setDownloadDelegate(this.delegate); 5540 } catch (error) { 5541 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5542 } 5543 }) 5544 Button('startDownload') 5545 .onClick(() => { 5546 try { 5547 this.controller.startDownload('https://www.example.com'); 5548 } catch (error) { 5549 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5550 } 5551 }) 5552 Web({ src: 'www.example.com', controller: this.controller }) 5553 } 5554 } 5555} 5556``` 5557 5558### getCustomUserAgent<sup>10+</sup> 5559 5560getCustomUserAgent(): string 5561 5562Obtains a custom user agent. 5563 5564For details about the default **User-Agent**, see [Developing User-Agent](../../web/web-default-userAgent.md). 5565 5566**System capability**: SystemCapability.Web.Webview.Core 5567 5568**Return value** 5569 5570| Type | Description | 5571| ------ | ------------------------- | 5572| string | Information about the custom user agent.| 5573 5574**Error codes** 5575 5576For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5577 5578| ID | Error Message | 5579| -------- | ------------------------------------------------------------ | 5580| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5581 5582**Example** 5583 5584```ts 5585// xxx.ets 5586import { webview } from '@kit.ArkWeb'; 5587import { BusinessError } from '@kit.BasicServicesKit'; 5588 5589@Entry 5590@Component 5591struct WebComponent { 5592 controller: webview.WebviewController = new webview.WebviewController(); 5593 @State userAgent: string = ''; 5594 5595 build() { 5596 Column() { 5597 Button('getCustomUserAgent') 5598 .onClick(() => { 5599 try { 5600 this.userAgent = this.controller.getCustomUserAgent(); 5601 console.log("userAgent: " + this.userAgent); 5602 } catch (error) { 5603 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5604 } 5605 }) 5606 Web({ src: 'www.example.com', controller: this.controller }) 5607 } 5608 } 5609} 5610``` 5611 5612### setConnectionTimeout<sup>11+</sup> 5613 5614static setConnectionTimeout(timeout: number): void 5615 5616Sets the network connection timeout. You can use the **onErrorReceive** method in the **Web** component to obtain the timeout error code. 5617 5618**System capability**: SystemCapability.Web.Webview.Core 5619 5620**Parameters** 5621 5622| Name | Type | Mandatory | Description | 5623| ---------------| ------- | ---- | ------------- | 5624| timeout | number | Yes | Socket connection timeout interval, in seconds. The value of socket must be an integer greater than 0.| 5625 5626**Error codes** 5627 5628For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5629 5630| ID| Error Message | 5631| -------- | ------------------------------------------------------------ | 5632| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 5633 5634**Example** 5635 5636```ts 5637// xxx.ets 5638import { webview } from '@kit.ArkWeb'; 5639import { BusinessError } from '@kit.BasicServicesKit'; 5640 5641@Entry 5642@Component 5643struct WebComponent { 5644 controller: webview.WebviewController = new webview.WebviewController(); 5645 5646 build() { 5647 Column() { 5648 Button('setConnectionTimeout') 5649 .onClick(() => { 5650 try { 5651 webview.WebviewController.setConnectionTimeout(5); 5652 console.log("setConnectionTimeout: 5s"); 5653 } catch (error) { 5654 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5655 } 5656 }) 5657 Web({ src: 'www.example.com', controller: this.controller }) 5658 .onErrorReceive((event) => { 5659 if (event) { 5660 console.log('getErrorInfo:' + event.error.getErrorInfo()); 5661 console.log('getErrorCode:' + event.error.getErrorCode()); 5662 } 5663 }) 5664 } 5665 } 5666} 5667``` 5668 5669### warmupServiceWorker<sup>12+</sup> 5670 5671static warmupServiceWorker(url: string): void 5672 5673Warms 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. 5674 5675**System capability**: SystemCapability.Web.Webview.Core 5676 5677**Parameters** 5678 5679| Name | Type | Mandatory | Description | 5680| ---------------| ------- | ---- | ------------- | 5681| url | string | Yes | URL of the ServiceWorker to warm up.| 5682 5683**Error codes** 5684 5685For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5686 5687| ID | Error Message | 5688| -------- | ------------------------------------------------------------ | 5689| 17100002 | Invalid url. | 5690 5691**Example** 5692 5693```ts 5694// xxx.ts 5695import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 5696import { hilog } from '@kit.PerformanceAnalysisKit'; 5697import { window } from '@kit.ArkUI'; 5698import { webview } from '@kit.ArkWeb'; 5699 5700export default class EntryAbility extends UIAbility { 5701 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 5702 console.log("EntryAbility onCreate"); 5703 webview.WebviewController.initializeWebEngine(); 5704 webview.WebviewController.warmupServiceWorker("https://www.example.com"); 5705 AppStorage.setOrCreate("abilityWant", want); 5706 } 5707} 5708``` 5709 5710### enableSafeBrowsing<sup>11+</sup> 5711 5712enableSafeBrowsing(enable: boolean): void 5713 5714<!--RP1-->Enables the safe browsing feature. This feature is forcibly enabled and cannot be disabled for identified untrusted websites. 5715By default, this feature does not take effect. OpenHarmony provides only the malicious website blocking web UI. The website risk detection and web UI display features are implemented by the vendor. You are advised to listen for [DidStartNavigation](https://gitee.com/openharmony-tpc/chromium_src/blob/master/content/public/browser/web_contents_observer.h#:~:text=virtual%20void-,DidStartNavigation) and [DidRedirectNavigation](https://gitee.com/openharmony-tpc/chromium_src/blob/master/content/public/browser/web_contents_observer.h#:~:text=virtual%20void-,DidRedirectNavigation) in **WebContentsObserver** to detect risks. 5716<!--RP1End--> 5717 5718**System capability**: SystemCapability.Web.Webview.Core 5719 5720**Parameters** 5721 5722| Name | Type | Mandatory | Description | 5723| --------| ------- | ---- | ---------------------------| 5724| enable | boolean | Yes | Whether to enable the safe browsing feature.| 5725 5726**Error codes** 5727 5728For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5729 5730| ID| Error Message | 5731| -------- | ----------------------- | 5732| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5733 5734**Example** 5735 5736```ts 5737// xxx.ets 5738import { webview } from '@kit.ArkWeb'; 5739import { BusinessError } from '@kit.BasicServicesKit'; 5740 5741@Entry 5742@Component 5743struct WebComponent { 5744 controller: webview.WebviewController = new webview.WebviewController(); 5745 5746 build() { 5747 Column() { 5748 Button('enableSafeBrowsing') 5749 .onClick(() => { 5750 try { 5751 this.controller.enableSafeBrowsing(true); 5752 console.log("enableSafeBrowsing: true"); 5753 } catch (error) { 5754 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5755 } 5756 }) 5757 Web({ src: 'www.example.com', controller: this.controller }) 5758 } 5759 } 5760} 5761``` 5762 5763### isSafeBrowsingEnabled<sup>11+</sup> 5764 5765isSafeBrowsingEnabled(): boolean 5766 5767Checks whether the safe browsing feature is enabled for this web page. 5768 5769**System capability**: SystemCapability.Web.Webview.Core 5770 5771**Return value** 5772 5773| Type | Description | 5774| ------- | --------------------------------------- | 5775| boolean | Whether the safe browsing feature is enabled. The default value is **false**.| 5776 5777**Example** 5778 5779```ts 5780// xxx.ets 5781import { webview } from '@kit.ArkWeb'; 5782 5783@Entry 5784@Component 5785struct WebComponent { 5786 controller: webview.WebviewController = new webview.WebviewController(); 5787 5788 build() { 5789 Column() { 5790 Button('isSafeBrowsingEnabled') 5791 .onClick(() => { 5792 let result = this.controller.isSafeBrowsingEnabled(); 5793 console.log("result: " + result); 5794 }) 5795 Web({ src: 'www.example.com', controller: this.controller }) 5796 } 5797 } 5798} 5799``` 5800 5801### enableIntelligentTrackingPrevention<sup>12+</sup> 5802 5803enableIntelligentTrackingPrevention(enable: boolean): void 5804 5805Enables intelligent tracking prevention. By default, this feature is disabled. 5806 5807**System capability**: SystemCapability.Web.Webview.Core 5808 5809**Parameters** 5810 5811| Name | Type | Mandatory | Description | 5812| --------| ------- | ---- | ---------------------------| 5813| enable | boolean | Yes | Whether to enable intelligent tracking prevention.| 5814 5815**Error codes** 5816 5817For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5818 5819| ID| Error Message | 5820| -------- | ----------------------- | 5821| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5822| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5823 5824**Example** 5825 5826```ts 5827// xxx.ets 5828import { webview } from '@kit.ArkWeb'; 5829import { BusinessError } from '@kit.BasicServicesKit'; 5830 5831@Entry 5832@Component 5833struct WebComponent { 5834 controller: webview.WebviewController = new webview.WebviewController(); 5835 5836 build() { 5837 Column() { 5838 Button('enableIntelligentTrackingPrevention') 5839 .onClick(() => { 5840 try { 5841 this.controller.enableIntelligentTrackingPrevention(true); 5842 console.log("enableIntelligentTrackingPrevention: true"); 5843 } catch (error) { 5844 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5845 } 5846 }) 5847 Web({ src: 'www.example.com', controller: this.controller }) 5848 } 5849 } 5850} 5851``` 5852 5853### isIntelligentTrackingPreventionEnabled<sup>12+</sup> 5854 5855isIntelligentTrackingPreventionEnabled(): boolean 5856 5857Obtains whether intelligent tracking prevention is enabled on this web page. 5858 5859**System capability**: SystemCapability.Web.Webview.Core 5860 5861**Return value** 5862 5863| Type | Description | 5864| ------- | --------------------------------------- | 5865| boolean | Whether intelligent tracking prevention is enabled on the current web page. The default value is **false**.| 5866 5867**Error codes** 5868 5869For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5870 5871| ID| Error Message | 5872| -------- | ----------------------- | 5873| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5874 5875**Example** 5876 5877```ts 5878// xxx.ets 5879import { webview } from '@kit.ArkWeb'; 5880import { BusinessError } from '@kit.BasicServicesKit'; 5881 5882@Entry 5883@Component 5884struct WebComponent { 5885 controller: webview.WebviewController = new webview.WebviewController(); 5886 5887 build() { 5888 Column() { 5889 Button('isIntelligentTrackingPreventionEnabled') 5890 .onClick(() => { 5891 try { 5892 let result = this.controller.isIntelligentTrackingPreventionEnabled(); 5893 console.log("result: " + result); 5894 } catch (error) { 5895 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5896 } 5897 }) 5898 Web({ src: 'www.example.com', controller: this.controller }) 5899 } 5900 } 5901} 5902``` 5903 5904### addIntelligentTrackingPreventionBypassingList<sup>12+</sup> 5905 5906static addIntelligentTrackingPreventionBypassingList(hostList: Array\<string>): void 5907 5908Adds a list of domain names that bypass intelligent tracking prevention. 5909 5910**System capability**: SystemCapability.Web.Webview.Core 5911 5912**Parameters** 5913 5914| Name | Type | Mandatory | Description | 5915| ----------- | ------------- | ---- | ------------------------ | 5916| hostList | Array\<string> | Yes | List of domain names that bypass intelligent tracking prevention.| 5917 5918**Error codes** 5919 5920For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5921 5922| ID | Error Message | 5923| -------- | ------------------------ | 5924| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5925 5926**Example** 5927 5928```ts 5929// xxx.ets 5930import { webview } from '@kit.ArkWeb'; 5931import { BusinessError } from '@kit.BasicServicesKit'; 5932 5933@Entry 5934@Component 5935struct WebComponent { 5936 controller: webview.WebviewController = new webview.WebviewController(); 5937 5938 build() { 5939 Column() { 5940 Button('addIntelligentTrackingPreventionBypassingList') 5941 .onClick(() => { 5942 try { 5943 let hostList = ["www.test1.com", "www.test2.com", "www.test3.com"]; 5944 webview.WebviewController.addIntelligentTrackingPreventionBypassingList(hostList); 5945 } catch (error) { 5946 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5947 } 5948 }) 5949 Web({ src: 'www.example.com', controller: this.controller }) 5950 } 5951 } 5952} 5953``` 5954 5955### removeIntelligentTrackingPreventionBypassingList<sup>12+</sup> 5956 5957static removeIntelligentTrackingPreventionBypassingList(hostList: Array\<string>): void 5958 5959Deletes the domain names from the list of domain names added through the **addIntelligentTrackingPreventionBypassingList** API. 5960 5961**System capability**: SystemCapability.Web.Webview.Core 5962 5963**Parameters** 5964 5965| Name | Type | Mandatory | Description | 5966| ----------- | ------------- | ---- | ------------------------ | 5967| hostList | Array\<string> | Yes | List of domain names that bypass intelligent tracking prevention.| 5968 5969**Error codes** 5970 5971For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5972 5973| ID | Error Message | 5974| -------- | ------------------------ | 5975| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5976 5977**Example** 5978 5979```ts 5980// xxx.ets 5981import { webview } from '@kit.ArkWeb'; 5982import { BusinessError } from '@kit.BasicServicesKit'; 5983 5984@Entry 5985@Component 5986struct WebComponent { 5987 controller: webview.WebviewController = new webview.WebviewController(); 5988 5989 build() { 5990 Column() { 5991 Button('removeIntelligentTrackingPreventionBypassingList') 5992 .onClick(() => { 5993 try { 5994 let hostList = ["www.test1.com", "www.test2.com"]; 5995 webview.WebviewController.removeIntelligentTrackingPreventionBypassingList(hostList); 5996 } catch (error) { 5997 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5998 } 5999 }) 6000 Web({ src: 'www.example.com', controller: this.controller }) 6001 } 6002 } 6003} 6004``` 6005 6006### clearIntelligentTrackingPreventionBypassingList<sup>12+</sup> 6007 6008static clearIntelligentTrackingPreventionBypassingList(): void 6009 6010Deletes all domain names from the list of domain names added through the **addIntelligentTrackingPreventionBypassingList** API. 6011 6012**System capability**: SystemCapability.Web.Webview.Core 6013 6014**Example** 6015 6016```ts 6017// xxx.ets 6018import { webview } from '@kit.ArkWeb'; 6019 6020@Entry 6021@Component 6022struct WebComponent { 6023 controller: webview.WebviewController = new webview.WebviewController(); 6024 6025 build() { 6026 Column() { 6027 Button('clearIntelligentTrackingPreventionBypassingList') 6028 .onClick(() => { 6029 webview.WebviewController.clearIntelligentTrackingPreventionBypassingList(); 6030 }) 6031 Web({ src: 'www.example.com', controller: this.controller }) 6032 } 6033 } 6034} 6035``` 6036 6037### getDefaultUserAgent<sup>14+</sup> 6038 6039static getDefaultUserAgent(): string 6040 6041Obtains the default user agent. 6042 6043This API can be called only in the UI thread. 6044 6045For details about the default **User-Agent**, see [Developing User-Agent](../../web/web-default-userAgent.md). 6046 6047**System capability**: SystemCapability.Web.Webview.Core 6048 6049**Example** 6050 6051```ts 6052// xxx.ets 6053import { webview } from '@kit.ArkWeb'; 6054import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 6055 6056export default class EntryAbility extends UIAbility { 6057 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 6058 console.log("EntryAbility onCreate"); 6059 webview.WebviewController.initializeWebEngine(); 6060 let defaultUserAgent = webview.WebviewController.getDefaultUserAgent(); 6061 console.log("defaultUserAgent: " + defaultUserAgent); 6062 } 6063} 6064``` 6065 6066### enableAdsBlock<sup>12+</sup> 6067 6068enableAdsBlock(enable: boolean): void 6069 6070Enables ad blocking. By default, this feature is disabled. 6071 6072**System capability**: SystemCapability.Web.Webview.Core 6073 6074**Parameters** 6075 6076| Name | Type | Mandatory | Description | 6077| --------| ------- | ---- | ---------------------------| 6078| enable | boolean | Yes | Whether to enable ad blocking.| 6079 6080**Error codes** 6081 6082For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6083 6084| ID| Error Message | 6085| -------- | ----------------------- | 6086| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6087| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Parameter string is too long. 3.Parameter verification failed. | 6088 6089**Example** 6090 6091```ts 6092// xxx.ets 6093import { webview } from '@kit.ArkWeb'; 6094import { BusinessError } from '@kit.BasicServicesKit'; 6095 6096@Entry 6097@Component 6098struct WebComponent { 6099 controller: webview.WebviewController = new webview.WebviewController(); 6100 6101 build() { 6102 Column() { 6103 Button('enableAdsBlock') 6104 .onClick(() => { 6105 try { 6106 this.controller.enableAdsBlock(true); 6107 console.log("enableAdsBlock: true") 6108 } catch (error) { 6109 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6110 } 6111 }) 6112 Web({ src: 'www.example.com', controller: this.controller }) 6113 } 6114 } 6115} 6116``` 6117 6118### isAdsBlockEnabled<sup>12+</sup> 6119 6120isAdsBlockEnabled() : boolean 6121 6122Checks whether ad blocking is enabled. By default, this feature is disabled. 6123 6124**System capability**: SystemCapability.Web.Webview.Core 6125 6126**Return value** 6127 6128| Type | Description | 6129| ------------------------------------------------------------ | ---------------------- | 6130| boolean | Returns **true** if ad blocking is enabled; returns **false** otherwise.| 6131 6132**Example** 6133 6134```ts 6135// xxx.ets 6136import { webview } from '@kit.ArkWeb'; 6137import { BusinessError } from '@kit.BasicServicesKit'; 6138 6139@Entry 6140@Component 6141struct WebComponent { 6142 controller: webview.WebviewController = new webview.WebviewController(); 6143 6144 build() { 6145 Column() { 6146 Button('isAdsBlockEnabled') 6147 .onClick(() => { 6148 try { 6149 let isAdsBlockEnabled: boolean = this.controller.isAdsBlockEnabled(); 6150 console.log("isAdsBlockEnabled:", isAdsBlockEnabled); 6151 } catch (error) { 6152 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6153 } 6154 }) 6155 Web({ src: 'www.example.com', controller: this.controller }) 6156 } 6157 } 6158} 6159``` 6160 6161### isAdsBlockEnabledForCurPage<sup>12+</sup> 6162 6163isAdsBlockEnabledForCurPage() : boolean 6164 6165Checks whether ad blocking is enabled on this web page. 6166After 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. 6167 6168**System capability**: SystemCapability.Web.Webview.Core 6169 6170**Return value** 6171 6172| Type | Description | 6173| ------------------------------------------------------------ | ---------------------- | 6174| boolean | Returns **true** if ad blocking is enabled; returns **false** otherwise.| 6175 6176**Example** 6177 6178```ts 6179// xxx.ets 6180import { webview } from '@kit.ArkWeb'; 6181import { BusinessError } from '@kit.BasicServicesKit'; 6182 6183@Entry 6184@Component 6185struct WebComponent { 6186 controller: webview.WebviewController = new webview.WebviewController(); 6187 6188 build() { 6189 Column() { 6190 Button('isAdsBlockEnabledForCurPage') 6191 .onClick(() => { 6192 try { 6193 let isAdsBlockEnabledForCurPage: boolean = this.controller.isAdsBlockEnabledForCurPage(); 6194 console.log("isAdsBlockEnabledForCurPage:", isAdsBlockEnabledForCurPage); 6195 } catch (error) { 6196 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6197 } 6198 }) 6199 Web({ src: 'www.example.com', controller: this.controller }) 6200 } 6201 } 6202} 6203``` 6204 6205### setRenderProcessMode<sup>12+</sup> 6206 6207static setRenderProcessMode(mode: RenderProcessMode): void 6208 6209Sets the ArkWeb render subprocess mode. 6210 6211**System capability**: SystemCapability.Web.Webview.Core 6212 6213**Parameters** 6214 6215| Name | Type | Mandatory | Description | 6216| ----------- | ------------- | ---- | ------------------------ | 6217| mode | [RenderProcessMode](#renderprocessmode12)| Yes | Render subprocess mode. You can call [getRenderProcessMode()](#getrenderprocessmode12) to view the ArkWeb rendering subprocess mode of the current device. The enumerated value **0** indicates the single render subprocess mode, and **1** indicates the multi-render subprocess mode. If an invalid number other than the enumerated value of **RenderProcessMode** is passed, the multi-render subprocess mode is used by default.| 6218 6219**Error codes** 6220 6221For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6222 6223| ID | Error Message | 6224| -------- | ------------------------ | 6225| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 6226 6227**Example** 6228 6229```ts 6230// xxx.ets 6231import { webview } from '@kit.ArkWeb'; 6232import { BusinessError } from '@kit.BasicServicesKit'; 6233 6234@Entry 6235@Component 6236struct WebComponent { 6237 controller: webview.WebviewController = new webview.WebviewController(); 6238 6239 build() { 6240 Column() { 6241 Button('setRenderProcessMode') 6242 .onClick(() => { 6243 try { 6244 webview.WebviewController.setRenderProcessMode(webview.RenderProcessMode.MULTIPLE); 6245 } catch (error) { 6246 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6247 } 6248 }) 6249 Web({ src: 'www.example.com', controller: this.controller }) 6250 } 6251 } 6252} 6253``` 6254### getRenderProcessMode<sup>12+</sup> 6255 6256static getRenderProcessMode(): RenderProcessMode 6257 6258Obtains the ArkWeb render subprocess mode. 6259 6260**System capability**: SystemCapability.Web.Webview.Core 6261 6262**Return value** 6263 6264| Type | Description | 6265| ----------------------------------------- | ------------------------------------------------------------ | 6266| [RenderProcessMode](#renderprocessmode12) | Render subprocess mode. You can call [getRenderProcessMode()](#getrenderprocessmode12) to obtain the ArkWeb render subprocess mode of the current device. The enumerated value **0** indicates the single render subprocess mode, and **1** indicates the multi-render subprocess mode. If the obtained value is not an enumerated value of **RenderProcessMode**, the multi-render subprocess mode is used by default.| 6267 6268 6269**Example** 6270 6271```ts 6272// xxx.ets 6273import { webview } from '@kit.ArkWeb'; 6274 6275@Entry 6276@Component 6277struct WebComponent { 6278 controller: webview.WebviewController = new webview.WebviewController(); 6279 6280 build() { 6281 Column() { 6282 Button('getRenderProcessMode') 6283 .onClick(() => { 6284 let mode = webview.WebviewController.getRenderProcessMode(); 6285 console.log("getRenderProcessMode: " + mode); 6286 }) 6287 Web({ src: 'www.example.com', controller: this.controller }) 6288 } 6289 } 6290} 6291``` 6292 6293### terminateRenderProcess<sup>12+</sup> 6294 6295terminateRenderProcess(): boolean 6296 6297Terminates this render process. 6298 6299Calling 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. 6300 6301**System capability**: SystemCapability.Web.Webview.Core 6302 6303**Return value** 6304 6305| Type | Description | 6306| ------------------------------------------------------------ | ---------------------- | 6307| 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.| 6308 6309**Error codes** 6310 6311For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6312 6313| ID | Error Message | 6314| -------- | ------------------------------------------------------------ | 6315| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6316 6317**Example** 6318 6319```ts 6320// xxx.ets 6321import { webview } from '@kit.ArkWeb'; 6322 6323@Entry 6324@Component 6325struct WebComponent { 6326 controller: webview.WebviewController = new webview.WebviewController(); 6327 6328 build() { 6329 Column() { 6330 Button('terminateRenderProcess') 6331 .onClick(() => { 6332 let result = this.controller.terminateRenderProcess(); 6333 console.log("terminateRenderProcess result: " + result); 6334 }) 6335 Web({ src: 'www.example.com', controller: this.controller }) 6336 } 6337 } 6338} 6339``` 6340 6341### postUrl<sup>11+</sup> 6342 6343postUrl(url: string, postData: ArrayBuffer): void 6344 6345Loads 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. 6346 6347**System capability**: SystemCapability.Web.Webview.Core 6348 6349**Parameters** 6350 6351| Name | Type | Mandatory| Description | 6352| ------- | ---------------- | ---- | :-------------------- | 6353| url | string | Yes | URL to load. | 6354| postData | ArrayBuffer | Yes | Data to transfer using the POST method. The request must be encoded in "application/x-www-form-urlencoded" format.| 6355 6356**Error codes** 6357 6358For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6359 6360| ID| Error Message | 6361| -------- | ------------------------------------------------------------ | 6362| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6363| 17100002 | Invalid url. | 6364| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 6365 6366**Example** 6367 6368```ts 6369// xxx.ets 6370import { webview } from '@kit.ArkWeb'; 6371import { BusinessError } from '@kit.BasicServicesKit'; 6372 6373class TestObj { 6374 constructor() { 6375 } 6376 6377 test(str: string): ArrayBuffer { 6378 let buf = new ArrayBuffer(str.length); 6379 let buff = new Uint8Array(buf); 6380 6381 for (let i = 0; i < str.length; i++) { 6382 buff[i] = str.charCodeAt(i); 6383 } 6384 return buf; 6385 } 6386} 6387 6388@Entry 6389@Component 6390struct WebComponent { 6391 controller: webview.WebviewController = new webview.WebviewController(); 6392 @State testObjtest: TestObj = new TestObj(); 6393 6394 build() { 6395 Column() { 6396 Button('postUrl') 6397 .onClick(() => { 6398 try { 6399 // Convert data to the ArrayBuffer type. 6400 let postData = this.testObjtest.test("Name=test&Password=test"); 6401 this.controller.postUrl('www.example.com', postData); 6402 } catch (error) { 6403 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6404 } 6405 }) 6406 Web({ src: '', controller: this.controller }) 6407 } 6408 } 6409} 6410``` 6411 6412### createWebPrintDocumentAdapter<sup>11+</sup> 6413 6414createWebPrintDocumentAdapter(jobName: string): print.PrintDocumentAdapter 6415 6416Creates a **PrintDocumentAdapter** instance to provide content for printing. 6417 6418**System capability**: SystemCapability.Web.Webview.Core 6419 6420**Parameters** 6421 6422| Name | Type | Mandatory| Description | 6423| ------- | ------ | ---- | :-------------------- | 6424| jobName | string | Yes | Name of the file to print. | 6425 6426**Return value** 6427 6428| Type | Description | 6429| -------------------- | ------------------------- | 6430| print.printDocumentAdapter | **PrintDocumentAdapter** instance created.| 6431 6432**Error codes** 6433 6434For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6435 6436| ID| Error Message | 6437| -------- | -------------------------------------------------------------------------- | 6438| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 6439| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6440 6441**Example** 6442 6443```ts 6444// xxx.ets 6445import { webview } from '@kit.ArkWeb'; 6446import { BusinessError, print } from '@kit.BasicServicesKit'; 6447 6448@Entry 6449@Component 6450struct WebComponent { 6451 controller: webview.WebviewController = new webview.WebviewController(); 6452 6453 build() { 6454 Column() { 6455 Button('createWebPrintDocumentAdapter') 6456 .onClick(() => { 6457 try { 6458 let webPrintDocadapter = this.controller.createWebPrintDocumentAdapter('example.pdf'); 6459 print.print('example_jobid', webPrintDocadapter, null, getContext()); 6460 } catch (error) { 6461 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6462 } 6463 }) 6464 Web({ src: 'www.example.com', controller: this.controller }) 6465 } 6466 } 6467} 6468``` 6469### isIncognitoMode<sup>11+</sup> 6470 6471isIncognitoMode(): boolean 6472 6473Checks whether this Webview is in incognito mode. 6474 6475**System capability**: SystemCapability.Web.Webview.Core 6476 6477**Return value** 6478 6479| Type | Description | 6480| -------------------- | ------------------------- | 6481| boolean | Whether the Webview is in incognito mode.| 6482 6483**Error codes** 6484 6485For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6486 6487| ID| Error Message | 6488| -------- | -------------------------------------------------------------------------- | 6489| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6490 6491**Example** 6492 6493```ts 6494// xxx.ets 6495import { webview } from '@kit.ArkWeb'; 6496import { BusinessError } from '@kit.BasicServicesKit'; 6497 6498@Entry 6499@Component 6500struct WebComponent { 6501 controller: webview.WebviewController = new webview.WebviewController(); 6502 6503 build() { 6504 Column() { 6505 Button('isIncognitoMode') 6506 .onClick(() => { 6507 try { 6508 let result = this.controller.isIncognitoMode(); 6509 console.log('isIncognitoMode' + result); 6510 } catch (error) { 6511 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6512 } 6513 }) 6514 Web({ src: 'www.example.com', controller: this.controller }) 6515 } 6516 } 6517} 6518``` 6519 6520### getSecurityLevel<sup>11+</sup> 6521 6522getSecurityLevel(): SecurityLevel 6523 6524Obtains the security level of this web page. 6525 6526**System capability**: SystemCapability.Web.Webview.Core 6527 6528**Return value** 6529 6530| Type | Description | 6531| ----------------------------------- | --------------------------- | 6532| [SecurityLevel](#securitylevel11) | Security level of the web page. The value can be **NONE**, **SECURE**, **WARNING**, or **DANGEROUS**.| 6533 6534**Error codes** 6535 6536For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6537 6538| ID| Error Message | 6539| -------- | ------------------------------------------------------------ | 6540| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6541 6542**Example** 6543 6544```ts 6545import { webview } from '@kit.ArkWeb'; 6546 6547@Entry 6548@Component 6549struct WebComponent { 6550 controller: webview.WebviewController = new webview.WebviewController(); 6551 6552 build() { 6553 Column() { 6554 Web({ src: 'www.example.com', controller: this.controller }) 6555 .onPageEnd((event) => { 6556 if (event) { 6557 let securityLevel = this.controller.getSecurityLevel(); 6558 console.info('securityLevel: ', securityLevel); 6559 } 6560 }) 6561 } 6562 } 6563} 6564``` 6565 6566### setScrollable<sup>12+</sup> 6567 6568setScrollable(enable: boolean, type?: ScrollType): void 6569 6570Sets whether this web page is scrollable. 6571 6572**System capability**: SystemCapability.Web.Webview.Core 6573 6574**Parameters** 6575 6576| Name| Type| Mandatory| Description | 6577| ------ | -------- | ---- | ---------------------- | 6578| enable | boolean | Yes | Whether the web page is scrollable. The value **true** means the web page is scrollable, and **false** means the opposite.| 6579| 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**.| 6580 6581**Error codes** 6582 6583For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6584 6585| ID| Error Message | 6586| -------- | ------------------------------------------------------------ | 6587| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 6588| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6589 6590**Example** 6591 6592```ts 6593// xxx.ets 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 Button('setScrollable') 6605 .onClick(() => { 6606 try { 6607 this.controller.setScrollable(true); 6608 } catch (error) { 6609 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6610 } 6611 }) 6612 Web({ src: 'www.example.com', controller: this.controller }) 6613 } 6614 } 6615} 6616``` 6617 6618### getScrollable<sup>12+</sup> 6619 6620getScrollable(): boolean 6621 6622Obtains whether this web page is scrollable. 6623 6624**System capability**: SystemCapability.Web.Webview.Core 6625 6626**Return value** 6627 6628| Type | Description | 6629| ------ | -------------- | 6630| boolean | Whether the web page is scrollable. The value **true** means the web page is scrollable, and **false** means the opposite.| 6631 6632**Error codes** 6633 6634For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6635 6636| ID| Error Message | 6637| -------- | ------------------------------------------------------------ | 6638| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6639 6640**Example** 6641 6642```ts 6643// xxx.ets 6644import { webview } from '@kit.ArkWeb'; 6645import { BusinessError } from '@kit.BasicServicesKit'; 6646 6647@Entry 6648@Component 6649struct WebComponent { 6650 controller: webview.WebviewController = new webview.WebviewController(); 6651 6652 build() { 6653 Column() { 6654 Button('getScrollable') 6655 .onClick(() => { 6656 try { 6657 let scrollEnabled = this.controller.getScrollable(); 6658 console.log("scrollEnabled: " + scrollEnabled); 6659 } catch (error) { 6660 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6661 } 6662 }) 6663 Web({ src: 'www.example.com', controller: this.controller }) 6664 } 6665 } 6666} 6667``` 6668 6669### setPrintBackground<sup>12+</sup> 6670 6671setPrintBackground(enable: boolean): void 6672 6673Sets whether to print the web page background. 6674 6675**System capability**: SystemCapability.Web.Webview.Core 6676 6677**Parameters** 6678 6679| Name | Type | Mandatory| Description | 6680| -------- | ------- | ---- | -------------------------------------- | 6681| 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.| 6682 6683**Error codes** 6684 6685For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6686 6687| ID| Error Message | 6688| -------- | ------------------------------------------------------------ | 6689| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 6690| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6691 6692**Example** 6693 6694```ts 6695import { webview } from '@kit.ArkWeb'; 6696import { BusinessError } from '@kit.BasicServicesKit'; 6697 6698@Entry 6699@Component 6700struct WebComponent { 6701 controller: webview.WebviewController = new webview.WebviewController(); 6702 6703 build() { 6704 Column() { 6705 Button('setPrintBackground') 6706 .onClick(() => { 6707 try { 6708 this.controller.setPrintBackground(false); 6709 } catch (error) { 6710 console.error(`ErrorCode:${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6711 } 6712 }) 6713 Web({ src: 'www.example.com', controller: this.controller }) 6714 } 6715 } 6716} 6717``` 6718 6719### getPrintBackground<sup>12+</sup> 6720 6721getPrintBackground(): boolean 6722 6723Obtains whether the web page background is printed. 6724 6725**System capability**: SystemCapability.Web.Webview.Core 6726 6727**Return value** 6728 6729| Type | Description | 6730| -------------------- | ------------------------- | 6731| boolean | Whether the web page background is printed.| 6732 6733**Error codes** 6734 6735For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6736 6737| ID| Error Message | 6738| -------- | ------------------------------------------------------------ | 6739| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6740 6741**Example** 6742 6743```ts 6744import { webview } from '@kit.ArkWeb'; 6745import { BusinessError } from '@kit.BasicServicesKit'; 6746 6747@Entry 6748@Component 6749struct WebComponent { 6750 controller: webview.WebviewController = new webview.WebviewController(); 6751 6752 build() { 6753 Column() { 6754 Button('setPrintBackground') 6755 .onClick(() => { 6756 try { 6757 let enable = this.controller.getPrintBackground(); 6758 console.log("getPrintBackground: " + enable); 6759 } catch (error) { 6760 console.error(`ErrorCode:${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6761 } 6762 }) 6763 Web({ src: 'www.example.com', controller: this.controller }) 6764 } 6765 } 6766} 6767``` 6768 6769### getLastJavascriptProxyCallingFrameUrl<sup>12+</sup> 6770 6771getLastJavascriptProxyCallingFrameUrl(): string 6772 6773Obtains 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). This API can be used to obtain the URL of the frame of the object that is injected last time. 6774 6775**System capability**: SystemCapability.Web.Webview.Core 6776 6777**Error codes** 6778 6779For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6780 6781| ID| Error Message | 6782| -------- | ------------------------------------------------------------ | 6783| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6784 6785**Example** 6786 6787```ts 6788// xxx.ets 6789import { webview } from '@kit.ArkWeb'; 6790import { BusinessError } from '@kit.BasicServicesKit'; 6791 6792class TestObj { 6793 mycontroller: webview.WebviewController; 6794 6795 constructor(controller: webview.WebviewController) { 6796 this.mycontroller = controller; 6797 } 6798 6799 test(testStr: string): string { 6800 console.log('Web Component str' + testStr + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 6801 return testStr; 6802 } 6803 6804 toString(): void { 6805 console.log('Web Component toString ' + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 6806 } 6807 6808 testNumber(testNum: number): number { 6809 console.log('Web Component number' + testNum + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 6810 return testNum; 6811 } 6812 6813 testBool(testBol: boolean): boolean { 6814 console.log('Web Component boolean' + testBol + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 6815 return testBol; 6816 } 6817} 6818 6819class WebObj { 6820 mycontroller: webview.WebviewController; 6821 6822 constructor(controller: webview.WebviewController) { 6823 this.mycontroller = controller; 6824 } 6825 6826 webTest(): string { 6827 console.log('Web test ' + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 6828 return "Web test"; 6829 } 6830 6831 webString(): void { 6832 console.log('Web test toString ' + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 6833 } 6834} 6835 6836@Entry 6837@Component 6838struct Index { 6839 controller: webview.WebviewController = new webview.WebviewController(); 6840 @State testObjtest: TestObj = new TestObj(this.controller); 6841 @State webTestObj: WebObj = new WebObj(this.controller); 6842 6843 build() { 6844 Column() { 6845 Button('refresh') 6846 .onClick(() => { 6847 try { 6848 this.controller.refresh(); 6849 } catch (error) { 6850 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6851 } 6852 }) 6853 Button('Register JavaScript To Window') 6854 .onClick(() => { 6855 try { 6856 this.controller.registerJavaScriptProxy(this.testObjtest, "objName", ["test", "toString", "testNumber", "testBool"]); 6857 this.controller.registerJavaScriptProxy(this.webTestObj, "objTestName", ["webTest", "webString"]); 6858 } catch (error) { 6859 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6860 } 6861 }) 6862 Button('deleteJavaScriptRegister') 6863 .onClick(() => { 6864 try { 6865 this.controller.deleteJavaScriptRegister("objName"); 6866 this.controller.deleteJavaScriptRegister("objTestName"); 6867 } catch (error) { 6868 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6869 } 6870 }) 6871 Web({ src: $rawfile('index.html'), controller: this.controller }) 6872 .javaScriptAccess(true) 6873 } 6874 } 6875} 6876``` 6877 6878HTML file to be loaded: 6879```html 6880<!-- index.html --> 6881<!DOCTYPE html> 6882<html> 6883 <meta charset="utf-8"> 6884 <body> 6885 <button type="button" onclick="htmlTest()">Click Me!</button> 6886 <p id="demo"></p> 6887 <p id="webDemo"></p> 6888 </body> 6889 <script type="text/javascript"> 6890 function htmlTest() { 6891 // This function call expects to return "ArkUI Web Component" 6892 let str=objName.test("webtest data"); 6893 objName.testNumber(1); 6894 objName.testBool(true); 6895 document.getElementById("demo").innerHTML=str; 6896 console.log('objName.test result:'+ str) 6897 6898 // This function call expects to return "Web test" 6899 let webStr = objTestName.webTest(); 6900 document.getElementById("webDemo").innerHTML=webStr; 6901 console.log('objTestName.webTest result:'+ webStr) 6902 } 6903</script> 6904</html> 6905``` 6906 6907### pauseAllTimers<sup>12+</sup> 6908 6909pauseAllTimers(): void 6910 6911Pauses all WebView timers. 6912 6913**System capability**: SystemCapability.Web.Webview.Core 6914 6915**Error codes** 6916 6917For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6918 6919| ID| Error Message | 6920| -------- | ------------------------------------------------------------ | 6921| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6922 6923**Example** 6924 6925```ts 6926import { webview } from '@kit.ArkWeb'; 6927import { BusinessError } from '@kit.BasicServicesKit'; 6928 6929@Entry 6930@Component 6931struct WebComponent { 6932 controller: webview.WebviewController = new webview.WebviewController(); 6933 6934 build() { 6935 Column() { 6936 Row() { 6937 Button('PauseAllTimers') 6938 .onClick(() => { 6939 try { 6940 webview.WebviewController.pauseAllTimers(); 6941 } catch (error) { 6942 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6943 } 6944 }) 6945 } 6946 Web({ src: $rawfile("index.html"), controller: this.controller }) 6947 } 6948 } 6949} 6950``` 6951HTML file to be loaded: 6952 6953```html 6954<!DOCTYPE html> 6955<html> 6956 <body> 6957 <button style="width:300px;height:150px;font-size:50px" onclick="startTimer()">start</button> 6958 <button style="width:300px;height:150px;font-size:50px" onclick="resetTimer()">reset</button> 6959 <input style="width:300px;height:150px;font-size:50px" value="0" id="show_num"> 6960 </body> 6961</html> 6962<script> 6963 var timer = null; 6964 var num = 0; 6965 6966 function startTimer() { 6967 timer = setInterval(function() { 6968 document.getElementById("show_num").value = ++num; 6969 }, 1000); 6970 } 6971</script> 6972``` 6973 6974### resumeAllTimers<sup>12+</sup> 6975 6976resumeAllTimers(): void 6977 6978Resumes all timers that are paused from the **pauseAllTimers()** API. 6979 6980**System capability**: SystemCapability.Web.Webview.Core 6981 6982**Error codes** 6983 6984For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6985 6986| ID| Error Message | 6987| -------- | ------------------------------------------------------------ | 6988| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6989 6990**Example** 6991 6992```ts 6993import { webview } from '@kit.ArkWeb'; 6994import { BusinessError } from '@kit.BasicServicesKit'; 6995 6996@Entry 6997@Component 6998struct WebComponent { 6999 controller: webview.WebviewController = new webview.WebviewController(); 7000 7001 build() { 7002 Column() { 7003 Row() { 7004 Button('ResumeAllTimers') 7005 .onClick(() => { 7006 try { 7007 webview.WebviewController.resumeAllTimers(); 7008 } catch (error) { 7009 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7010 } 7011 }) 7012 Button('PauseAllTimers') 7013 .onClick(() => { 7014 try { 7015 webview.WebviewController.pauseAllTimers(); 7016 } catch (error) { 7017 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7018 } 7019 }) 7020 } 7021 Web({ src: $rawfile("index.html"), controller: this.controller }) 7022 } 7023 } 7024} 7025``` 7026HTML file to be loaded: 7027 7028```html 7029<!DOCTYPE html> 7030<html> 7031 <body> 7032 <button style="width:300px;height:150px;font-size:50px" onclick="startTimer()">start</button> 7033 <button style="width:300px;height:150px;font-size:50px" onclick="resetTimer()">reset</button> 7034 <input style="width:300px;height:150px;font-size:50px" value="0" id="show_num"> 7035 </body> 7036</html> 7037<script> 7038 var timer = null; 7039 var num = 0; 7040 7041 function startTimer() { 7042 timer = setInterval(function() { 7043 document.getElementById("show_num").value = ++num; 7044 }, 1000); 7045 } 7046 7047 function resetTimer() { 7048 clearInterval(timer); 7049 document.getElementById("show_num").value = 0; 7050 num = 0; 7051 } 7052</script> 7053``` 7054 7055### stopAllMedia<sup>12+</sup> 7056 7057stopAllMedia(): void 7058 7059Stops all audio and video on a web page. 7060 7061**System capability**: SystemCapability.Web.Webview.Core 7062 7063**Error codes** 7064 7065For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7066 7067| ID| Error Message | 7068| -------- | ------------------------------------------------------------ | 7069| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7070 7071**Example** 7072 7073```ts 7074// xxx.ets 7075import { webview } from '@kit.ArkWeb'; 7076import { BusinessError } from '@kit.BasicServicesKit'; 7077 7078@Entry 7079@Component 7080struct WebComponent { 7081 controller: webview.WebviewController = new webview.WebviewController(); 7082 7083 build() { 7084 Column() { 7085 Button('stopAllMedia') 7086 .onClick(() => { 7087 try { 7088 this.controller.stopAllMedia(); 7089 } catch (error) { 7090 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7091 } 7092 }) 7093 Web({ src: 'www.example.com', controller: this.controller }) 7094 } 7095 } 7096} 7097``` 7098 7099### pauseAllMedia<sup>12+</sup> 7100 7101pauseAllMedia(): void 7102 7103Pauses all audio and video on a web page. 7104 7105**System capability**: SystemCapability.Web.Webview.Core 7106 7107**Error codes** 7108 7109For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7110 7111| ID| Error Message | 7112| -------- | ------------------------------------------------------------ | 7113| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7114 7115**Example** 7116 7117```ts 7118// xxx.ets 7119import { webview } from '@kit.ArkWeb'; 7120import { BusinessError } from '@kit.BasicServicesKit'; 7121 7122@Entry 7123@Component 7124struct WebComponent { 7125 controller: webview.WebviewController = new webview.WebviewController(); 7126 7127 build() { 7128 Column() { 7129 Button('pauseAllMedia') 7130 .onClick(() => { 7131 try { 7132 this.controller.pauseAllMedia(); 7133 } catch (error) { 7134 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7135 } 7136 }) 7137 Web({ src: 'www.example.com', controller: this.controller }) 7138 } 7139 } 7140} 7141``` 7142 7143### resumeAllMedia<sup>12+</sup> 7144 7145resumeAllMedia(): void 7146 7147Resumes the playback of the audio and video that are paused by the pauseAllMedia interface. 7148 7149**System capability**: SystemCapability.Web.Webview.Core 7150 7151**Error codes** 7152 7153For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7154 7155| ID| Error Message | 7156| -------- | ------------------------------------------------------------ | 7157| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7158 7159**Example** 7160 7161```ts 7162// xxx.ets 7163import { webview } from '@kit.ArkWeb'; 7164import { BusinessError } from '@kit.BasicServicesKit'; 7165 7166@Entry 7167@Component 7168struct WebComponent { 7169 controller: webview.WebviewController = new webview.WebviewController(); 7170 7171 build() { 7172 Column() { 7173 Button('resumeAllMedia') 7174 .onClick(() => { 7175 try { 7176 this.controller.resumeAllMedia(); 7177 } catch (error) { 7178 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7179 } 7180 }) 7181 Web({ src: 'www.example.com', controller: this.controller }) 7182 } 7183 } 7184} 7185``` 7186 7187### closeAllMediaPresentations<sup>12+</sup> 7188 7189closeAllMediaPresentations(): void 7190 7191Closes all full-screen videos on a web page. 7192 7193**System capability**: SystemCapability.Web.Webview.Core 7194 7195**Error codes** 7196 7197For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7198 7199| ID| Error Message | 7200| -------- | ------------------------------------------------------------ | 7201| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7202 7203**Example** 7204 7205```ts 7206// xxx.ets 7207import { webview } from '@kit.ArkWeb'; 7208import { BusinessError } from '@kit.BasicServicesKit'; 7209 7210@Entry 7211@Component 7212struct WebComponent { 7213 controller: webview.WebviewController = new webview.WebviewController(); 7214 7215 build() { 7216 Column() { 7217 Button('closeAllMediaPresentations') 7218 .onClick(() => { 7219 try { 7220 this.controller.closeAllMediaPresentations(); 7221 } catch (error) { 7222 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7223 } 7224 }) 7225 Web({ src: 'www.example.com', controller: this.controller }) 7226 } 7227 } 7228} 7229``` 7230 7231### getMediaPlaybackState<sup>12+</sup> 7232 7233getMediaPlaybackState(): MediaPlaybackState 7234 7235Queries the current audio and video playback control status. 7236 7237**System capability**: SystemCapability.Web.Webview.Core 7238 7239**Return value** 7240 7241| Type | Description | 7242| ------------------------------------------- | --------------------------------------------------------- | 7243| [MediaPlaybackState](#mediaplaybackstate12) | Playback control status of the current web page. The options are **NONE**, **PLAYING**, **PAUSED**, and **STOPPED**.| 7244 7245**Error codes** 7246 7247For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7248 7249| ID| Error Message | 7250| -------- | ------------------------------------------------------------ | 7251| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7252 7253**Example** 7254 7255```ts 7256// xxx.ets 7257import { webview } from '@kit.ArkWeb'; 7258import { BusinessError } from '@kit.BasicServicesKit'; 7259 7260@Entry 7261@Component 7262struct WebComponent { 7263 controller: webview.WebviewController = new webview.WebviewController(); 7264 7265 build() { 7266 Column() { 7267 Button('getMediaPlaybackState') 7268 .onClick(() => { 7269 try { 7270 console.log("MediaPlaybackState : " + this.controller.getMediaPlaybackState()); 7271 } catch (error) { 7272 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7273 } 7274 }) 7275 Web({ src: 'www.example.com', controller: this.controller }) 7276 } 7277 } 7278} 7279``` 7280 7281### setWebSchemeHandler<sup>12+</sup> 7282 7283setWebSchemeHandler(scheme: string, handler: WebSchemeHandler): void 7284 7285Sets the [WebSchemeHandler](#webschemehandler12), [WebSchemeHandler](#webschemehandler12) class for the current Web component to intercept requests of a specified scheme. 7286 7287**System capability**: SystemCapability.Web.Webview.Core 7288 7289**Parameters** 7290 7291| Name| Type | Mandatory| Description | 7292| ------ | ------ | ---- | :------------------------ | 7293| scheme | string | Yes | Protocol to be intercepted.| 7294| handler | [WebSchemeHandler](#webschemehandler12) | Yes | Interceptor that intercepts this protocol.| 7295 7296**Error codes** 7297 7298For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7299 7300| ID| Error Message | 7301| -------- | ------------------------------------------------------------ | 7302| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 7303| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7304 7305**Example** 7306 7307```ts 7308// xxx.ets 7309import { webview } from '@kit.ArkWeb'; 7310import { BusinessError } from '@kit.BasicServicesKit'; 7311 7312@Entry 7313@Component 7314struct WebComponent { 7315 controller: webview.WebviewController = new webview.WebviewController(); 7316 schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); 7317 7318 build() { 7319 Column() { 7320 Button('setWebSchemeHandler') 7321 .onClick(() => { 7322 try { 7323 this.controller.setWebSchemeHandler('http', this.schemeHandler); 7324 } catch (error) { 7325 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7326 } 7327 }) 7328 Web({ src: 'www.example.com', controller: this.controller }) 7329 } 7330 } 7331} 7332``` 7333 7334### clearWebSchemeHandler<sup>12+</sup> 7335 7336clearWebSchemeHandler(): void 7337 7338Clears all WebSchemeHandlers set for the current Web component. 7339 7340**System capability**: SystemCapability.Web.Webview.Core 7341 7342**Error codes** 7343 7344For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7345 7346| ID| Error Message | 7347| -------- | ------------------------------------------------------------ | 7348| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7349 7350**Example** 7351 7352```ts 7353// xxx.ets 7354import { webview } from '@kit.ArkWeb'; 7355import { BusinessError } from '@kit.BasicServicesKit'; 7356 7357@Entry 7358@Component 7359struct WebComponent { 7360 controller: webview.WebviewController = new webview.WebviewController(); 7361 7362 build() { 7363 Column() { 7364 Button('clearWebSchemeHandler') 7365 .onClick(() => { 7366 try { 7367 this.controller.clearWebSchemeHandler(); 7368 } catch (error) { 7369 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7370 } 7371 }) 7372 Web({ src: 'www.example.com', controller: this.controller }) 7373 } 7374 } 7375} 7376``` 7377 7378### setServiceWorkerWebSchemeHandler<sup>12+</sup> 7379 7380setServiceWorkerWebSchemeHandler(scheme: string, handler: WebSchemeHandler): void 7381 7382Sets the WebSchemeHandler used to intercept ServiceWorker for all Web components of the current application. 7383 7384**System capability**: SystemCapability.Web.Webview.Core 7385 7386**Parameters** 7387 7388| Name| Type | Mandatory| Description | 7389| ------ | ------ | ---- | :------------------------ | 7390| scheme | string | Yes | Protocol to be intercepted.| 7391| handler | [WebSchemeHandler](#webschemehandler12) | Yes | Interceptor that intercepts this protocol.| 7392 7393**Error codes** 7394 7395For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7396 7397| ID| Error Message | 7398| -------- | ------------------------------------------------------------ | 7399| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 7400 7401**Example** 7402 7403```ts 7404// xxx.ets 7405import { webview } from '@kit.ArkWeb'; 7406import { BusinessError } from '@kit.BasicServicesKit'; 7407 7408@Entry 7409@Component 7410struct WebComponent { 7411 controller: webview.WebviewController = new webview.WebviewController(); 7412 schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); 7413 7414 build() { 7415 Column() { 7416 Button('setWebSchemeHandler') 7417 .onClick(() => { 7418 try { 7419 webview.WebviewController.setServiceWorkerWebSchemeHandler('http', this.schemeHandler); 7420 } catch (error) { 7421 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7422 } 7423 }) 7424 Web({ src: 'www.example.com', controller: this.controller }) 7425 } 7426 } 7427} 7428``` 7429 7430### clearServiceWorkerWebSchemeHandler<sup>12+</sup> 7431 7432clearServiceWorkerWebSchemeHandler(): void 7433 7434Clears all WebSchemeHandlers that are set in the application and used to intercept ServiceWorker. 7435 7436**System capability**: SystemCapability.Web.Webview.Core 7437 7438**Example** 7439 7440```ts 7441// xxx.ets 7442import { webview } from '@kit.ArkWeb'; 7443 7444@Entry 7445@Component 7446struct WebComponent { 7447 controller: webview.WebviewController = new webview.WebviewController(); 7448 7449 build() { 7450 Column() { 7451 Button('clearServiceWorkerWebSchemeHandler') 7452 .onClick(() => { 7453 webview.WebviewController.clearServiceWorkerWebSchemeHandler(); 7454 }) 7455 Web({ src: 'www.example.com', controller: this.controller }) 7456 } 7457 } 7458} 7459``` 7460 7461### startCamera<sup>12+</sup> 7462 7463startCamera(): void 7464 7465Enables the camera capture of the current web page. 7466 7467**System capability**: SystemCapability.Web.Webview.Core 7468 7469**Error codes** 7470 7471For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7472 7473| ID| Error Message | 7474| -------- | ------------------------------------------------------------ | 7475| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7476 7477**Example** 7478```ts 7479// xxx.ets 7480import { webview } from '@kit.ArkWeb'; 7481import { BusinessError } from '@kit.BasicServicesKit'; 7482import { abilityAccessCtrl, PermissionRequestResult, common } from '@kit.AbilityKit'; 7483 7484let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); 7485try { 7486 let context: Context = getContext(this) as common.UIAbilityContext; 7487 atManager.requestPermissionsFromUser(context, ['ohos.permission.CAMERA'], (err: BusinessError, data: PermissionRequestResult) => { 7488 console.info('data:' + JSON.stringify(data)); 7489 console.info('data permissions:' + data.permissions); 7490 console.info('data authResults:' + data.authResults); 7491 }) 7492} catch (error) { 7493 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7494} 7495 7496@Entry 7497@Component 7498struct WebComponent { 7499 controller: webview.WebviewController = new webview.WebviewController(); 7500 7501 build() { 7502 Column() { 7503 Button("startCamera").onClick(() => { 7504 try { 7505 this.controller.startCamera(); 7506 } catch (error) { 7507 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7508 } 7509 }) 7510 Button("stopCamera").onClick(() => { 7511 try { 7512 this.controller.stopCamera(); 7513 } catch (error) { 7514 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7515 } 7516 }) 7517 Button("closeCamera").onClick(() => { 7518 try { 7519 this.controller.closeCamera(); 7520 } catch (error) { 7521 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7522 } 7523 }) 7524 Web({ src: $rawfile('index.html'), controller: this.controller }) 7525 .onPermissionRequest((event) => { 7526 if (event) { 7527 AlertDialog.show({ 7528 title: 'title', 7529 message: 'text', 7530 primaryButton: { 7531 value: 'deny', 7532 action: () => { 7533 event.request.deny(); 7534 } 7535 }, 7536 secondaryButton: { 7537 value: 'onConfirm', 7538 action: () => { 7539 event.request.grant(event.request.getAccessibleResource()); 7540 } 7541 }, 7542 cancel: () => { 7543 event.request.deny(); 7544 } 7545 }) 7546 } 7547 }) 7548 } 7549 } 7550} 7551 7552``` 7553HTML file to be loaded: 7554 ```html 7555<!-- index.html --> 7556<!DOCTYPE html> 7557<html> 7558 <head> 7559 <meta charset="UTF-8"> 7560 </head> 7561 <body> 7562 <video id="video" width="400px" height="400px" autoplay="autoplay"> 7563 </video> 7564 <input type="button" title="HTML5 Camera" value="Enable Camera" onclick="getMedia()"/> 7565 <script> 7566 function getMedia() { 7567 let constraints = { 7568 video: { 7569 width: 500, 7570 height: 500 7571 }, 7572 audio: true 7573 } 7574 let video = document.getElementById("video"); 7575 let promise = navigator.mediaDevices.getUserMedia(constraints); 7576 promise.then(function(MediaStream) { 7577 video.srcObject = MediaStream; 7578 video.play(); 7579 }) 7580 } 7581 </script> 7582 </body> 7583</html> 7584 ``` 7585 7586### stopCamera<sup>12+</sup> 7587 7588stopCamera(): void 7589 7590Stops the camera capture of the current web page. 7591 7592**System capability**: SystemCapability.Web.Webview.Core 7593 7594**Error codes** 7595 7596For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7597 7598| ID| Error Message | 7599| -------- | ------------------------------------------------------------ | 7600| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7601 7602**Example** 7603 7604For the complete sample code, see [startCamera](#startcamera12). 7605 7606### closeCamera<sup>12+</sup> 7607 7608closeCamera(): void 7609 7610Disables the camera capture of the current web page. 7611 7612**System capability**: SystemCapability.Web.Webview.Core 7613 7614**Error codes** 7615 7616For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7617 7618| ID| Error Message | 7619| -------- | ------------------------------------------------------------ | 7620| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7621 7622**Example** 7623 7624For the complete sample code, see [startCamera](#startcamera12). 7625 7626### precompileJavaScript<sup>12+</sup> 7627 7628precompileJavaScript(url: string, script: string | Uint8Array, cacheOptions: CacheOptions): Promise\<number\> 7629 7630Precompiles JavaScript to generate the bytecode cache or update the existing bytecode cache based on the provided parameters. 7631The API determines whether to update the existing bytecode cache based on the provided file information, E-Tag response header, and Last-Modified response header. 7632 7633**System capability**: SystemCapability.Web.Webview.Core 7634 7635**Parameters** 7636 7637| Name | Type | Mandatory| Description | 7638| ------- | ------ | ---- | :-------------------- | 7639| 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. | 7640| script | string \| Uint8Array | Yes | Text content of the local JavaScript. The content cannot be empty. | 7641| cacheOptions | [CacheOptions](#cacheoptions12) | Yes | Whether to update the bytecode cache. | 7642 7643**Return value** 7644 7645| Type | Description | 7646| ----------------------------------- | --------------------------- | 7647| 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.| 7648 7649**Error codes** 7650 7651For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7652 7653| ID| Error Message | 7654| -------- | ------------------------------------------------------------ | 7655| 401 | Invalid input parameter.Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | 7656| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7657 7658**Example** 7659 7660The 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: 7661 76621. Save **UIContext** to localStorage in **EntryAbility**. 7663 7664 ```ts 7665 // EntryAbility.ets 7666 import { UIAbility } from '@kit.AbilityKit'; 7667 import { window } from '@kit.ArkUI'; 7668 7669 const localStorage: LocalStorage = new LocalStorage('uiContext'); 7670 7671 export default class EntryAbility extends UIAbility { 7672 storage: LocalStorage = localStorage; 7673 7674 onWindowStageCreate(windowStage: window.WindowStage) { 7675 windowStage.loadContent('pages/Index', this.storage, (err, data) => { 7676 if (err.code) { 7677 return; 7678 } 7679 7680 this.storage.setOrCreate<UIContext>("uiContext", windowStage.getMainWindowSync().getUIContext()); 7681 }); 7682 } 7683 } 7684 ``` 7685 76862. Write the basic code required by the dynamic component. 7687 7688 ```ts 7689 // DynamicComponent.ets 7690 import { NodeController, BuilderNode, FrameNode, UIContext } from '@kit.ArkUI'; 7691 7692 export interface BuilderData { 7693 url: string; 7694 controller: WebviewController; 7695 } 7696 7697 const storage = LocalStorage.getShared(); 7698 7699 export class NodeControllerImpl extends NodeController { 7700 private rootNode: BuilderNode<BuilderData[]> | null = null; 7701 private wrappedBuilder: WrappedBuilder<BuilderData[]> | null = null; 7702 7703 constructor(wrappedBuilder: WrappedBuilder<BuilderData[]>) { 7704 super(); 7705 this.wrappedBuilder = wrappedBuilder; 7706 } 7707 7708 makeNode(): FrameNode | null { 7709 if (this.rootNode != null) { 7710 return this.rootNode.getFrameNode(); 7711 } 7712 return null; 7713 } 7714 7715 initWeb(url: string, controller: WebviewController) { 7716 if(this.rootNode != null) { 7717 return; 7718 } 7719 7720 const uiContext: UIContext = storage.get<UIContext>("uiContext") as UIContext; 7721 if (!uiContext) { 7722 return; 7723 } 7724 this.rootNode = new BuilderNode(uiContext); 7725 this.rootNode.build(this.wrappedBuilder, { url: url, controller: controller }); 7726 } 7727 } 7728 7729 export const createNode = (wrappedBuilder: WrappedBuilder<BuilderData[]>, data: BuilderData) => { 7730 const baseNode = new NodeControllerImpl(wrappedBuilder); 7731 baseNode.initWeb(data.url, data.controller); 7732 return baseNode; 7733 } 7734 ``` 7735 77363. 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. 7737 7738 <!--code_no_check--> 7739 ```ts 7740 // PrecompileWebview.ets 7741 import { BuilderData } from "./DynamicComponent"; 7742 import { Config, configs } from "./PrecompileConfig"; 7743 7744 @Builder 7745 function WebBuilder(data: BuilderData) { 7746 Web({ src: data.url, controller: data.controller }) 7747 .onControllerAttached(() => { 7748 precompile(data.controller, configs); 7749 }) 7750 .fileAccess(true) 7751 } 7752 7753 export const precompileWebview = wrapBuilder<BuilderData[]>(WebBuilder); 7754 7755 export const precompile = async (controller: WebviewController, configs: Array<Config>) => { 7756 for (const config of configs) { 7757 let content = await readRawFile(config.localPath); 7758 7759 try { 7760 controller.precompileJavaScript(config.url, content, config.options) 7761 .then(errCode => { 7762 console.error("precompile successfully! " + errCode); 7763 }).catch((errCode: number) => { 7764 console.error("precompile failed. " + errCode); 7765 }); 7766 } catch (err) { 7767 console.error("precompile failed. " + err.code + " " + err.message); 7768 } 7769 } 7770 } 7771 7772 async function readRawFile(path: string) { 7773 try { 7774 return await getContext().resourceManager.getRawFileContent(path);; 7775 } catch (err) { 7776 return new Uint8Array(0); 7777 } 7778 } 7779 ``` 7780 7781JavaScript 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. 7782 77834. Compile the code of the service component. 7784 7785 <!--code_no_check--> 7786 ```ts 7787 // BusinessWebview.ets 7788 import { BuilderData } from "./DynamicComponent"; 7789 7790 @Builder 7791 function WebBuilder(data: BuilderData) { 7792 // The component can be extended based on service requirements. 7793 Web({ src: data.url, controller: data.controller }) 7794 .cacheMode(CacheMode.Default) 7795 } 7796 7797 export const businessWebview = wrapBuilder<BuilderData[]>(WebBuilder); 7798 ``` 7799 78005. Write the resource configuration information. 7801 7802 ```ts 7803 // PrecompileConfig.ets 7804 import { webview } from '@kit.ArkWeb' 7805 7806 export interface Config { 7807 url: string, 7808 localPath: string, // Local resource path 7809 options: webview.CacheOptions 7810 } 7811 7812 export let configs: Array<Config> = [ 7813 { 7814 url: "https://www.example.com/example.js", 7815 localPath: "example.js", 7816 options: { 7817 responseHeaders: [ 7818 { headerKey: "E-Tag", headerValue: "aWO42N9P9dG/5xqYQCxsx+vDOoU="}, 7819 { headerKey: "Last-Modified", headerValue: "Wed, 21 Mar 2024 10:38:41 GMT"} 7820 ] 7821 } 7822 } 7823 ] 7824 ``` 7825 78266. Use the component on the page. 7827 7828 <!--code_no_check--> 7829 ```ts 7830 // Index.ets 7831 import { webview } from '@kit.ArkWeb'; 7832 import { NodeController } from '@kit.ArkUI'; 7833 import { createNode } from "./DynamicComponent" 7834 import { precompileWebview } from "./PrecompileWebview" 7835 import { businessWebview } from "./BusinessWebview" 7836 7837 @Entry 7838 @Component 7839 struct Index { 7840 @State precompileNode: NodeController | undefined = undefined; 7841 precompileController: webview.WebviewController = new webview.WebviewController(); 7842 7843 @State businessNode: NodeController | undefined = undefined; 7844 businessController: webview.WebviewController = new webview.WebviewController(); 7845 7846 aboutToAppear(): void { 7847 // Initialize the Web component used to inject local resources. 7848 this.precompileNode = createNode(precompileWebview, 7849 { url: "https://www.example.com/empty.html", controller: this.precompileController}); 7850 } 7851 7852 build() { 7853 Column() { 7854 // Load the Web component used by the service at a proper time. In this example, the button is clicked. 7855 Button ("Load Page") 7856 .onClick(() => { 7857 this.businessNode = createNode(businessWebview, { 7858 url: "https://www.example.com/business.html", 7859 controller: this.businessController 7860 }); 7861 }) 7862 // The Web component used for the service. 7863 NodeContainer(this.businessNode); 7864 } 7865 } 7866 } 7867 ``` 7868 7869To 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. 7870 7871### onCreateNativeMediaPlayer<sup>12+</sup> 7872 7873onCreateNativeMediaPlayer(callback: CreateNativeMediaPlayerCallback): void 7874 7875Called 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. 7876If the application does not take over media playback on the web page, this callback is not invoked. 7877 7878**System capability**: SystemCapability.Web.Webview.Core 7879 7880**Parameters** 7881 7882| Name| Type| Mandatory| Description| 7883|--------|------|------|------| 7884| callback | [CreateNativeMediaPlayerCallback](#createnativemediaplayercallback12) | Yes| Callback when the application takes over media playback on the web page.| 7885 7886**Example** 7887 7888```ts 7889// xxx.ets 7890import { webview } from '@kit.ArkWeb'; 7891 7892class ActualNativeMediaPlayerListener { 7893 handler: webview.NativeMediaPlayerHandler; 7894 7895 constructor(handler: webview.NativeMediaPlayerHandler) { 7896 this.handler = handler; 7897 } 7898 7899 onPlaying() { 7900 // The native media player starts playback. 7901 this.handler.handleStatusChanged(webview.PlaybackStatus.PLAYING); 7902 } 7903 onPaused() { 7904 // The native media player pauses the playback. 7905 this.handler.handleStatusChanged(webview.PlaybackStatus.PAUSED); 7906 } 7907 onSeeking() { 7908 // The local player starts to jump to the target time point. 7909 this.handler.handleSeeking(); 7910 } 7911 onSeekDone() { 7912 // The native media player seeks to the target time point. 7913 this.handler.handleSeekFinished(); 7914 } 7915 onEnded() { 7916 // The playback on the native media player is ended. 7917 this.handler.handleEnded(); 7918 } 7919 onVolumeChanged() { 7920 // Obtain the volume of the local player. 7921 let volume: number = getVolume(); 7922 this.handler.handleVolumeChanged(volume); 7923 } 7924 onCurrentPlayingTimeUpdate() { 7925 // Update the playback time. 7926 let currentTime: number = getCurrentPlayingTime(); 7927 // Convert the time unit to second. 7928 let currentTimeInSeconds = convertToSeconds(currentTime); 7929 this.handler.handleTimeUpdate(currentTimeInSeconds); 7930 } 7931 onBufferedChanged() { 7932 // The cache is changed. 7933 // Obtain the cache duration of the native media player. 7934 let bufferedEndTime: number = getCurrentBufferedTime(); 7935 // Convert the time unit to second. 7936 let bufferedEndTimeInSeconds = convertToSeconds(bufferedEndTime); 7937 this.handler.handleBufferedEndTimeChanged(bufferedEndTimeInSeconds); 7938 7939 // Check the cache status. 7940 // If the cache status changes, notify the ArkWeb engine of the cache status. 7941 let lastReadyState: webview.ReadyState = getLastReadyState(); 7942 let currentReadyState: webview.ReadyState = getCurrentReadyState(); 7943 if (lastReadyState != currentReadyState) { 7944 this.handler.handleReadyStateChanged(currentReadyState); 7945 } 7946 } 7947 onEnterFullscreen() { 7948 // The native media player enters the full screen mode. 7949 let isFullscreen: boolean = true; 7950 this.handler.handleFullscreenChanged(isFullscreen); 7951 } 7952 onExitFullscreen() { 7953 // The native media player exits the full screen mode. 7954 let isFullscreen: boolean = false; 7955 this.handler.handleFullscreenChanged(isFullscreen); 7956 } 7957 onUpdateVideoSize(width: number, height: number) { 7958 // Notify the ArkWeb kernel when the native media player parses the video width and height. 7959 this.handler.handleVideoSizeChanged(width, height); 7960 } 7961 onDurationChanged(duration: number) { 7962 // Notify the ArkWeb kernel when the native media player parses the video duration. 7963 this.handler.handleDurationChanged(duration); 7964 } 7965 onError(error: webview.MediaError, errorMessage: string) { 7966 // Notify the ArkWeb kernel that an error occurs in the native media player. 7967 this.handler.handleError(error, errorMessage); 7968 } 7969 onNetworkStateChanged(state: webview.NetworkState) { 7970 // Notify the ArkWeb kernel that the network state of the native media player changes. 7971 this.handler.handleNetworkStateChanged(state); 7972 } 7973 onPlaybackRateChanged(playbackRate: number) { 7974 // Notify the ArkWeb kernel that the playback rate of the native media player changes. 7975 this.handler.handlePlaybackRateChanged(playbackRate); 7976 } 7977 onMutedChanged(muted: boolean) { 7978 // Notify the ArkWeb kernel that the native media player is muted. 7979 this.handler.handleMutedChanged(muted); 7980 } 7981 7982 // Listen for other state of the native media player. 7983} 7984 7985class NativeMediaPlayerImpl implements webview.NativeMediaPlayerBridge { 7986 constructor(handler: webview.NativeMediaPlayerHandler, mediaInfo: webview.MediaInfo) { 7987 // 1. Create a listener for the native media player. 7988 let listener: ActualNativeMediaPlayerListener = new ActualNativeMediaPlayerListener(handler); 7989 // 2. Create a native media player. 7990 // 3. Listen for the local player. 7991 // ... 7992 } 7993 7994 updateRect(x: number, y: number, width: number, height: number) { 7995 // The position and size of the <video> tag are changed. 7996 // Make changes based on the information change. 7997 } 7998 7999 play() { 8000 // Start the native media player for playback. 8001 } 8002 8003 pause() { 8004 //Pause the playback on the local player. 8005 } 8006 8007 seek(targetTime: number) { 8008 // The local player jumps to a specified time point. 8009 } 8010 8011 release() { 8012 // Destroy the local player. 8013 } 8014 8015 setVolume(volume: number) { 8016 // The ArkWeb kernel requires to adjust the volume of the local player. 8017 // Set the volume of the local player. 8018 } 8019 8020 setMuted(muted: boolean) { 8021 // Mute or unmute the local player. 8022 } 8023 8024 setPlaybackRate(playbackRate: number) { 8025 // Adjust the playback speed of the local player. 8026 } 8027 8028 enterFullscreen() { 8029 // Set the local player to play in full screen mode. 8030 } 8031 8032 exitFullscreen() { 8033 // Set the local player to exit full screen mode. 8034 } 8035 8036 resumePlayer() { 8037 // Create a player again. 8038 // Resume the status information of the player. 8039 } 8040 8041 suspendPlayer(type: webview.SuspendType) { 8042 // Record the status information of the player. 8043 // Destroy the player. 8044 } 8045} 8046 8047@Entry 8048@Component 8049struct WebComponent { 8050 controller: webview.WebviewController = new webview.WebviewController() 8051 build() { 8052 Column() { 8053 Web({ src: 'www.example.com', controller: this.controller }) 8054 .enableNativeMediaPlayer({enable: true, shouldOverlay: false}) 8055 .onPageBegin((event) => { 8056 this.controller.onCreateNativeMediaPlayer((handler: webview.NativeMediaPlayerHandler, mediaInfo: webview.MediaInfo) => { 8057 if (!shouldHandle(mediaInfo)) { 8058 // The local player does not take over the media. 8059 // The ArkWeb engine will play the media with its own player. 8060 return null; 8061 } 8062 let nativePlayer: webview.NativeMediaPlayerBridge = new NativeMediaPlayerImpl(handler, mediaInfo); 8063 return nativePlayer; 8064 }); 8065 }) 8066 } 8067 } 8068} 8069 8070// stub 8071function getVolume() { 8072 return 1; 8073} 8074function getCurrentPlayingTime() { 8075 return 1; 8076} 8077function getCurrentBufferedTime() { 8078 return 1; 8079} 8080function convertToSeconds(input: number) { 8081 return input; 8082} 8083function getLastReadyState() { 8084 return webview.ReadyState.HAVE_NOTHING; 8085} 8086function getCurrentReadyState() { 8087 return webview.ReadyState.HAVE_NOTHING; 8088} 8089function shouldHandle(mediaInfo: webview.MediaInfo) { 8090 return true; 8091} 8092``` 8093 8094### enableWholeWebPageDrawing<sup>12+</sup> 8095 8096static enableWholeWebPageDrawing(): void 8097 8098Enables the full drawing capability for the web page. This API works only during **Web** component initialization. 8099 8100**System capability**: SystemCapability.Web.Webview.Core 8101 8102**Example** 8103 8104```ts 8105// xxx.ets 8106import { webview } from '@kit.ArkWeb'; 8107import { BusinessError } from '@kit.BasicServicesKit'; 8108 8109@Entry 8110@Component 8111struct WebComponent { 8112 controller: webview.WebviewController = new webview.WebviewController(); 8113 8114 aboutToAppear(): void { 8115 try { 8116 webview.WebviewController.enableWholeWebPageDrawing(); 8117 } catch (error) { 8118 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8119 } 8120 } 8121 8122 build() { 8123 Column() { 8124 Web({ src: 'www.example.com', controller: this.controller }) 8125 } 8126 } 8127} 8128``` 8129 8130### webPageSnapshot<sup>12+</sup> 8131 8132webPageSnapshot(info: SnapshotInfo, callback: AsyncCallback\<SnapshotResult>): void 8133 8134Obtains the full drawing result of the web page. 8135 8136**System capability**: SystemCapability.Web.Webview.Core 8137 8138**Parameters** 8139 8140| Name | Type | Mandatory | Description | 8141| ----------- | ------------- | ---- | ------------------------ | 8142| info | [SnapshotInfo](#snapshotinfo12)| Yes | Information for obtaining the full drawing result.| 8143| callback | [SnapshotResult](#snapshotresult12)| Yes | Callback used to return the result.| 8144 8145**Example** 8146 8147```ts 8148// xxx.ets 8149import { webview } from '@kit.ArkWeb'; 8150import { BusinessError } from '@kit.BasicServicesKit'; 8151 8152@Entry 8153@Component 8154struct WebComponent { 8155 controller: webview.WebviewController = new webview.WebviewController(); 8156 8157 build() { 8158 Column() { 8159 Button('webPageSnapshot') 8160 .onClick(() => { 8161 try { 8162 this.controller.webPageSnapshot({ id: "1234", size: { width: 100, height: 100 } }, (error, result) => { 8163 if (error) { 8164 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8165 return; 8166 } 8167 if (result) { 8168 console.info(`return value is:${result}`); 8169 // You can process the returned result as required. 8170 } 8171 }); 8172 } catch (error) { 8173 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8174 } 8175 }) 8176 Web({ src: 'www.example.com', controller: this.controller }) 8177 } 8178 } 8179} 8180``` 8181 8182### injectOfflineResources<sup>12+</sup> 8183 8184injectOfflineResources(resourceMaps: Array\<[OfflineResourceMap](#offlineresourcemap12)\>): void 8185 8186Injects local offline resources to the memory cache to improve the initial page startup speed. 8187Resources 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. 8188Under 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. 8189The 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. 8190Resources injected in this mode can be loaded only through HTML tags. 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**. 8191After **webview.WebviewController.SetRenderProcessMode(webview.RenderProcessMode.MULTIPLE)** is called, the application starts the multi-rendering process mode. This API does not take effect in this scenario. 8192 8193**System capability**: SystemCapability.Web.Webview.Core 8194 8195**Parameters** 8196 8197| Name | Type | Mandatory| Description | 8198| ------- | ------ | ---- | :-------------------- | 8199| 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. | 8200 8201**Error codes** 8202 8203For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8204 8205| ID| Error Message | 8206| -------- | ------------------------------------------------------------ | 8207| 401 | Invalid input parameter.Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | 8208| 17100001 | Init error. The WebviewController must be associated with a Web component. | 8209| 17100002 | Invalid url. | 8210 8211**Example** 8212 8213When 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: 82141. Save **UIContext** to localStorage in **EntryAbility**. 8215 8216 ```ts 8217 // EntryAbility.ets 8218 import { UIAbility } from '@kit.AbilityKit'; 8219 import { window } from '@kit.ArkUI'; 8220 8221 const localStorage: LocalStorage = new LocalStorage('uiContext'); 8222 8223 export default class EntryAbility extends UIAbility { 8224 storage: LocalStorage = localStorage; 8225 8226 onWindowStageCreate(windowStage: window.WindowStage) { 8227 windowStage.loadContent('pages/Index', this.storage, (err, data) => { 8228 if (err.code) { 8229 return; 8230 } 8231 8232 this.storage.setOrCreate<UIContext>("uiContext", windowStage.getMainWindowSync().getUIContext()); 8233 }); 8234 } 8235 } 8236 ``` 8237 82382. Write the basic code required by the dynamic component. 8239 8240 ```ts 8241 // DynamicComponent.ets 8242 import { NodeController, BuilderNode, FrameNode, UIContext } from '@kit.ArkUI'; 8243 8244 export interface BuilderData { 8245 url: string; 8246 controller: WebviewController; 8247 } 8248 8249 const storage = LocalStorage.getShared(); 8250 8251 export class NodeControllerImpl extends NodeController { 8252 private rootNode: BuilderNode<BuilderData[]> | null = null; 8253 private wrappedBuilder: WrappedBuilder<BuilderData[]> | null = null; 8254 8255 constructor(wrappedBuilder: WrappedBuilder<BuilderData[]>) { 8256 super(); 8257 this.wrappedBuilder = wrappedBuilder; 8258 } 8259 8260 makeNode(): FrameNode | null { 8261 if (this.rootNode != null) { 8262 return this.rootNode.getFrameNode(); 8263 } 8264 return null; 8265 } 8266 8267 initWeb(url: string, controller: WebviewController) { 8268 if(this.rootNode != null) { 8269 return; 8270 } 8271 8272 const uiContext: UIContext = storage.get<UIContext>("uiContext") as UIContext; 8273 if (!uiContext) { 8274 return; 8275 } 8276 this.rootNode = new BuilderNode(uiContext); 8277 this.rootNode.build(this.wrappedBuilder, { url: url, controller: controller }); 8278 } 8279 } 8280 8281 export const createNode = (wrappedBuilder: WrappedBuilder<BuilderData[]>, data: BuilderData) => { 8282 const baseNode = new NodeControllerImpl(wrappedBuilder); 8283 baseNode.initWeb(data.url, data.controller); 8284 return baseNode; 8285 } 8286 ``` 8287 82883. 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. 8289 8290 <!--code_no_check--> 8291 ```ts 8292 // InjectWebview.ets 8293 import { webview } from '@kit.ArkWeb'; 8294 import { resourceConfigs } from "./Resource"; 8295 import { BuilderData } from "./DynamicComponent"; 8296 8297 @Builder 8298 function WebBuilder(data: BuilderData) { 8299 Web({ src: data.url, controller: data.controller }) 8300 .onControllerAttached(async () => { 8301 try { 8302 data.controller.injectOfflineResources(await getData ()); 8303 } catch (err) { 8304 console.error("error: " + err.code + " " + err.message); 8305 } 8306 }) 8307 .fileAccess(true) 8308 } 8309 8310 export const injectWebview = wrapBuilder<BuilderData[]>(WebBuilder); 8311 8312 export async function getData() { 8313 const resourceMapArr: Array<webview.OfflineResourceMap> = []; 8314 8315 // Read the configuration and read the file content from the rawfile directory. 8316 for (let config of resourceConfigs) { 8317 let buf: Uint8Array = new Uint8Array(0); 8318 if (config.localPath) { 8319 buf = await readRawFile(config.localPath); 8320 } 8321 8322 resourceMapArr.push({ 8323 urlList: config.urlList, 8324 resource: buf, 8325 responseHeaders: config.responseHeaders, 8326 type: config.type, 8327 }) 8328 } 8329 8330 return resourceMapArr; 8331 } 8332 8333 export async function readRawFile(url: string) { 8334 try { 8335 return await getContext().resourceManager.getRawFileContent(url); 8336 } catch (err) { 8337 return new Uint8Array(0); 8338 } 8339 } 8340 ``` 8341 83424. Compile the code of the service component. 8343 8344 <!--code_no_check--> 8345 ```ts 8346 // BusinessWebview.ets 8347 import { BuilderData } from "./DynamicComponent"; 8348 8349 @Builder 8350 function WebBuilder(data: BuilderData) { 8351 // The component can be extended based on service requirements. 8352 Web({ src: data.url, controller: data.controller }) 8353 .cacheMode(CacheMode.Default) 8354 } 8355 8356 export const businessWebview = wrapBuilder<BuilderData[]>(WebBuilder); 8357 ``` 8358 83595. Write the resource configuration information. 8360 8361 ```ts 8362 // Resource.ets 8363 import { webview } from '@kit.ArkWeb'; 8364 8365 export interface ResourceConfig { 8366 urlList: Array<string>, 8367 type: webview.OfflineResourceType, 8368 responseHeaders: Array<Header>, 8369 localPath: string, // Path for storing local resources in the rawfile directory. 8370 } 8371 8372 export const resourceConfigs: Array<ResourceConfig> = [ 8373 { 8374 localPath: "example.png", 8375 urlList: [ 8376 "https://www.example.com/", 8377 "https://www.example.com/path1/example.png", 8378 "https://www.example.com/path2/example.png", 8379 ], 8380 type: webview.OfflineResourceType.IMAGE, 8381 responseHeaders: [ 8382 { headerKey: "Cache-Control", headerValue: "max-age=1000" }, 8383 { headerKey: "Content-Type", headerValue: "image/png" }, 8384 ] 8385 }, 8386 { 8387 localPath: "example.js", 8388 urlList: [ // Only one URL is provided. This URL is used as both the resource origin and the network request address of the resource. 8389 "https://www.example.com/example.js", 8390 ], 8391 type: webview.OfflineResourceType.CLASSIC_JS, 8392 responseHeaders: [ 8393 // Used in <script crossorigin="anonymous" /> mode to provide additional response headers. 8394 { headerKey: "Cross-Origin", headerValue:"anonymous" } 8395 ] 8396 }, 8397 ]; 8398 ``` 8399 84006. Use the component on the page. 8401 <!--code_no_check--> 8402 ```ts 8403 // Index.ets 8404 import { webview } from '@kit.ArkWeb'; 8405 import { NodeController } from '@kit.ArkUI'; 8406 import { createNode } from "./DynamicComponent" 8407 import { injectWebview } from "./InjectWebview" 8408 import { businessWebview } from "./BusinessWebview" 8409 8410 @Entry 8411 @Component 8412 struct Index { 8413 @State injectNode: NodeController | undefined = undefined; 8414 injectController: webview.WebviewController = new webview.WebviewController(); 8415 8416 @State businessNode: NodeController | undefined = undefined; 8417 businessController: webview.WebviewController = new webview.WebviewController(); 8418 8419 aboutToAppear(): void { 8420 // Initialize the Web component used to inject local resources and provide an empty HTML page as the URL. 8421 this.injectNode = createNode(injectWebview, 8422 { url: "https://www.example.com/empty.html", controller: this.injectController}); 8423 } 8424 8425 build() { 8426 Column() { 8427 // Load the Web component used by the service at a proper time. In this example, the button is clicked. 8428 Button ("Load Page") 8429 .onClick(() => { 8430 this.businessNode = createNode(businessWebview, { 8431 url: "https://www.example.com/business.html", 8432 controller: this.businessController 8433 }); 8434 }) 8435 // The Web component used for the service. 8436 NodeContainer(this.businessNode); 8437 } 8438 } 8439 } 8440 ``` 8441 84427. Example of a loaded HTML web page: 8443 8444 ```HTML 8445 <!DOCTYPE html> 8446 <html lang="en"> 8447 <head></head> 8448 <body> 8449 <img src="https://www.example.com/path1/request.png" /> 8450 <img src="https://www.example.com/path2/request.png" /> 8451 <script src="https://www.example.com/example.js" crossorigin="anonymous"></script> 8452 </body> 8453 </html> 8454 ``` 8455 8456### setHostIP<sup>12+</sup> 8457 8458static setHostIP(hostName: string, address: string, aliveTime: number): void 8459 8460Sets the IP address of the host after domain name resolution. 8461 8462**System capability**: SystemCapability.Web.Webview.Core 8463 8464**Parameters** 8465 8466| Name | Type| Mandatory| Description | 8467| --------- | -------- | ---- | ------------------------------------ | 8468| hostName | string | Yes | Domain name of the host whose DNS records are to be added. | 8469| address | string | Yes | Host domain name resolution address (IPv4 and IPv6).| 8470| aliveTime | number | Yes | Cache validity period, in seconds. | 8471 8472**Error codes** 8473 8474For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8475 8476| ID| Error Message | 8477| -------- | ------------------------ | 8478| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | 8479 8480**Example** 8481 8482For details, see [clearHostIP](#clearhostip12). 8483 8484### clearHostIP<sup>12+</sup> 8485 8486static clearHostIP(hostName: string): void 8487 8488Clears the IP address of a specified host after domain name resolution. 8489 8490**System capability**: SystemCapability.Web.Webview.Core 8491 8492**Parameters** 8493 8494| Name | Type| Mandatory| Description | 8495| -------- | -------- | ---- | ------------------------- | 8496| hostName | string | Yes | Domain name of the host whose DNS records are to be cleared.| 8497 8498**Error codes** 8499 8500For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8501 8502| ID| Error Message | 8503| -------- | ------------------------ | 8504| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | 8505 8506**Example** 8507 8508```ts 8509// xxx.ets 8510import { webview } from '@kit.ArkWeb'; 8511import { BusinessError } from '@kit.BasicServicesKit'; 8512 8513@Entry 8514@Component 8515struct WebComponent { 8516 controller: webview.WebviewController = new webview.WebviewController(); 8517 8518 build() { 8519 Column() { 8520 // The setting takes effect before the URL is loaded. 8521 Button('setHostIP') 8522 .onClick(() => { 8523 try { 8524 webview.WebviewController.setHostIP('www.example.com', '127.0.0.1', 30); 8525 } catch (error) { 8526 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8527 } 8528 }) 8529 Button('clearHostIP') 8530 .onClick(() => { 8531 try { 8532 webview.WebviewController.clearHostIP('www.example.com'); 8533 } catch (error) { 8534 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8535 } 8536 }) 8537 Web({ src: 'www.example.com', controller: this.controller }) 8538 } 8539 } 8540} 8541``` 8542 8543### getSurfaceId<sup>12+</sup> 8544 8545getSurfaceId(): string 8546 8547Obtains 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. 8548 8549**System capability**: SystemCapability.Web.Webview.Core 8550 8551**Return value** 8552 8553| Type | Description | 8554| ------ | ------------------- | 8555| string | ID of the surface held by ArkWeb.| 8556 8557**Example** 8558 8559```ts 8560// xxx.ets 8561import { webview } from '@kit.ArkWeb'; 8562import { image } from '@kit.ImageKit'; 8563import { BusinessError } from '@kit.BasicServicesKit'; 8564 8565@Entry 8566@Component 8567struct Example{ 8568 controller: webview.WebviewController = new webview.WebviewController(); 8569 8570 @State imagePixelMap: image.PixelMap | undefined = undefined; 8571 8572 build(){ 8573 Column(){ 8574 Button ("Screenshot") 8575 .onClick(()=>{ 8576 try { 8577 let surfaceId = this.controller.getSurfaceId(); 8578 console.log("surfaceId: " + surfaceId); 8579 if(surfaceId.length != 0) { 8580 let region:image.Region = { x: 0, y: 0, size: { height: 800, width: 1000}} 8581 this.imagePixelMap = image.createPixelMapFromSurfaceSync(surfaceId, region) 8582 } 8583 } catch (error) { 8584 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8585 } 8586 }) 8587 Image(this.imagePixelMap) 8588 .height(100) 8589 Web({src: 'www.example.com', controller: this.controller}) 8590 } 8591 } 8592} 8593``` 8594 8595### setUrlTrustList<sup>12+</sup> 8596 8597setUrlTrustList(urlTrustList: string): void 8598 8599Sets 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. 8600 8601**System capability**: SystemCapability.Web.Webview.Core 8602 8603**Parameters** 8604 8605| Name | Type | Mandatory| Description | 8606| ------- | ------ | ---- | :-------------------- | 8607| 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>} | 8608 8609**Parameters in JSON format**: 8610| Name | Type| Mandatory| Description | 8611| -------- | -------- | ---- | ------------------------- | 8612| scheme | string | No| Optional parameter. The supported protocols are HTTP and HTTPS.| 8613| 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.| 8614| port | number | No| Optional parameter.| 8615| 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.| 8616 8617**Error codes** 8618 8619For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8620 8621| ID| Error Message | 8622| -------- | ------------------------------------------------------------ | 8623| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified.2. Parameter string is too long.3. Parameter verification failed. | 8624| 17100001 | Init error. The WebviewController must be associated with a Web component. | 8625 8626**Example** 8627 ```ts 8628 // xxx.ets 8629 import { webview } from '@kit.ArkWeb'; 8630 import { BusinessError } from '@kit.BasicServicesKit'; 8631 8632 @Entry 8633 @Component 8634 struct WebComponent { 8635 controller: webview.WebviewController = new webview.WebviewController(); 8636 urltrustList: string = "{\"UrlPermissionList\":[{\"scheme\":\"http\", \"host\":\"trust.example.com\", \"port\":80, \"path\":\"test\"}]}" 8637 8638 build() { 8639 Column() { 8640 Button('Setting the trustlist') 8641 .onClick(() => { 8642 try { 8643 // Set a trustlist to allow access only to trust web pages. 8644 this.controller.setUrlTrustList(this.urltrustList); 8645 } catch (error) { 8646 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8647 } 8648 }) 8649 Button('Cancel the trustlist.') 8650 .onClick(() => { 8651 try { 8652 // Input an empty string to setUrlTrustList() to disable the trustlist, and all URLs can be accessed. 8653 this.controller.setUrlTrustList(""); 8654 } catch (error) { 8655 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8656 } 8657 }) 8658 Button('Access the trust web') 8659 .onClick(() => { 8660 try { 8661 // The trustlist is enabled and trust web pages can be accessed. 8662 this.controller.loadUrl('http://trust.example.com/test'); 8663 } catch (error) { 8664 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8665 } 8666 }) 8667 Button('Access the untrust web') 8668 .onClick(() => { 8669 try { 8670 // The trustlist is enabled that untrust web pages cannot be accessed and an error page is displayed. 8671 this.controller.loadUrl('http://untrust.example.com/test'); 8672 } catch (error) { 8673 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8674 } 8675 }) 8676 Web({ src: 'http://untrust.example.com/test', controller: this.controller }).onControllerAttached(() => { 8677 try { 8678 // 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. 8679 this.controller.setUrlTrustList(this.urltrustList); 8680 } catch (error) { 8681 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8682 } 8683 }) 8684 } 8685 } 8686 } 8687 ``` 8688 8689### setPathAllowingUniversalAccess<sup>12+</sup> 8690 8691setPathAllowingUniversalAccess(pathList: Array\<string\>): void 8692 8693Sets a path list. When a file protocol accesses resources in the path 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: 8694 86951. 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: 8696 8697* /data/storage/el2/base/files/example 8698* /data/storage/el2/base/haps/entry/files/example 8699 87002. 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: 8701 8702* /data/storage/el1/bundle/entry/resource/resfile 8703* /data/storage/el1/bundle/entry/resource/resfile/example 8704 8705If a path in the list is not 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). 8706 8707**System capability**: SystemCapability.Web.Webview.Core 8708 8709**Parameters** 8710 8711| Name | Type| Mandatory| Description | 8712| -------- | -------- | ---- | ------------------------- | 8713| pathList | Array\<string\> | Yes | The path list.| 8714 8715**Error codes** 8716 8717For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8718 8719| ID| Error Message | 8720| -------- | ------------------------ | 8721| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Parameter string is too long. 3.Parameter verification failed. | 8722| 17100001 | Init error. The WebviewController must be associated with a Web component. | 8723 8724**Example** 8725 8726```ts 8727// xxx.ets 8728import { webview } from '@kit.ArkWeb'; 8729import { BusinessError } from '@kit.BasicServicesKit'; 8730 8731@Entry 8732@Component 8733struct WebComponent { 8734 controller: WebviewController = new webview.WebviewController(); 8735 8736 build() { 8737 Row() { 8738 Web({ src: "", controller: this.controller }) 8739 .onControllerAttached(() => { 8740 try { 8741 // Set the list of paths that can be accessed across domains. 8742 this.controller.setPathAllowingUniversalAccess([ 8743 getContext().resourceDir, 8744 getContext().filesDir + "/example" 8745 ]) 8746 this.controller.loadUrl("file://" + getContext().resourceDir + "/index.html") 8747 } catch (error) { 8748 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8749 } 8750 }) 8751 .javaScriptAccess(true) 8752 .fileAccess(true) 8753 .domStorageAccess(true) 8754 } 8755 } 8756} 8757 8758``` 8759 8760Load the HTML file in the application resource directory **resource/resfile/index.html**. 8761```html 8762<!-- index.html --> 8763<!DOCTYPE html> 8764<html lang="en"> 8765 8766<head> 8767 <meta charset="utf-8"> 8768 <title>Demo</title> 8769 <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, viewport-fit=cover"> 8770 <script> 8771 function getFile() { 8772 var file = "file:///data/storage/el1/bundle/entry/resources/resfile/js/script.js"; 8773 var xmlHttpReq = new XMLHttpRequest(); 8774 xmlHttpReq.onreadystatechange = function(){ 8775 console.log("readyState:" + xmlHttpReq.readyState); 8776 console.log("status:" + xmlHttpReq.status); 8777 if(xmlHttpReq.readyState == 4){ 8778 if (xmlHttpReq.status == 200) { 8779 // If the path list is set on the eTS, resources can be obtained. 8780 const element = document.getElementById('text'); 8781 element.textContent = "load " + file + " success"; 8782 } else { 8783 // If the path list is not set on the eTS, a CORS error is triggered. 8784 const element = document.getElementById('text'); 8785 element.textContent = "load " + file + " failed"; 8786 } 8787 } 8788 } 8789 xmlHttpReq.open("GET", file); 8790 xmlHttpReq.send(null); 8791 } 8792 8793 </script> 8794</head> 8795 8796<body> 8797<div class="page"> 8798 <button id="example" onclick="getFile()">stealFile</button> 8799</div> 8800<div id="text"></div> 8801</body> 8802 8803</html> 8804``` 8805 8806In the HTML file, use the file protocol to access the local JS file through **XMLHttpRequest**. The JS file is stored in **resource/rawfile/js/script.js**. 8807<!--code_no_check--> 8808```javascript 8809const body = document.body; 8810const element = document.createElement('div'); 8811element.textContent = 'success'; 8812body.appendChild(element); 8813``` 8814 8815### enableBackForwardCache<sup>12+</sup> 8816 8817static enableBackForwardCache(features: BackForwardCacheSupportedFeatures): void 8818 8819Enables the back-forward cache of a **Web** component. You can specify whether to add a specific page to the back-forward cache. 8820 8821This API must be called before [initializeWebEngine()](#initializewebengine) initializes the kernel. 8822 8823**System capability**: SystemCapability.Web.Webview.Core 8824 8825**Parameters** 8826 8827| Name | Type | Mandatory | Description | 8828| ---------------| ------- | ---- | ------------- | 8829| features | [BackForwardCacheSupportedFeatures](#backforwardcachesupportedfeatures12) | Yes | Features of the pages, which allow them to be added to the back-forward cache.| 8830 8831**Example** 8832 8833```ts 8834// EntryAbility.ets 8835import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 8836import { hilog } from '@kit.PerformanceAnalysisKit'; 8837import { window } from '@kit.ArkUI'; 8838import { webview } from '@kit.ArkWeb'; 8839 8840export default class EntryAbility extends UIAbility { 8841 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 8842 let features = new webview.BackForwardCacheSupportedFeatures(); 8843 features.nativeEmbed = true; 8844 features.mediaTakeOver = true; 8845 // 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. 8846 8847 webview.WebviewController.enableBackForwardCache(features); 8848 webview.WebviewController.initializeWebEngine(); 8849 AppStorage.setOrCreate("abilityWant", want); 8850 } 8851} 8852``` 8853 8854### setBackForwardCacheOptions<sup>12+</sup> 8855 8856setBackForwardCacheOptions(options: BackForwardCacheOptions): void 8857 8858Sets the back-forward cache options of the **Web** component. 8859 8860**System capability**: SystemCapability.Web.Webview.Core 8861 8862**Parameters** 8863 8864| Name | Type | Mandatory | Description | 8865| ---------------| ------- | ---- | ------------- | 8866| options | [BackForwardCacheOptions](#backforwardcacheoptions12) | Yes | Options to control the back-forward cache of the **Web** component.| 8867 8868**Error codes** 8869 8870For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8871 8872| ID| Error Message | 8873| -------- | ------------------------------------------------------------ | 8874| 17100001 | Init error. The WebviewController must be associated with a Web component. | 8875 8876**Example** 8877 8878```ts 8879// xxx.ts 8880import { webview } from '@kit.ArkWeb'; 8881 8882@Entry 8883@Component 8884struct Index { 8885 controller: webview.WebviewController = new webview.WebviewController(); 8886 8887 build() { 8888 Column() { 8889 Row() { 8890 Button("Add options").onClick((event: ClickEvent) => { 8891 let options = new webview.BackForwardCacheOptions(); 8892 options.size = 3; 8893 options.timeToLive = 10; 8894 this.controller.setBackForwardCacheOptions(options); 8895 }) 8896 Button("Backward").onClick((event: ClickEvent) => { 8897 this.controller.backward(); 8898 }) 8899 Button("Forward").onClick((event: ClickEvent) => { 8900 this.controller.forward(); 8901 }) 8902 } 8903 Web({ src: "https://www.example.com", controller: this.controller }) 8904 } 8905 .height('100%') 8906 .width('100%') 8907 } 8908} 8909``` 8910 8911### trimMemoryByPressureLevel<sup>14+</sup> 8912 8913trimMemoryByPressureLevel(level: PressureLevel): void 8914 8915Clears the cache occupied by **Web** component based on the specified memory pressure level. 8916 8917**System capability**: SystemCapability.Web.Webview.Core 8918 8919**Parameters** 8920 8921| Name | Type | Mandatory| Description | 8922| ------- | ------ | ---- | :-------------------- | 8923| level | [PressureLevel](#pressurelevel14) | Yes| Pressure level of the memory to be cleared.| 8924 8925**Error codes** 8926 8927For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8928 8929| ID| Error Message | 8930| -------- | ------------------------------------------------------------ | 8931| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Parameter string is too long. 3.Parameter verification failed. | 8932 8933**Example** 8934```ts 8935// xxx.ets 8936import { webview } from '@kit.ArkWeb'; 8937import { BusinessError } from '@kit.BasicServicesKit'; 8938 8939@Entry 8940@Component 8941struct WebComponent { 8942 controller: WebviewController = new webview.WebviewController(); 8943 build() { 8944 Column() { 8945 Row() { 8946 Button('trim_Memory') 8947 .onClick(() => { 8948 try { 8949 // Set the current memory pressure level to moderate and release a small amount of memory. 8950 webview.WebviewController.trimMemoryByPressureLevel( 8951 webview.PressureLevel.MEMORY_PRESSURE_LEVEL_MODERATE); 8952 } catch (error) { 8953 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8954 } 8955 }) 8956 }.height('10%') 8957 Web({ src: 'www.example.com', controller: this.controller }) 8958 } 8959 } 8960} 8961``` 8962 8963### createPdf<sup>14+</sup> 8964 8965createPdf(configuration: PdfConfiguration, callback: AsyncCallback\<PdfData\>): void 8966 8967Obtains the data stream of a specified web page using an asynchronous callback. 8968 8969**System capability**: SystemCapability.Web.Webview.Core 8970 8971**Parameters** 8972 8973| Name | Type | Mandatory| Description | 8974| ------------- | --------------------------------------- | ---- | ----------------------- | 8975| configuration | [PdfConfiguration](#pdfconfiguration14) | Yes | Parameters required for creating a PDF file. | 8976| callback | AsyncCallback<[PdfData](#pdfdata14)> | Yes | Callback used to return the data stream of an online PDF file.| 8977 8978**Error codes** 8979 8980For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8981 8982| ID| Error Message | 8983| -------- | ------------------------------------------------------------ | 8984| 401 | Invalid input parameter. | 8985| 17100001 | Init error. The WebviewController must be associated with a Web component. | 8986 8987**Example** 8988 8989```ts 8990import { fileIo as fs } from '@kit.CoreFileKit'; 8991import { webview } from '@kit.ArkWeb'; 8992import { BusinessError } from '@kit.BasicServicesKit'; 8993import { common } from '@kit.AbilityKit'; 8994 8995@Entry 8996@Component 8997struct Index { 8998 controller: webview.WebviewController = new webview.WebviewController(); 8999 pdfConfig: webview.PdfConfiguration = { 9000 width: 8.27, 9001 height: 11.69, 9002 marginTop: 0, 9003 marginBottom: 0, 9004 marginRight: 0, 9005 marginLeft: 0, 9006 shouldPrintBackground: true 9007 } 9008 9009 build() { 9010 Column() { 9011 Button('SavePDF') 9012 .onClick(() => { 9013 this.controller.createPdf( 9014 this.pdfConfig, 9015 (error, result: webview.PdfData) => { 9016 try { 9017 // Obtain the component context. 9018 let context = getContext(this) as common.UIAbilityContext; 9019 // Obtain the sandbox path and set the PDF file name. 9020 let filePath = context.filesDir + "/test.pdf"; 9021 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 9022 fs.write(file.fd, result.pdfArrayBuffer().buffer).then((writeLen: number) => { 9023 console.info("createPDF write data to file succeed and size is:" + writeLen); 9024 }).catch((err: BusinessError) => { 9025 console.error("createPDF write data to file failed with error message: " + err.message + 9026 ", error code: " + err.code); 9027 }).finally(() => { 9028 fs.closeSync(file); 9029 }); 9030 } catch (resError) { 9031 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9032 } 9033 }); 9034 }) 9035 Web({ src: "www.example.com", controller: this.controller }) 9036 } 9037 } 9038} 9039``` 9040 9041### createPdf<sup>14+</sup> 9042 9043createPdf(configuration: PdfConfiguration): Promise\<PdfData\> 9044 9045Obtains the data stream of a specified web page using a promise. 9046 9047**System capability**: SystemCapability.Web.Webview.Core 9048 9049**Parameters** 9050 9051| Name | Type | Mandatory| Description | 9052| ------------- | --------------------------------------- | ---- | ----------------- | 9053| configuration | [PdfConfiguration](#pdfconfiguration14) | Yes | Parameters required for creating a PDF file.| 9054 9055**Return value** 9056 9057| Type | Description | 9058| ------------------------------ | ----------------------------- | 9059| Promise<[PdfData](#pdfdata14)> | Promise used to return the data stream of a web page.| 9060 9061**Error codes** 9062 9063For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9064 9065| ID| Error Message | 9066| -------- | ------------------------------------------------------------ | 9067| 401 | Invalid input parameter. | 9068| 17100001 | Init error. The WebviewController must be associated with a Web component. | 9069 9070**Example** 9071 9072```ts 9073import { fileIo as fs } from '@kit.CoreFileKit'; 9074import { webview } from '@kit.ArkWeb'; 9075import { BusinessError } from '@kit.BasicServicesKit'; 9076import { common } from '@kit.AbilityKit'; 9077 9078@Entry 9079@Component 9080struct Index { 9081 controller: webview.WebviewController = new webview.WebviewController(); 9082 pdfConfig: webview.PdfConfiguration = { 9083 width: 8.27, 9084 height: 11.69, 9085 marginTop: 0, 9086 marginBottom: 0, 9087 marginRight: 0, 9088 marginLeft: 0, 9089 shouldPrintBackground: true 9090 } 9091 9092 build() { 9093 Column() { 9094 Button('SavePDF') 9095 .onClick(() => { 9096 this.controller.createPdf(this.pdfConfig) 9097 .then((result: webview.PdfData) => { 9098 try { 9099 // Obtain the component context. 9100 let context = getContext(this) as common.UIAbilityContext; 9101 // Obtain the sandbox path and set the PDF file name. 9102 let filePath = context.filesDir + "/test.pdf"; 9103 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 9104 fs.write(file.fd, result.pdfArrayBuffer().buffer).then((writeLen: number) => { 9105 console.info("createPDF write data to file succeed and size is:" + writeLen); 9106 }).catch((err: BusinessError) => { 9107 console.error("createPDF write data to file failed with error message: " + err.message + 9108 ", error code: " + err.code); 9109 }).finally(() => { 9110 fs.closeSync(file); 9111 }); 9112 } catch (resError) { 9113 console.error(`ErrorCode: ${(resError as BusinessError).code}, Message: ${(resError as BusinessError).message}`); 9114 } 9115 }) 9116 }) 9117 Web({ src: "www.example.com", controller: this.controller }) 9118 } 9119 } 9120} 9121``` 9122 9123### getScrollOffset<sup>13+</sup> 9124 9125getScrollOffset(): ScrollOffset 9126 9127Obtains the current scrolling offset of a web page. 9128 9129**System capability**: SystemCapability.Web.Webview.Core 9130 9131**Return value** 9132 9133| Type | Description | 9134| :------------------------------ | ---------------------- | 9135| [ScrollOffset](#scrolloffset13) | Current scrolling offset of the web page.| 9136 9137**Example** 9138 9139```ts 9140import { webview } from '@kit.ArkWeb'; 9141import { componentUtils } from '@kit.ArkUI'; 9142 9143@Entry 9144@Component 9145struct WebComponent { 9146 @State testTitle: string = 'webScroll' 9147 controller: webview.WebviewController = new webview.WebviewController(); 9148 @State controllerX: number =-100; 9149 @State controllerY: number =-100; 9150 @State mode: OverScrollMode = OverScrollMode.ALWAYS; 9151 9152 build() { 9153 Column() { 9154 Row() { 9155 Text(this.testTitle) 9156 .fontSize(30) 9157 .fontWeight(FontWeight.Bold) 9158 .margin(5) 9159 } 9160 Column() { 9161 Text(`controllerX: ${this.controllerX}, controllerY: ${this.controllerY}`) 9162 } 9163 .margin({ top: 10, bottom: 10 }) 9164 Web({ src: $rawfile("scrollByTo.html"), controller: this.controller }) 9165 .key("web_01") 9166 .overScrollMode(this.mode) 9167 .onTouch((event) => { 9168 this.controllerX = this.controller.getScrollOffset().x; 9169 this.controllerY = this.controller.getScrollOffset().y; 9170 let componentInfo = componentUtils.getRectangleById("web_01"); 9171 let webHeight = px2vp(componentInfo.size.height); 9172 let pageHeight = this.controller.getPageHeight(); 9173 if (this.controllerY < 0) { 9174 // Case 1: When a web page is scrolled down, use ScrollOffset.y directly. 9175 console.log(`get downwards overscroll offsetY = ${this.controllerY}`); 9176 } else if ((this.controllerY != 0) && (this.controllerY > (pageHeight - webHeight))) { 9177 // Case 2: When a web page is scrolled up, calculate the offset between the lower boundary of the web page and that of the Web component. 9178 console.log(`get upwards overscroll offsetY = ${this.controllerY - (pageHeight >= webHeight ? (pageHeight - webHeight) : 0)}`); 9179 } else { 9180 // Case 3: If the web page is not scrolled, use ScrollOffset.y directly. 9181 console.log(`get scroll offsetY = ${this.controllerY}`); 9182 } 9183 }) 9184 .height(600) 9185 } 9186 .width('100%') 9187 .height('100%') 9188 } 9189} 9190``` 9191 9192### getLastHitTest<sup>18+</sup> 9193 9194getLastHitTest(): HitTestValue 9195 9196Obtains the element information of the area being clicked last time. 9197 9198**System capability**: SystemCapability.Web.Webview.Core 9199 9200**Return value** 9201 9202| Type | Description | 9203| ------------ | -------------------- | 9204| [HitTestValue](#hittestvalue) | Element information of the area being clicked.| 9205 9206**Error codes** 9207 9208For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9209 9210| ID| Error Message | 9211| -------- | ------------------------------------------------------------ | 9212| 17100001 | Init error. The WebviewController must be associated with a Web component. | 9213 9214**Example** 9215 9216```ts 9217// xxx.ets 9218import { webview } from '@kit.ArkWeb'; 9219import { BusinessError } from '@kit.BasicServicesKit'; 9220 9221@Entry 9222@Component 9223struct WebComponent { 9224 controller: webview.WebviewController = new webview.WebviewController(); 9225 9226 build() { 9227 Column() { 9228 Button('getLastHitTest') 9229 .onClick(() => { 9230 try { 9231 let hitValue = this.controller.getLastHitTest(); 9232 console.log("hitType: " + hitValue.type); 9233 console.log("extra: " + hitValue.extra); 9234 } catch (error) { 9235 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9236 } 9237 }) 9238 Web({ src: 'www.example.com', controller: this.controller }) 9239 } 9240 } 9241} 9242``` 9243 9244## WebCookieManager 9245 9246Implements a **WebCookieManager** instance to manage behavior of cookies in **Web** components. All **Web** components in an application share a **WebCookieManager** instance. 9247 9248### getCookie<sup>(deprecated)</sup> 9249 9250static getCookie(url: string): string 9251 9252Obtains the cookie value of the specified URL. 9253 9254> **NOTE** 9255> 9256> This API is supported since API version 9 and deprecated since API version 11. You are advised to use [fetchCookieSync](#fetchcookiesync11) instead. 9257 9258**System capability**: SystemCapability.Web.Webview.Core 9259 9260**Parameters** 9261 9262| Name| Type | Mandatory| Description | 9263| ------ | ------ | ---- | :------------------------ | 9264| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 9265 9266**Return value** 9267 9268| Type | Description | 9269| ------ | ------------------------- | 9270| string | Cookie value corresponding to the specified URL.| 9271 9272**Error codes** 9273 9274For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9275 9276| ID| Error Message | 9277| -------- | ------------------------------------------------------ | 9278| 17100002 | Invalid url. | 9279| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 9280 9281**Example** 9282 9283```ts 9284// xxx.ets 9285import { webview } from '@kit.ArkWeb'; 9286import { BusinessError } from '@kit.BasicServicesKit'; 9287 9288@Entry 9289@Component 9290struct WebComponent { 9291 controller: webview.WebviewController = new webview.WebviewController(); 9292 9293 build() { 9294 Column() { 9295 Button('getCookie') 9296 .onClick(() => { 9297 try { 9298 let value = webview.WebCookieManager.getCookie('https://www.example.com'); 9299 console.log("value: " + value); 9300 } catch (error) { 9301 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9302 } 9303 }) 9304 Web({ src: 'www.example.com', controller: this.controller }) 9305 } 9306 } 9307} 9308``` 9309 9310### fetchCookieSync<sup>11+</sup> 9311 9312static fetchCookieSync(url: string, incognito?: boolean): string 9313 9314Obtains the cookie value of the specified URL. 9315 9316> **NOTE** 9317> 9318> The system automatically deletes expired cookies. For data with the same key name, the new data overwrites the previous data. 9319> 9320> To obtain the cookie value that can be used, pass a complete link to **fetchCookieSync()**. 9321> 9322> **fetchCookieSync()** is used to obtain all cookie values. Cookie values are separated by semicolons (;). However, a specific cookie value cannot be obtained separately. 9323 9324**System capability**: SystemCapability.Web.Webview.Core 9325 9326**Parameters** 9327 9328| Name| Type | Mandatory| Description | 9329| ------ | ------ | ---- | :------------------------ | 9330| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 9331| 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.| 9332 9333**Return value** 9334 9335| Type | Description | 9336| ------ | ------------------------- | 9337| string | Cookie value corresponding to the specified URL.| 9338 9339**Error codes** 9340 9341For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9342 9343| ID| Error Message | 9344| -------- | ------------------------------------------------------ | 9345| 17100002 | Invalid url. | 9346| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9347 9348**Example** 9349 9350```ts 9351// xxx.ets 9352import { webview } from '@kit.ArkWeb'; 9353import { BusinessError } from '@kit.BasicServicesKit'; 9354 9355@Entry 9356@Component 9357struct WebComponent { 9358 controller: webview.WebviewController = new webview.WebviewController(); 9359 9360 build() { 9361 Column() { 9362 Button('fetchCookieSync') 9363 .onClick(() => { 9364 try { 9365 let value = webview.WebCookieManager.fetchCookieSync('https://www.example.com'); 9366 console.log("fetchCookieSync cookie = " + value); 9367 } catch (error) { 9368 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9369 } 9370 }) 9371 Web({ src: 'www.example.com', controller: this.controller }) 9372 } 9373 } 9374} 9375``` 9376 9377### fetchCookie<sup>11+</sup> 9378 9379static fetchCookie(url: string, callback: AsyncCallback\<string>): void 9380 9381Obtains the cookie value of a specified URL. This API uses an asynchronous callback to return the result. 9382 9383**System capability**: SystemCapability.Web.Webview.Core 9384 9385**Parameters** 9386 9387| Name| Type | Mandatory| Description | 9388| ------ | ------ | ---- | :------------------------ | 9389| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 9390| callback | AsyncCallback\<string> | Yes| Callback used to return the result.| 9391 9392**Error codes** 9393 9394For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9395 9396| ID| Error Message | 9397| -------- | ------------------------------------------------------ | 9398| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9399| 17100002 | Invalid url. | 9400 9401**Example** 9402 9403```ts 9404// xxx.ets 9405import { webview } from '@kit.ArkWeb'; 9406import { BusinessError } from '@kit.BasicServicesKit'; 9407 9408@Entry 9409@Component 9410struct WebComponent { 9411 controller: webview.WebviewController = new webview.WebviewController(); 9412 9413 build() { 9414 Column() { 9415 Button('fetchCookie') 9416 .onClick(() => { 9417 try { 9418 webview.WebCookieManager.fetchCookie('https://www.example.com', (error, cookie) => { 9419 if (error) { 9420 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9421 return; 9422 } 9423 if (cookie) { 9424 console.log('fetchCookie cookie = ' + cookie); 9425 } 9426 }) 9427 } catch (error) { 9428 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9429 } 9430 }) 9431 Web({ src: 'www.example.com', controller: this.controller }) 9432 } 9433 } 9434} 9435``` 9436 9437### fetchCookie<sup>11+</sup> 9438 9439static fetchCookie(url: string): Promise\<string> 9440 9441Obtains the cookie value of a specified URL. This API uses a promise to return the result. 9442 9443**System capability**: SystemCapability.Web.Webview.Core 9444 9445**Parameters** 9446 9447| Name| Type | Mandatory| Description | 9448| ------ | ------ | ---- | :------------------------ | 9449| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 9450 9451**Return value** 9452 9453| Type | Description | 9454| ------ | ------------------------- | 9455| Promise\<string> | Promise used to return the result.| 9456 9457**Error codes** 9458 9459For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9460 9461| ID| Error Message | 9462| -------- | ------------------------------------------------------ | 9463| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9464| 17100002 | Invalid url. | 9465 9466**Example** 9467 9468```ts 9469// xxx.ets 9470import { webview } from '@kit.ArkWeb'; 9471import { BusinessError } from '@kit.BasicServicesKit'; 9472 9473@Entry 9474@Component 9475struct WebComponent { 9476 controller: webview.WebviewController = new webview.WebviewController(); 9477 9478 build() { 9479 Column() { 9480 Button('fetchCookie') 9481 .onClick(() => { 9482 try { 9483 webview.WebCookieManager.fetchCookie('https://www.example.com') 9484 .then(cookie => { 9485 console.log("fetchCookie cookie = " + cookie); 9486 }) 9487 .catch((error: BusinessError) => { 9488 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 9489 }) 9490 } catch (error) { 9491 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9492 } 9493 }) 9494 Web({ src: 'www.example.com', controller: this.controller }) 9495 } 9496 } 9497} 9498``` 9499 9500### fetchCookie<sup>14+</sup> 9501 9502static fetchCookie(url: string, incognito: boolean): Promise\<string> 9503 9504Obtains the cookie value of a specified URL. This API uses a promise to return the result. 9505 9506**System capability**: SystemCapability.Web.Webview.Core 9507 9508**Parameters** 9509 9510| Name| Type | Mandatory| Description | 9511| ------ | ------ | ---- | :------------------------ | 9512| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 9513| incognito | boolean | Yes | Whether to obtain the cookie in incognito mode. The value **true** means to obtain the cookie in incognito mode, and **false** means the opposite.| 9514 9515**Return value** 9516 9517| Type | Description | 9518| ------ | ------------------------- | 9519| Promise\<string> | Promise used to return the result.| 9520 9521**Error codes** 9522 9523For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9524 9525| ID| Error Message | 9526| -------- | ------------------------------------------------------ | 9527| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9528| 17100002 | Invalid url. | 9529 9530**Example** 9531 9532```ts 9533// xxx.ets 9534import { webview } from '@kit.ArkWeb'; 9535import { BusinessError } from '@kit.BasicServicesKit'; 9536 9537@Entry 9538@Component 9539struct WebComponent { 9540 controller: webview.WebviewController = new webview.WebviewController(); 9541 9542 build() { 9543 Column() { 9544 Button('fetchCookie') 9545 .onClick(() => { 9546 try { 9547 webview.WebCookieManager.fetchCookie('https://www.example.com', false) 9548 .then(cookie => { 9549 console.log("fetchCookie cookie = " + cookie); 9550 }) 9551 .catch((error: BusinessError) => { 9552 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 9553 }) 9554 } catch (error) { 9555 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9556 } 9557 }) 9558 Web({ src: 'www.example.com', controller: this.controller }) 9559 } 9560 } 9561} 9562``` 9563 9564### setCookie<sup>(deprecated)</sup> 9565 9566static setCookie(url: string, value: string): void 9567 9568Sets a cookie for the specified URL. 9569 9570> **NOTE** 9571> 9572> 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. 9573 9574**System capability**: SystemCapability.Web.Webview.Core 9575 9576**Parameters** 9577 9578| Name| Type | Mandatory| Description | 9579| ------ | ------ | ---- | :------------------------ | 9580| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 9581| value | string | Yes | Cookie value to set. | 9582 9583**Error codes** 9584 9585For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9586 9587| ID| Error Message | 9588| -------- | ------------------------------------------------------ | 9589| 17100002 | Invalid url. | 9590| 17100005 | Invalid cookie value. | 9591| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9592 9593**Example** 9594 9595```ts 9596// xxx.ets 9597import { webview } from '@kit.ArkWeb'; 9598import { BusinessError } from '@kit.BasicServicesKit'; 9599 9600@Entry 9601@Component 9602struct WebComponent { 9603 controller: webview.WebviewController = new webview.WebviewController(); 9604 9605 build() { 9606 Column() { 9607 Button('setCookie') 9608 .onClick(() => { 9609 try { 9610 webview.WebCookieManager.setCookie('https://www.example.com', 'a=b'); 9611 } catch (error) { 9612 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9613 } 9614 }) 9615 Web({ src: 'www.example.com', controller: this.controller }) 9616 } 9617 } 9618} 9619``` 9620 9621### configCookieSync<sup>11+</sup> 9622 9623static configCookieSync(url: string, value: string, incognito?: boolean): void 9624 9625Sets a cookie for the specified URL. 9626 9627> **NOTE** 9628> 9629> You can set **url** in **configCookieSync** to a domain name so that the cookie is attached to the requests on the page. 9630> 9631> It is recommended that cookie syncing be completed before the **Web** component is loaded. 9632> 9633> If **configCookieSync()** is used to set cookies for two or more times, the cookies set each time are separated by semicolons (;). 9634 9635**System capability**: SystemCapability.Web.Webview.Core 9636 9637**Parameters** 9638 9639| Name| Type | Mandatory| Description | 9640| ------ | ------ | ---- | :------------------------ | 9641| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 9642| value | string | Yes | Cookie value to set. | 9643| 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.| 9644 9645**Error codes** 9646 9647For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9648 9649| ID| Error Message | 9650| -------- | ------------------------------------------------------ | 9651| 17100002 | Invalid url. | 9652| 17100005 | Invalid cookie value. | 9653| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9654 9655**Example** 9656 9657```ts 9658// xxx.ets 9659import { webview } from '@kit.ArkWeb'; 9660import { BusinessError } from '@kit.BasicServicesKit'; 9661 9662@Entry 9663@Component 9664struct WebComponent { 9665 controller: webview.WebviewController = new webview.WebviewController(); 9666 9667 build() { 9668 Column() { 9669 Button('configCookieSync') 9670 .onClick(() => { 9671 try { 9672 // Only one cookie value can be set in configCookieSync at a time. 9673 webview.WebCookieManager.configCookieSync('https://www.example.com', 'a=b'); 9674 } catch (error) { 9675 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9676 } 9677 }) 9678 Web({ src: 'www.example.com', controller: this.controller }) 9679 } 9680 } 9681} 9682``` 9683 9684### configCookieSync<sup>14+</sup> 9685 9686static configCookieSync(url: string, value: string, incognito: boolean, includeHttpOnly: boolean): void 9687 9688Sets the cookie value for the specified URL. 9689 9690**System capability**: SystemCapability.Web.Webview.Core 9691 9692**Parameters** 9693 9694| Name| Type | Mandatory| Description | 9695| ------ | ------ | ---- | :------------------------ | 9696| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 9697| value | string | Yes | Cookie value to set. | 9698| incognito | boolean | Yes | Whether to set the cookies in incognito mode. The value **true** means to set the cookies in incognito mode, and **false** means the opposite.| 9699| includeHttpOnly | boolean | Yes | Whether to overwrite cookies containing **HttpOnly**. The value **true** means to overwrite cookies containing **HttpOnly**, and **false** means the opposite.| 9700 9701**Error codes** 9702 9703For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9704 9705| ID| Error Message | 9706| -------- | ------------------------------------------------------ | 9707| 17100002 | Invalid url. | 9708| 17100005 | Invalid cookie value. | 9709| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9710 9711**Example** 9712 9713```ts 9714// xxx.ets 9715import { webview } from '@kit.ArkWeb'; 9716import { BusinessError } from '@kit.BasicServicesKit'; 9717 9718@Entry 9719@Component 9720struct WebComponent { 9721 controller: webview.WebviewController = new webview.WebviewController(); 9722 9723 build() { 9724 Column() { 9725 Button('configCookieSync') 9726 .onClick(() => { 9727 try { 9728 // Only a single cookie value can be set. 9729 webview.WebCookieManager.configCookieSync('https://www.example.com', 'a=b', false, false); 9730 } catch (error) { 9731 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9732 } 9733 }) 9734 Web({ src: 'www.example.com', controller: this.controller }) 9735 } 9736 } 9737} 9738``` 9739 9740### configCookie<sup>11+</sup> 9741 9742static configCookie(url: string, value: string, callback: AsyncCallback\<void>): void 9743 9744Sets the value of a single cookie for a specified URL. This API uses an asynchronous callback to return the result. 9745 9746**System capability**: SystemCapability.Web.Webview.Core 9747 9748**Parameters** 9749 9750| Name| Type | Mandatory| Description | 9751| ------ | ------ | ---- | :------------------------ | 9752| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 9753| value | string | Yes | Cookie value to set. | 9754| callback | AsyncCallback\<void> | Yes| Callback used to return the result.| 9755 9756**Error codes** 9757 9758For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9759 9760| ID| Error Message | 9761| -------- | ------------------------------------------------------ | 9762| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9763| 17100002 | Invalid url. | 9764| 17100005 | Invalid cookie value. | 9765 9766**Example** 9767 9768```ts 9769// xxx.ets 9770import { webview } from '@kit.ArkWeb'; 9771import { BusinessError } from '@kit.BasicServicesKit'; 9772 9773@Entry 9774@Component 9775struct WebComponent { 9776 controller: webview.WebviewController = new webview.WebviewController(); 9777 9778 build() { 9779 Column() { 9780 Button('configCookie') 9781 .onClick(() => { 9782 try { 9783 webview.WebCookieManager.configCookie('https://www.example.com', "a=b", (error) => { 9784 if (error) { 9785 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9786 } 9787 }) 9788 } catch (error) { 9789 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9790 } 9791 }) 9792 Web({ src: 'www.example.com', controller: this.controller }) 9793 } 9794 } 9795} 9796``` 9797 9798### configCookie<sup>11+</sup> 9799 9800static configCookie(url: string, value: string): Promise\<void> 9801 9802Sets the value of a single cookie for a specified URL. This API uses a promise to return the result. 9803 9804**System capability**: SystemCapability.Web.Webview.Core 9805 9806**Parameters** 9807 9808| Name| Type | Mandatory| Description | 9809| ------ | ------ | ---- | :------------------------ | 9810| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 9811| value | string | Yes | Cookie value to set. | 9812 9813**Return value** 9814 9815| Type | Description | 9816| ------ | ------------------------- | 9817| Promise\<void> | Promise used to return the result.| 9818 9819**Error codes** 9820 9821For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9822 9823| ID| Error Message | 9824| -------- | ------------------------------------------------------ | 9825| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9826| 17100002 | Invalid url. | 9827| 17100005 | Invalid cookie value. | 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('configCookie') 9844 .onClick(() => { 9845 try { 9846 webview.WebCookieManager.configCookie('https://www.example.com', 'a=b') 9847 .then(() => { 9848 console.log('configCookie success!'); 9849 }) 9850 .catch((error: BusinessError) => { 9851 console.log('error: ' + JSON.stringify(error)); 9852 }) 9853 } catch (error) { 9854 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9855 } 9856 }) 9857 Web({ src: 'www.example.com', controller: this.controller }) 9858 } 9859 } 9860} 9861``` 9862 9863### configCookie<sup>14+</sup> 9864 9865static configCookie(url: string, value: string, incognito: boolean, includeHttpOnly: boolean): Promise\<void> 9866 9867Sets the value of a single cookie for a specified URL. This API uses a promise to return the result. 9868 9869**System capability**: SystemCapability.Web.Webview.Core 9870 9871**Parameters** 9872 9873| Name| Type | Mandatory| Description | 9874| ------ | ------ | ---- | :------------------------ | 9875| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 9876| value | string | Yes | Cookie value to set. | 9877| incognito | boolean | Yes | Whether to set the cookies in incognito mode. The value **true** means to set the cookies in incognito mode, and **false** means the opposite.| 9878| includeHttpOnly | boolean | Yes | Whether to overwrite cookies containing **HttpOnly**. The value **true** means to overwrite cookies containing **HttpOnly**, and **false** means the opposite.| 9879 9880**Return value** 9881 9882| Type | Description | 9883| ------ | ------------------------- | 9884| Promise\<void> | Promise used to return the result.| 9885 9886**Error codes** 9887 9888For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9889 9890| ID| Error Message | 9891| -------- | ------------------------------------------------------ | 9892| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9893| 17100002 | Invalid url. | 9894| 17100005 | Invalid cookie value. | 9895 9896**Example** 9897 9898```ts 9899// xxx.ets 9900import { webview } from '@kit.ArkWeb'; 9901import { BusinessError } from '@kit.BasicServicesKit'; 9902 9903@Entry 9904@Component 9905struct WebComponent { 9906 controller: webview.WebviewController = new webview.WebviewController(); 9907 9908 build() { 9909 Column() { 9910 Button('configCookie') 9911 .onClick(() => { 9912 try { 9913 webview.WebCookieManager.configCookie('https://www.example.com', 'a=b', false, false) 9914 .then(() => { 9915 console.log('configCookie success!'); 9916 }) 9917 .catch((error: BusinessError) => { 9918 console.log('error: ' + JSON.stringify(error)); 9919 }) 9920 } catch (error) { 9921 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9922 } 9923 }) 9924 Web({ src: 'www.example.com', controller: this.controller }) 9925 } 9926 } 9927} 9928``` 9929 9930### saveCookieSync<sup>15+</sup> 9931 9932static saveCookieSync(): void 9933 9934Saves the cookies in the memory to the drive. This API uses a synchronous callback to return the result. 9935 9936**System capability**: SystemCapability.Web.Webview.Core 9937 9938> **NOTE** 9939> 9940> **saveCookieSync** is used to forcibly write cookies that need to be persisted to disks. By default, session cookies in 2-in-1 and tablets are not persisted. 9941 9942**Example** 9943 9944```ts 9945// xxx.ets 9946import { webview } from '@kit.ArkWeb'; 9947import { BusinessError } from '@kit.BasicServicesKit'; 9948 9949@Entry 9950@Component 9951struct WebComponent { 9952 controller: webview.WebviewController = new webview.WebviewController(); 9953 9954 build() { 9955 Column() { 9956 Button('saveCookieSync') 9957 .onClick(() => { 9958 try { 9959 webview.WebCookieManager.saveCookieSync(); 9960 } catch (error) { 9961 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9962 } 9963 }) 9964 Web({ src: 'www.example.com', controller: this.controller }) 9965 } 9966 } 9967} 9968``` 9969 9970### saveCookieAsync 9971 9972static saveCookieAsync(callback: AsyncCallback\<void>): void 9973 9974Saves the cookies in the memory to the drive. This API uses an asynchronous callback to return the result. 9975 9976**System capability**: SystemCapability.Web.Webview.Core 9977 9978**Parameters** 9979 9980| Name | Type | Mandatory| Description | 9981| -------- | ---------------------- | ---- | :------------------------------------------------- | 9982| callback | AsyncCallback\<void> | Yes | Callback used to return whether the cookies are successfully saved.| 9983 9984**Error codes** 9985 9986For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9987 9988| ID| Error Message | 9989| -------- | ------------------------------------------------------ | 9990| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 9991 9992**Example** 9993 9994```ts 9995// xxx.ets 9996import { webview } from '@kit.ArkWeb'; 9997import { BusinessError } from '@kit.BasicServicesKit'; 9998 9999@Entry 10000@Component 10001struct WebComponent { 10002 controller: webview.WebviewController = new webview.WebviewController(); 10003 10004 build() { 10005 Column() { 10006 Button('saveCookieAsync') 10007 .onClick(() => { 10008 try { 10009 webview.WebCookieManager.saveCookieAsync((error) => { 10010 if (error) { 10011 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10012 } 10013 }) 10014 } catch (error) { 10015 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10016 } 10017 }) 10018 Web({ src: 'www.example.com', controller: this.controller }) 10019 } 10020 } 10021} 10022``` 10023 10024### saveCookieAsync 10025 10026static saveCookieAsync(): Promise\<void> 10027 10028Saves the cookies in the memory to the drive. This API uses a promise to return the result. 10029 10030**System capability**: SystemCapability.Web.Webview.Core 10031 10032**Return value** 10033 10034| Type | Description | 10035| ---------------- | ----------------------------------------- | 10036| Promise\<void> | Promise used to return the operation result.| 10037 10038**Error codes** 10039 10040For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10041 10042| ID| Error Message | 10043| -------- | ------------------------------------------------------ | 10044| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10045 10046**Example** 10047 10048```ts 10049// xxx.ets 10050import { webview } from '@kit.ArkWeb'; 10051import { BusinessError } from '@kit.BasicServicesKit'; 10052 10053@Entry 10054@Component 10055struct WebComponent { 10056 controller: webview.WebviewController = new webview.WebviewController(); 10057 10058 build() { 10059 Column() { 10060 Button('saveCookieAsync') 10061 .onClick(() => { 10062 try { 10063 webview.WebCookieManager.saveCookieAsync() 10064 .then(() => { 10065 console.log("saveCookieAsyncCallback success!"); 10066 }) 10067 .catch((error: BusinessError) => { 10068 console.error("error: " + error); 10069 }); 10070 } catch (error) { 10071 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10072 } 10073 }) 10074 Web({ src: 'www.example.com', controller: this.controller }) 10075 } 10076 } 10077} 10078``` 10079 10080### putAcceptCookieEnabled 10081 10082static putAcceptCookieEnabled(accept: boolean): void 10083 10084Sets whether the **WebCookieManager** instance has the permission to send and receive cookies. 10085 10086**System capability**: SystemCapability.Web.Webview.Core 10087 10088**Parameters** 10089 10090| Name| Type | Mandatory| Description | 10091| ------ | ------- | ---- | :----------------------------------- | 10092| accept | boolean | Yes | Whether the **WebCookieManager** instance has the permission to send and receive cookies.<br>Default value: **true**| 10093 10094**Error codes** 10095 10096For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10097 10098| ID| Error Message | 10099| -------- | ------------------------------------------------------ | 10100| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10101 10102**Example** 10103 10104```ts 10105// xxx.ets 10106import { webview } from '@kit.ArkWeb'; 10107import { BusinessError } from '@kit.BasicServicesKit'; 10108 10109@Entry 10110@Component 10111struct WebComponent { 10112 controller: webview.WebviewController = new webview.WebviewController(); 10113 10114 build() { 10115 Column() { 10116 Button('putAcceptCookieEnabled') 10117 .onClick(() => { 10118 try { 10119 webview.WebCookieManager.putAcceptCookieEnabled(false); 10120 } catch (error) { 10121 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10122 } 10123 }) 10124 Web({ src: 'www.example.com', controller: this.controller }) 10125 } 10126 } 10127} 10128``` 10129 10130### isCookieAllowed 10131 10132static isCookieAllowed(): boolean 10133 10134Checks whether the **WebCookieManager** instance has the permission to send and receive cookies. 10135 10136**System capability**: SystemCapability.Web.Webview.Core 10137 10138**Return value** 10139 10140| Type | Description | 10141| ------- | -------------------------------- | 10142| boolean | Whether the **WebCookieManager** instance has the permission to send and receive cookies. The default value is **true**.| 10143 10144**Example** 10145 10146```ts 10147// xxx.ets 10148import { webview } from '@kit.ArkWeb'; 10149 10150@Entry 10151@Component 10152struct WebComponent { 10153 controller: webview.WebviewController = new webview.WebviewController(); 10154 10155 build() { 10156 Column() { 10157 Button('isCookieAllowed') 10158 .onClick(() => { 10159 let result = webview.WebCookieManager.isCookieAllowed(); 10160 console.log("result: " + result); 10161 }) 10162 Web({ src: 'www.example.com', controller: this.controller }) 10163 } 10164 } 10165} 10166``` 10167 10168### putAcceptThirdPartyCookieEnabled 10169 10170static putAcceptThirdPartyCookieEnabled(accept: boolean): void 10171 10172Sets whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. 10173 10174**System capability**: SystemCapability.Web.Webview.Core 10175 10176**Parameters** 10177 10178| Name| Type | Mandatory| Description | 10179| ------ | ------- | ---- | :----------------------------------------- | 10180| accept | boolean | Yes | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies.<br>Default value: **false**| 10181 10182**Error codes** 10183 10184For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10185 10186| ID| Error Message | 10187| -------- | ------------------------------------------------------ | 10188| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10189 10190**Example** 10191 10192```ts 10193// xxx.ets 10194import { webview } from '@kit.ArkWeb'; 10195import { BusinessError } from '@kit.BasicServicesKit'; 10196 10197@Entry 10198@Component 10199struct WebComponent { 10200 controller: webview.WebviewController = new webview.WebviewController(); 10201 10202 build() { 10203 Column() { 10204 Button('putAcceptThirdPartyCookieEnabled') 10205 .onClick(() => { 10206 try { 10207 webview.WebCookieManager.putAcceptThirdPartyCookieEnabled(false); 10208 } catch (error) { 10209 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10210 } 10211 }) 10212 Web({ src: 'www.example.com', controller: this.controller }) 10213 } 10214 } 10215} 10216``` 10217 10218### isThirdPartyCookieAllowed 10219 10220static isThirdPartyCookieAllowed(): boolean 10221 10222Checks whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. 10223 10224**System capability**: SystemCapability.Web.Webview.Core 10225 10226**Return value** 10227 10228| Type | Description | 10229| ------- | -------------------------------------- | 10230| boolean | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. The default value is **false**.| 10231 10232**Example** 10233 10234```ts 10235// xxx.ets 10236import { webview } from '@kit.ArkWeb'; 10237 10238@Entry 10239@Component 10240struct WebComponent { 10241 controller: webview.WebviewController = new webview.WebviewController(); 10242 10243 build() { 10244 Column() { 10245 Button('isThirdPartyCookieAllowed') 10246 .onClick(() => { 10247 let result = webview.WebCookieManager.isThirdPartyCookieAllowed(); 10248 console.log("result: " + result); 10249 }) 10250 Web({ src: 'www.example.com', controller: this.controller }) 10251 } 10252 } 10253} 10254``` 10255 10256### existCookie 10257 10258static existCookie(incognito?: boolean): boolean 10259 10260Checks whether cookies exist. 10261 10262**System capability**: SystemCapability.Web.Webview.Core 10263 10264**Parameters** 10265 10266| Name| Type | Mandatory| Description | 10267| ------ | ------- | ---- | :----------------------------------------- | 10268| 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.| 10269 10270**Return value** 10271 10272| Type | Description | 10273| ------- | -------------------------------------- | 10274| boolean | Whether cookies exist. The value **true** means that cookies exist, and **false** means the opposite.| 10275 10276**Example** 10277 10278```ts 10279// xxx.ets 10280import { webview } from '@kit.ArkWeb'; 10281 10282@Entry 10283@Component 10284struct WebComponent { 10285 controller: webview.WebviewController = new webview.WebviewController(); 10286 10287 build() { 10288 Column() { 10289 Button('existCookie') 10290 .onClick(() => { 10291 let result = webview.WebCookieManager.existCookie(); 10292 console.log("result: " + result); 10293 }) 10294 Web({ src: 'www.example.com', controller: this.controller }) 10295 } 10296 } 10297} 10298``` 10299 10300### deleteEntireCookie<sup>(deprecated)</sup> 10301 10302static deleteEntireCookie(): void 10303 10304Deletes all cookies. 10305 10306> **NOTE** 10307> 10308> This API is supported since API version 9 and deprecated since API version 11. You are advised to use [clearAllCookiesSync](#clearallcookiessync11) instead. 10309 10310**System capability**: SystemCapability.Web.Webview.Core 10311 10312**Example** 10313 10314```ts 10315// xxx.ets 10316import { webview } from '@kit.ArkWeb'; 10317 10318@Entry 10319@Component 10320struct WebComponent { 10321 controller: webview.WebviewController = new webview.WebviewController(); 10322 10323 build() { 10324 Column() { 10325 Button('deleteEntireCookie') 10326 .onClick(() => { 10327 webview.WebCookieManager.deleteEntireCookie(); 10328 }) 10329 Web({ src: 'www.example.com', controller: this.controller }) 10330 } 10331 } 10332} 10333``` 10334 10335### clearAllCookiesSync<sup>11+</sup> 10336 10337static clearAllCookiesSync(incognito?: boolean): void 10338 10339Deletes all cookies. 10340 10341**System capability**: SystemCapability.Web.Webview.Core 10342 10343**Parameters** 10344 10345| Name| Type | Mandatory| Description | 10346| ------ | ------- | ---- | :----------------------------------------- | 10347| 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.| 10348 10349**Example** 10350 10351```ts 10352// xxx.ets 10353import { webview } from '@kit.ArkWeb'; 10354 10355@Entry 10356@Component 10357struct WebComponent { 10358 controller: webview.WebviewController = new webview.WebviewController(); 10359 10360 build() { 10361 Column() { 10362 Button('clearAllCookiesSync') 10363 .onClick(() => { 10364 webview.WebCookieManager.clearAllCookiesSync(); 10365 }) 10366 Web({ src: 'www.example.com', controller: this.controller }) 10367 } 10368 } 10369} 10370``` 10371 10372### clearAllCookies<sup>11+</sup> 10373 10374static clearAllCookies(callback: AsyncCallback\<void>): void 10375 10376Clears all cookies. This API uses an asynchronous callback to return the result. 10377 10378**System capability**: SystemCapability.Web.Webview.Core 10379 10380**Parameters** 10381 10382| Name | Type | Mandatory| Description | 10383| -------- | ---------------------- | ---- | :------------------------------------------------- | 10384| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 10385 10386**Error codes** 10387 10388For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10389 10390| ID| Error Message | 10391| -------- | ------------------------------------------------------ | 10392| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 10393 10394**Example** 10395 10396```ts 10397// xxx.ets 10398import { webview } from '@kit.ArkWeb'; 10399import { BusinessError } from '@kit.BasicServicesKit'; 10400 10401@Entry 10402@Component 10403struct WebComponent { 10404 controller: webview.WebviewController = new webview.WebviewController(); 10405 10406 build() { 10407 Column() { 10408 Button('clearAllCookies') 10409 .onClick(() => { 10410 try { 10411 webview.WebCookieManager.clearAllCookies((error) => { 10412 if (error) { 10413 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10414 } 10415 }) 10416 } catch (error) { 10417 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10418 } 10419 }) 10420 Web({ src: 'www.example.com', controller: this.controller }) 10421 } 10422 } 10423} 10424``` 10425 10426### clearAllCookies<sup>11+</sup> 10427 10428static clearAllCookies(): Promise\<void> 10429 10430Clears all cookies. This API uses a promise to return the result. 10431 10432**System capability**: SystemCapability.Web.Webview.Core 10433 10434**Return value** 10435 10436| Type | Description | 10437| ---------------- | ----------------------------------------- | 10438| Promise\<void> | Promise used to return the result.| 10439 10440**Error codes** 10441 10442For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10443 10444| ID| Error Message | 10445| -------- | ------------------------------------------------------ | 10446| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 10447 10448**Example** 10449 10450```ts 10451// xxx.ets 10452import { webview } from '@kit.ArkWeb'; 10453import { BusinessError } from '@kit.BasicServicesKit'; 10454 10455@Entry 10456@Component 10457struct WebComponent { 10458 controller: webview.WebviewController = new webview.WebviewController(); 10459 10460 build() { 10461 Column() { 10462 Button('clearAllCookies') 10463 .onClick(() => { 10464 try { 10465 webview.WebCookieManager.clearAllCookies() 10466 .then(() => { 10467 console.log("clearAllCookies success!"); 10468 }) 10469 .catch((error: BusinessError) => { 10470 console.error("error: " + error); 10471 }); 10472 } catch (error) { 10473 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10474 } 10475 }) 10476 Web({ src: 'www.example.com', controller: this.controller }) 10477 } 10478 } 10479} 10480``` 10481 10482### deleteSessionCookie<sup>(deprecated)</sup> 10483 10484static deleteSessionCookie(): void 10485 10486Deletes all session cookies. 10487 10488> **NOTE** 10489> 10490> This API is supported since API version 9 and deprecated since API version 11. You are advised to use [clearSessionCookiesync](#clearsessioncookiesync11) instead. 10491 10492**System capability**: SystemCapability.Web.Webview.Core 10493 10494**Example** 10495 10496```ts 10497// xxx.ets 10498import { webview } from '@kit.ArkWeb'; 10499 10500@Entry 10501@Component 10502struct WebComponent { 10503 controller: webview.WebviewController = new webview.WebviewController(); 10504 10505 build() { 10506 Column() { 10507 Button('deleteSessionCookie') 10508 .onClick(() => { 10509 webview.WebCookieManager.deleteSessionCookie(); 10510 }) 10511 Web({ src: 'www.example.com', controller: this.controller }) 10512 } 10513 } 10514} 10515``` 10516 10517### clearSessionCookieSync<sup>11+</sup> 10518 10519static clearSessionCookieSync(): void 10520 10521Deletes all session cookies. 10522 10523**System capability**: SystemCapability.Web.Webview.Core 10524 10525**Example** 10526 10527```ts 10528// xxx.ets 10529import { webview } from '@kit.ArkWeb'; 10530 10531@Entry 10532@Component 10533struct WebComponent { 10534 controller: webview.WebviewController = new webview.WebviewController(); 10535 10536 build() { 10537 Column() { 10538 Button('clearSessionCookieSync') 10539 .onClick(() => { 10540 webview.WebCookieManager.clearSessionCookieSync(); 10541 }) 10542 Web({ src: 'www.example.com', controller: this.controller }) 10543 } 10544 } 10545} 10546``` 10547 10548### clearSessionCookie<sup>11+</sup> 10549 10550static clearSessionCookie(callback: AsyncCallback\<void>): void 10551 10552Clears all session cookies. This API uses an asynchronous callback to return the result. 10553 10554**System capability**: SystemCapability.Web.Webview.Core 10555 10556**Parameters** 10557 10558| Name | Type | Mandatory| Description | 10559| -------- | ---------------------- | ---- | :------------------------------------------------- | 10560| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 10561 10562**Error codes** 10563 10564For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10565 10566| ID| Error Message | 10567| -------- | ------------------------------------------------------ | 10568| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 10569 10570**Example** 10571 10572```ts 10573// xxx.ets 10574import { webview } from '@kit.ArkWeb'; 10575import { BusinessError } from '@kit.BasicServicesKit'; 10576 10577@Entry 10578@Component 10579struct WebComponent { 10580 controller: webview.WebviewController = new webview.WebviewController(); 10581 10582 build() { 10583 Column() { 10584 Button('clearSessionCookie') 10585 .onClick(() => { 10586 try { 10587 webview.WebCookieManager.clearSessionCookie((error) => { 10588 if (error) { 10589 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10590 } 10591 }) 10592 } catch (error) { 10593 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10594 } 10595 }) 10596 Web({ src: 'www.example.com', controller: this.controller }) 10597 } 10598 } 10599} 10600``` 10601 10602### clearSessionCookie<sup>11+</sup> 10603 10604static clearSessionCookie(): Promise\<void> 10605 10606Clears all session cookies. This API uses a promise to return the result. 10607 10608**System capability**: SystemCapability.Web.Webview.Core 10609 10610**Return value** 10611 10612| Type | Description | 10613| ---------------- | ----------------------------------------- | 10614| Promise\<void> | Promise used to return the result.| 10615 10616**Error codes** 10617 10618For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10619 10620| ID| Error Message | 10621| -------- | ------------------------------------------------------ | 10622| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 10623 10624**Example** 10625 10626```ts 10627// xxx.ets 10628import { webview } from '@kit.ArkWeb'; 10629import { BusinessError } from '@kit.BasicServicesKit'; 10630 10631@Entry 10632@Component 10633struct WebComponent { 10634 controller: webview.WebviewController = new webview.WebviewController(); 10635 10636 build() { 10637 Column() { 10638 Button('clearSessionCookie') 10639 .onClick(() => { 10640 try { 10641 webview.WebCookieManager.clearSessionCookie() 10642 .then(() => { 10643 console.log("clearSessionCookie success!"); 10644 }) 10645 .catch((error: BusinessError) => { 10646 console.error("error: " + error); 10647 }); 10648 } catch (error) { 10649 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10650 } 10651 }) 10652 Web({ src: 'www.example.com', controller: this.controller }) 10653 } 10654 } 10655} 10656``` 10657 10658## WebStorage 10659 10660Implements a **WebStorage** object to manage the Web SQL database and HTML5 Web Storage APIs. All **Web** components in an application share a **WebStorage** object. 10661 10662> **NOTE** 10663> 10664> You must load the **Web** component before calling the APIs in **WebStorage**. 10665 10666### deleteOrigin 10667 10668static deleteOrigin(origin: string): void 10669 10670Deletes all data in the specified origin. 10671 10672**System capability**: SystemCapability.Web.Webview.Core 10673 10674**Parameters** 10675 10676| Name| Type | Mandatory| Description | 10677| ------ | ------ | ---- | ------------------------ | 10678| origin | string | Yes | Index of the origin, which is obtained through [getOrigins](#getorigins).| 10679 10680**Error codes** 10681 10682For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10683 10684| ID| Error Message | 10685| -------- | ------------------------------------------------------ | 10686| 17100011 | Invalid origin. | 10687| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10688 10689**Example** 10690 10691```ts 10692// xxx.ets 10693import { webview } from '@kit.ArkWeb'; 10694import { BusinessError } from '@kit.BasicServicesKit'; 10695 10696@Entry 10697@Component 10698struct WebComponent { 10699 controller: webview.WebviewController = new webview.WebviewController(); 10700 origin: string = "resource://rawfile/"; 10701 10702 build() { 10703 Column() { 10704 Button('deleteOrigin') 10705 .onClick(() => { 10706 try { 10707 webview.WebStorage.deleteOrigin(this.origin); 10708 } catch (error) { 10709 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10710 } 10711 10712 }) 10713 Web({ src: $rawfile('index.html'), controller: this.controller }) 10714 .databaseAccess(true) 10715 } 10716 } 10717} 10718``` 10719 10720HTML file to be loaded: 10721 ```html 10722 <!-- index.html --> 10723 <!DOCTYPE html> 10724 <html> 10725 <head> 10726 <meta charset="UTF-8"> 10727 <title>test</title> 10728 <script type="text/javascript"> 10729 10730 var db = openDatabase('mydb','1.0','Test DB',2 * 1024 * 1024); 10731 var msg; 10732 10733 db.transaction(function(tx){ 10734 tx.executeSql('INSERT INTO LOGS (id,log) VALUES(1,"test1")'); 10735 tx.executeSql('INSERT INTO LOGS (id,log) VALUES(2,"test2")'); 10736 msg = '<p>Data table created, with two data records inserted.</p>'; 10737 10738 document.querySelector('#status').innerHTML = msg; 10739 }); 10740 10741 db.transaction(function(tx){ 10742 tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) { 10743 var len = results.rows.length,i; 10744 msg = "<p>Number of records: " + len + "</p>"; 10745 10746 document.querySelector('#status').innerHTML += msg; 10747 10748 for(i = 0; i < len; i++){ 10749 msg = "<p><b>" + results.rows.item(i).log + "</b></p>"; 10750 10751 document.querySelector('#status').innerHTML += msg; 10752 } 10753 },null); 10754 }); 10755 10756 </script> 10757 </head> 10758 <body> 10759 <div id="status" name="status">Status</div> 10760 </body> 10761 </html> 10762 ``` 10763 10764### getOrigins 10765 10766static getOrigins(callback: AsyncCallback\<Array\<WebStorageOrigin>>): void 10767 10768Obtains information about all origins that are currently using the Web SQL Database. This API uses an asynchronous callback to return the result. 10769 10770**System capability**: SystemCapability.Web.Webview.Core 10771 10772**Parameters** 10773 10774| Name | Type | Mandatory| Description | 10775| -------- | -------------------------------------- | ---- | ------------------------------------------------------ | 10776| callback | AsyncCallback\<Array\<[WebStorageOrigin](#webstorageorigin)>> | Yes | Callback used to return the information about the origins. For details, see [WebStorageOrigin](#webstorageorigin).| 10777 10778**Error codes** 10779 10780For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10781 10782| ID| Error Message | 10783| -------- | ------------------------------------------------------ | 10784| 17100012 | Invalid web storage origin. | 10785| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10786 10787**Example** 10788 10789```ts 10790// xxx.ets 10791import { webview } from '@kit.ArkWeb'; 10792import { BusinessError } from '@kit.BasicServicesKit'; 10793 10794@Entry 10795@Component 10796struct WebComponent { 10797 controller: webview.WebviewController = new webview.WebviewController(); 10798 10799 build() { 10800 Column() { 10801 Button('getOrigins') 10802 .onClick(() => { 10803 try { 10804 webview.WebStorage.getOrigins((error, origins) => { 10805 if (error) { 10806 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10807 return; 10808 } 10809 for (let i = 0; i < origins.length; i++) { 10810 console.log('origin: ' + origins[i].origin); 10811 console.log('usage: ' + origins[i].usage); 10812 console.log('quota: ' + origins[i].quota); 10813 } 10814 }) 10815 } catch (error) { 10816 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10817 } 10818 10819 }) 10820 Web({ src: $rawfile('index.html'), controller: this.controller }) 10821 .databaseAccess(true) 10822 } 10823 } 10824} 10825``` 10826 10827For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 10828 10829### getOrigins 10830 10831static getOrigins(): Promise\<Array\<WebStorageOrigin>> 10832 10833Obtains information about all origins that are currently using the Web SQL Database. This API uses a promise to return the result. 10834 10835**System capability**: SystemCapability.Web.Webview.Core 10836 10837**Return value** 10838 10839| Type | Description | 10840| -------------------------------- | ------------------------------------------------------------ | 10841| Promise\<Array\<[WebStorageOrigin](#webstorageorigin)>> | Promise used to return the information about the origins. For details, see [WebStorageOrigin](#webstorageorigin).| 10842 10843**Error codes** 10844 10845For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10846 10847| ID| Error Message | 10848| -------- | ------------------------------------------------------ | 10849| 17100012 | Invalid web storage origin. | 10850| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10851 10852**Example** 10853 10854```ts 10855// xxx.ets 10856import { webview } from '@kit.ArkWeb'; 10857import { BusinessError } from '@kit.BasicServicesKit'; 10858 10859@Entry 10860@Component 10861struct WebComponent { 10862 controller: webview.WebviewController = new webview.WebviewController(); 10863 10864 build() { 10865 Column() { 10866 Button('getOrigins') 10867 .onClick(() => { 10868 try { 10869 webview.WebStorage.getOrigins() 10870 .then(origins => { 10871 for (let i = 0; i < origins.length; i++) { 10872 console.log('origin: ' + origins[i].origin); 10873 console.log('usage: ' + origins[i].usage); 10874 console.log('quota: ' + origins[i].quota); 10875 } 10876 }) 10877 .catch((e: BusinessError) => { 10878 console.log('error: ' + JSON.stringify(e)); 10879 }) 10880 } catch (error) { 10881 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10882 } 10883 10884 }) 10885 Web({ src: $rawfile('index.html'), controller: this.controller }) 10886 .databaseAccess(true) 10887 } 10888 } 10889} 10890``` 10891 10892For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 10893 10894### getOriginQuota 10895 10896static getOriginQuota(origin: string, callback: AsyncCallback\<number>): void 10897 10898Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. 10899 10900**System capability**: SystemCapability.Web.Webview.Core 10901 10902**Parameters** 10903 10904| Name | Type | Mandatory| Description | 10905| -------- | --------------------- | ---- | ------------------ | 10906| origin | string | Yes | Index of the origin.| 10907| callback | AsyncCallback\<number> | Yes | Storage quota of the origin. | 10908 10909**Error codes** 10910 10911For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10912 10913| ID| Error Message | 10914| -------- | ------------------------------------------------------ | 10915| 17100011 | Invalid origin. | 10916| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10917 10918**Example** 10919 10920```ts 10921// xxx.ets 10922import { webview } from '@kit.ArkWeb'; 10923import { BusinessError } from '@kit.BasicServicesKit'; 10924 10925@Entry 10926@Component 10927struct WebComponent { 10928 controller: webview.WebviewController = new webview.WebviewController(); 10929 origin: string = "resource://rawfile/"; 10930 10931 build() { 10932 Column() { 10933 Button('getOriginQuota') 10934 .onClick(() => { 10935 try { 10936 webview.WebStorage.getOriginQuota(this.origin, (error, quota) => { 10937 if (error) { 10938 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10939 return; 10940 } 10941 console.log('quota: ' + quota); 10942 }) 10943 } catch (error) { 10944 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10945 } 10946 10947 }) 10948 Web({ src: $rawfile('index.html'), controller: this.controller }) 10949 .databaseAccess(true) 10950 } 10951 } 10952} 10953``` 10954 10955For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 10956 10957### getOriginQuota 10958 10959static getOriginQuota(origin: string): Promise\<number> 10960 10961Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. 10962 10963**System capability**: SystemCapability.Web.Webview.Core 10964 10965**Parameters** 10966 10967| Name| Type | Mandatory| Description | 10968| ------ | ------ | ---- | ------------------ | 10969| origin | string | Yes | Index of the origin.| 10970 10971**Return value** 10972 10973| Type | Description | 10974| --------------- | --------------------------------------- | 10975| Promise\<number> | Promise used to return the storage quota of the origin.| 10976 10977**Error codes** 10978 10979For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10980 10981| ID| Error Message | 10982| -------- | ------------------------------------------------------ | 10983| 17100011 | Invalid origin. | 10984| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10985 10986**Example** 10987 10988```ts 10989// xxx.ets 10990import { webview } from '@kit.ArkWeb'; 10991import { BusinessError } from '@kit.BasicServicesKit'; 10992 10993@Entry 10994@Component 10995struct WebComponent { 10996 controller: webview.WebviewController = new webview.WebviewController(); 10997 origin: string = "resource://rawfile/"; 10998 10999 build() { 11000 Column() { 11001 Button('getOriginQuota') 11002 .onClick(() => { 11003 try { 11004 webview.WebStorage.getOriginQuota(this.origin) 11005 .then(quota => { 11006 console.log('quota: ' + quota); 11007 }) 11008 .catch((e: BusinessError) => { 11009 console.log('error: ' + JSON.stringify(e)); 11010 }) 11011 } catch (error) { 11012 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11013 } 11014 11015 }) 11016 Web({ src: $rawfile('index.html'), controller: this.controller }) 11017 .databaseAccess(true) 11018 } 11019 } 11020} 11021``` 11022 11023For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 11024 11025### getOriginUsage 11026 11027static getOriginUsage(origin: string, callback: AsyncCallback\<number>): void 11028 11029Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. 11030 11031**System capability**: SystemCapability.Web.Webview.Core 11032 11033**Parameters** 11034 11035| Name | Type | Mandatory| Description | 11036| -------- | --------------------- | ---- | ------------------ | 11037| origin | string | Yes | Index of the origin.| 11038| callback | AsyncCallback\<number> | Yes | Storage usage of the origin. | 11039 11040**Error codes** 11041 11042For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11043 11044| ID| Error Message | 11045| -------- | ------------------------------------------------------ | 11046| 17100011 | Invalid origin. | 11047| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11048 11049**Example** 11050 11051```ts 11052// xxx.ets 11053import { webview } from '@kit.ArkWeb'; 11054import { BusinessError } from '@kit.BasicServicesKit'; 11055 11056@Entry 11057@Component 11058struct WebComponent { 11059 controller: webview.WebviewController = new webview.WebviewController(); 11060 origin: string = "resource://rawfile/"; 11061 11062 build() { 11063 Column() { 11064 Button('getOriginUsage') 11065 .onClick(() => { 11066 try { 11067 webview.WebStorage.getOriginUsage(this.origin, (error, usage) => { 11068 if (error) { 11069 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11070 return; 11071 } 11072 console.log('usage: ' + usage); 11073 }) 11074 } catch (error) { 11075 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11076 } 11077 11078 }) 11079 Web({ src: $rawfile('index.html'), controller: this.controller }) 11080 .databaseAccess(true) 11081 } 11082 } 11083} 11084``` 11085 11086For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 11087 11088### getOriginUsage 11089 11090static getOriginUsage(origin: string): Promise\<number> 11091 11092Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. 11093 11094**System capability**: SystemCapability.Web.Webview.Core 11095 11096**Parameters** 11097 11098| Name| Type | Mandatory| Description | 11099| ------ | ------ | ---- | ------------------ | 11100| origin | string | Yes | Index of the origin.| 11101 11102**Return value** 11103 11104| Type | Description | 11105| --------------- | ------------------------------------- | 11106| Promise\<number> | Promise used to return the storage usage of the origin.| 11107 11108**Error codes** 11109 11110For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11111 11112| ID| Error Message | 11113| -------- | ----------------------------------------------------- | 11114| 17100011 | Invalid origin. | 11115| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11116 11117**Example** 11118 11119```ts 11120// xxx.ets 11121import { webview } from '@kit.ArkWeb'; 11122import { BusinessError } from '@kit.BasicServicesKit'; 11123 11124@Entry 11125@Component 11126struct WebComponent { 11127 controller: webview.WebviewController = new webview.WebviewController(); 11128 origin: string = "resource://rawfile/"; 11129 11130 build() { 11131 Column() { 11132 Button('getOriginUsage') 11133 .onClick(() => { 11134 try { 11135 webview.WebStorage.getOriginUsage(this.origin) 11136 .then(usage => { 11137 console.log('usage: ' + usage); 11138 }).catch((e: BusinessError) => { 11139 console.error('error: ' + JSON.stringify(e)); 11140 }) 11141 } catch (error) { 11142 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11143 } 11144 }) 11145 Web({ src: $rawfile('index.html'), controller: this.controller }) 11146 .databaseAccess(true) 11147 } 11148 } 11149} 11150``` 11151 11152For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 11153 11154### deleteAllData 11155 11156static deleteAllData(incognito?: boolean): void 11157 11158Deletes all data in the Web SQL Database. 11159 11160**System capability**: SystemCapability.Web.Webview.Core 11161 11162**Parameters** 11163 11164| Name| Type | Mandatory| Description | 11165| ------ | ------ | ---- | ------------------ | 11166| 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.| 11167 11168**Example** 11169 11170```ts 11171// xxx.ets 11172import { webview } from '@kit.ArkWeb'; 11173import { BusinessError } from '@kit.BasicServicesKit'; 11174 11175@Entry 11176@Component 11177struct WebComponent { 11178 controller: webview.WebviewController = new webview.WebviewController(); 11179 11180 build() { 11181 Column() { 11182 Button('deleteAllData') 11183 .onClick(() => { 11184 try { 11185 webview.WebStorage.deleteAllData(); 11186 } catch (error) { 11187 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11188 } 11189 }) 11190 Web({ src: $rawfile('index.html'), controller: this.controller }) 11191 .databaseAccess(true) 11192 } 11193 } 11194} 11195``` 11196 11197For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 11198 11199## WebDataBase 11200 11201Implements a **WebDataBase** object. 11202 11203> **NOTE** 11204> 11205> You must load the **Web** component before calling the APIs in **WebDataBase**. 11206 11207### getHttpAuthCredentials 11208 11209static getHttpAuthCredentials(host: string, realm: string): Array\<string> 11210 11211Retrieves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. 11212 11213**System capability**: SystemCapability.Web.Webview.Core 11214 11215**Parameters** 11216 11217| Name| Type | Mandatory| Description | 11218| ------ | ------ | ---- | ---------------------------- | 11219| host | string | Yes | Host to which HTTP authentication credentials apply.| 11220| realm | string | Yes | Realm to which HTTP authentication credentials apply. | 11221 11222**Return value** 11223 11224| Type | Description | 11225| ----- | -------------------------------------------- | 11226| Array\<string> | Returns the array of the matching user names and passwords if the operation is successful; returns an empty array otherwise.| 11227 11228**Error codes** 11229 11230For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11231 11232| ID| Error Message | 11233| -------- | ------------------------------------------------------ | 11234| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11235 11236**Example** 11237 11238```ts 11239// xxx.ets 11240import { webview } from '@kit.ArkWeb'; 11241import { BusinessError } from '@kit.BasicServicesKit'; 11242 11243@Entry 11244@Component 11245struct WebComponent { 11246 controller: webview.WebviewController = new webview.WebviewController(); 11247 host: string = "www.spincast.org"; 11248 realm: string = "protected example"; 11249 username_password: string[] = []; 11250 11251 build() { 11252 Column() { 11253 Button('getHttpAuthCredentials') 11254 .onClick(() => { 11255 try { 11256 this.username_password = webview.WebDataBase.getHttpAuthCredentials(this.host, this.realm); 11257 console.log('num: ' + this.username_password.length); 11258 } catch (error) { 11259 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11260 } 11261 }) 11262 Web({ src: 'www.example.com', controller: this.controller }) 11263 } 11264 } 11265} 11266``` 11267 11268### saveHttpAuthCredentials 11269 11270static saveHttpAuthCredentials(host: string, realm: string, username: string, password: string): void 11271 11272Saves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. 11273 11274**System capability**: SystemCapability.Web.Webview.Core 11275 11276**Parameters** 11277 11278| Name | Type | Mandatory| Description | 11279| -------- | ------ | ---- | ---------------------------- | 11280| host | string | Yes | Host to which HTTP authentication credentials apply.| 11281| realm | string | Yes | Realm to which HTTP authentication credentials apply. | 11282| username | string | Yes | User name. | 11283| password | string | Yes | Password. | 11284 11285**Error codes** 11286 11287For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11288 11289| ID| Error Message | 11290| -------- | ------------------------------------------------------ | 11291| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11292 11293**Example** 11294 11295```ts 11296// xxx.ets 11297import { webview } from '@kit.ArkWeb'; 11298import { BusinessError } from '@kit.BasicServicesKit'; 11299 11300@Entry 11301@Component 11302struct WebComponent { 11303 controller: webview.WebviewController = new webview.WebviewController(); 11304 host: string = "www.spincast.org"; 11305 realm: string = "protected example"; 11306 11307 build() { 11308 Column() { 11309 Button('saveHttpAuthCredentials') 11310 .onClick(() => { 11311 try { 11312 webview.WebDataBase.saveHttpAuthCredentials(this.host, this.realm, "Stromgol", "Laroche"); 11313 } catch (error) { 11314 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11315 } 11316 }) 11317 Web({ src: 'www.example.com', controller: this.controller }) 11318 } 11319 } 11320} 11321``` 11322 11323### existHttpAuthCredentials 11324 11325static existHttpAuthCredentials(): boolean 11326 11327Checks whether any saved HTTP authentication credentials exist. This API returns the result synchronously. 11328 11329**System capability**: SystemCapability.Web.Webview.Core 11330 11331**Return value** 11332 11333| Type | Description | 11334| ------- | ------------------------------------------------------------ | 11335| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist; returns **false** otherwise.| 11336 11337**Example** 11338 11339```ts 11340// xxx.ets 11341import { webview } from '@kit.ArkWeb'; 11342import { BusinessError } from '@kit.BasicServicesKit'; 11343 11344@Entry 11345@Component 11346struct WebComponent { 11347 controller: webview.WebviewController = new webview.WebviewController(); 11348 11349 build() { 11350 Column() { 11351 Button('existHttpAuthCredentials') 11352 .onClick(() => { 11353 try { 11354 let result = webview.WebDataBase.existHttpAuthCredentials(); 11355 } catch (error) { 11356 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11357 } 11358 }) 11359 Web({ src: 'www.example.com', controller: this.controller }) 11360 } 11361 } 11362} 11363``` 11364 11365### deleteHttpAuthCredentials 11366 11367static deleteHttpAuthCredentials(): void 11368 11369Deletes all HTTP authentication credentials saved in the cache. This API returns the result synchronously. 11370 11371**System capability**: SystemCapability.Web.Webview.Core 11372 11373**Example** 11374 11375```ts 11376// xxx.ets 11377import { webview } from '@kit.ArkWeb'; 11378import { BusinessError } from '@kit.BasicServicesKit'; 11379 11380@Entry 11381@Component 11382struct WebComponent { 11383 controller: webview.WebviewController = new webview.WebviewController(); 11384 11385 build() { 11386 Column() { 11387 Button('deleteHttpAuthCredentials') 11388 .onClick(() => { 11389 try { 11390 webview.WebDataBase.deleteHttpAuthCredentials(); 11391 } catch (error) { 11392 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11393 } 11394 }) 11395 Web({ src: 'www.example.com', controller: this.controller }) 11396 } 11397 } 11398} 11399``` 11400 11401## GeolocationPermissions 11402 11403Implements a **GeolocationPermissions** object. 11404 11405> **NOTE** 11406> 11407> You must load the **Web** component before calling the APIs in **GeolocationPermissions**. 11408 11409### Required Permissions 11410 11411**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). 11412 11413### allowGeolocation 11414 11415static allowGeolocation(origin: string, incognito?: boolean): void 11416 11417Allows the specified origin to use the geolocation information. 11418 11419**System capability**: SystemCapability.Web.Webview.Core 11420 11421**Parameters** 11422 11423| Name| Type | Mandatory| Description | 11424| ------ | ------ | ---- | ------------------ | 11425| origin | string | Yes |Index of the origin.| 11426| 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.| 11427 11428**Error codes** 11429 11430For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11431 11432| ID| Error Message | 11433| -------- | ------------------------------------------------------ | 11434| 17100011 | Invalid origin. | 11435| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11436 11437**Example** 11438 11439```ts 11440// xxx.ets 11441import { webview } from '@kit.ArkWeb'; 11442import { BusinessError } from '@kit.BasicServicesKit'; 11443 11444@Entry 11445@Component 11446struct WebComponent { 11447 controller: webview.WebviewController = new webview.WebviewController(); 11448 origin: string = "file:///"; 11449 11450 build() { 11451 Column() { 11452 Button('allowGeolocation') 11453 .onClick(() => { 11454 try { 11455 webview.GeolocationPermissions.allowGeolocation(this.origin); 11456 } catch (error) { 11457 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11458 } 11459 }) 11460 Web({ src: 'www.example.com', controller: this.controller }) 11461 } 11462 } 11463} 11464``` 11465 11466### deleteGeolocation 11467 11468static deleteGeolocation(origin: string, incognito?: boolean): void 11469 11470Clears the geolocation permission status of a specified origin. 11471 11472**System capability**: SystemCapability.Web.Webview.Core 11473 11474**Parameters** 11475 11476| Name| Type | Mandatory| Description | 11477| ------ | ------ | ---- | ------------------ | 11478| origin | string | Yes | Index of the origin.| 11479| 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.| 11480 11481**Error codes** 11482 11483For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11484 11485| ID| Error Message | 11486| -------- | ------------------------------------------------------ | 11487| 17100011 | Invalid origin. | 11488| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11489 11490**Example** 11491 11492```ts 11493// xxx.ets 11494import { webview } from '@kit.ArkWeb'; 11495import { BusinessError } from '@kit.BasicServicesKit'; 11496 11497@Entry 11498@Component 11499struct WebComponent { 11500 controller: webview.WebviewController = new webview.WebviewController(); 11501 origin: string = "file:///"; 11502 11503 build() { 11504 Column() { 11505 Button('deleteGeolocation') 11506 .onClick(() => { 11507 try { 11508 webview.GeolocationPermissions.deleteGeolocation(this.origin); 11509 } catch (error) { 11510 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11511 } 11512 }) 11513 Web({ src: 'www.example.com', controller: this.controller }) 11514 } 11515 } 11516} 11517``` 11518 11519### getAccessibleGeolocation 11520 11521static getAccessibleGeolocation(origin: string, callback: AsyncCallback\<boolean>, incognito?: boolean): void 11522 11523Obtains the geolocation permission status of the specified origin. This API uses an asynchronous callback to return the result. 11524 11525**System capability**: SystemCapability.Web.Webview.Core 11526 11527**Parameters** 11528 11529| Name | Type | Mandatory| Description | 11530| -------- | ---------------------- | ---- | ------------------------------------------------------------ | 11531| origin | string | Yes | Index of the origin. | 11532| 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.| 11533| 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.| 11534 11535**Error codes** 11536 11537For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11538 11539| ID| Error Message | 11540| -------- | ------------------------------------------------------ | 11541| 17100011 | Invalid origin. | 11542| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11543 11544**Example** 11545 11546```ts 11547// xxx.ets 11548import { webview } from '@kit.ArkWeb'; 11549import { BusinessError } from '@kit.BasicServicesKit'; 11550 11551@Entry 11552@Component 11553struct WebComponent { 11554 controller: webview.WebviewController = new webview.WebviewController(); 11555 origin: string = "file:///"; 11556 11557 build() { 11558 Column() { 11559 Button('getAccessibleGeolocation') 11560 .onClick(() => { 11561 try { 11562 webview.GeolocationPermissions.getAccessibleGeolocation(this.origin, (error, result) => { 11563 if (error) { 11564 console.error(`getAccessibleGeolocationAsync error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11565 return; 11566 } 11567 console.log('getAccessibleGeolocationAsync result: ' + result); 11568 }); 11569 } catch (error) { 11570 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11571 } 11572 }) 11573 Web({ src: 'www.example.com', controller: this.controller }) 11574 } 11575 } 11576} 11577``` 11578 11579### getAccessibleGeolocation 11580 11581static getAccessibleGeolocation(origin: string, incognito?: boolean): Promise\<boolean> 11582 11583Obtains the geolocation permission status of the specified origin. This API uses a promise to return the result. 11584 11585**System capability**: SystemCapability.Web.Webview.Core 11586 11587**Parameters** 11588 11589| Name| Type| Mandatory| Description | 11590| ------ | -------- | ---- | -------------------- | 11591| origin | string | Yes | Index of the origin.| 11592| 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.| 11593 11594**Return value** 11595 11596| Type | Description | 11597| ---------------- | ------------------------------------------------------------ | 11598| 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.| 11599 11600**Error codes** 11601 11602For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11603 11604| ID| Error Message | 11605| -------- | ------------------------------------------------------ | 11606| 17100011 | Invalid origin. | 11607| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11608 11609**Example** 11610 11611```ts 11612// xxx.ets 11613import { webview } from '@kit.ArkWeb'; 11614import { BusinessError } from '@kit.BasicServicesKit'; 11615 11616@Entry 11617@Component 11618struct WebComponent { 11619 controller: webview.WebviewController = new webview.WebviewController(); 11620 origin: string = "file:///"; 11621 11622 build() { 11623 Column() { 11624 Button('getAccessibleGeolocation') 11625 .onClick(() => { 11626 try { 11627 webview.GeolocationPermissions.getAccessibleGeolocation(this.origin) 11628 .then(result => { 11629 console.log('getAccessibleGeolocationPromise result: ' + result); 11630 }).catch((error: BusinessError) => { 11631 console.error(`getAccessibleGeolocationPromise error, ErrorCode: ${error.code}, Message: ${error.message}`); 11632 }); 11633 } catch (error) { 11634 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11635 } 11636 }) 11637 Web({ src: 'www.example.com', controller: this.controller }) 11638 } 11639 } 11640} 11641``` 11642 11643### getStoredGeolocation 11644 11645static getStoredGeolocation(callback: AsyncCallback\<Array\<string>>, incognito?: boolean): void 11646 11647Obtains the geolocation permission status of all origins. This API uses an asynchronous callback to return the result. 11648 11649**System capability**: SystemCapability.Web.Webview.Core 11650 11651**Parameters** 11652 11653| Name | Type | Mandatory| Description | 11654| -------- | ---------------------------- | ---- | ---------------------------------------- | 11655| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return the geolocation permission status of all origins.| 11656| 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.| 11657 11658**Error codes** 11659 11660For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11661 11662| ID| Error Message | 11663| -------- | ------------------------------------------------------ | 11664| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11665 11666**Example** 11667 11668```ts 11669// xxx.ets 11670import { webview } from '@kit.ArkWeb'; 11671import { BusinessError } from '@kit.BasicServicesKit'; 11672 11673@Entry 11674@Component 11675struct WebComponent { 11676 controller: webview.WebviewController = new webview.WebviewController(); 11677 11678 build() { 11679 Column() { 11680 Button('getStoredGeolocation') 11681 .onClick(() => { 11682 try { 11683 webview.GeolocationPermissions.getStoredGeolocation((error, origins) => { 11684 if (error) { 11685 console.error(`getStoredGeolocationAsync error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11686 return; 11687 } 11688 let origins_str: string = origins.join(); 11689 console.log('getStoredGeolocationAsync origins: ' + origins_str); 11690 }); 11691 } catch (error) { 11692 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11693 } 11694 }) 11695 Web({ src: 'www.example.com', controller: this.controller }) 11696 } 11697 } 11698} 11699``` 11700 11701### getStoredGeolocation 11702 11703static getStoredGeolocation(incognito?: boolean): Promise\<Array\<string>> 11704 11705Obtains the geolocation permission status of all origins. This API uses a promise to return the result. 11706 11707**System capability**: SystemCapability.Web.Webview.Core 11708 11709**Parameters** 11710 11711| Name | Type | Mandatory| Description | 11712| -------- | ---------------------------- | ---- | ---------------------------------------- | 11713| 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.| 11714 11715**Return value** 11716 11717| Type | Description | 11718| ---------------------- | --------------------------------------------------------- | 11719| Promise\<Array\<string>> | Promise used to return the geolocation permission status of all origins.| 11720 11721**Error codes** 11722 11723For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11724 11725| ID| Error Message | 11726| -------- | ------------------------------------------------------ | 11727| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11728 11729**Example** 11730 11731```ts 11732// xxx.ets 11733import { webview } from '@kit.ArkWeb'; 11734import { BusinessError } from '@kit.BasicServicesKit'; 11735 11736@Entry 11737@Component 11738struct WebComponent { 11739 controller: webview.WebviewController = new webview.WebviewController(); 11740 11741 build() { 11742 Column() { 11743 Button('getStoredGeolocation') 11744 .onClick(() => { 11745 try { 11746 webview.GeolocationPermissions.getStoredGeolocation() 11747 .then(origins => { 11748 let origins_str: string = origins.join(); 11749 console.log('getStoredGeolocationPromise origins: ' + origins_str); 11750 }).catch((error: BusinessError) => { 11751 console.error(`getStoredGeolocationPromise error, ErrorCode: ${error.code}, Message: ${error.message}`); 11752 }); 11753 } catch (error) { 11754 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11755 } 11756 }) 11757 Web({ src: 'www.example.com', controller: this.controller }) 11758 } 11759 } 11760} 11761``` 11762 11763### deleteAllGeolocation 11764 11765static deleteAllGeolocation(incognito?: boolean): void 11766 11767Clears the geolocation permission status of all sources. 11768 11769**System capability**: SystemCapability.Web.Webview.Core 11770 11771**Parameters** 11772 11773| Name | Type | Mandatory| Description | 11774| -------- | ---------------------------- | ---- | ---------------------------------------- | 11775| 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.| 11776 11777**Example** 11778 11779```ts 11780// xxx.ets 11781import { webview } from '@kit.ArkWeb'; 11782import { BusinessError } from '@kit.BasicServicesKit'; 11783 11784@Entry 11785@Component 11786struct WebComponent { 11787 controller: webview.WebviewController = new webview.WebviewController(); 11788 11789 build() { 11790 Column() { 11791 Button('deleteAllGeolocation') 11792 .onClick(() => { 11793 try { 11794 webview.GeolocationPermissions.deleteAllGeolocation(); 11795 } catch (error) { 11796 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11797 } 11798 }) 11799 Web({ src: 'www.example.com', controller: this.controller }) 11800 } 11801 } 11802} 11803``` 11804## WebHeader 11805 11806Describes the request/response header returned by the **Web** component. 11807 11808**System capability**: SystemCapability.Web.Webview.Core 11809 11810| Name | Type | Readable| Writable|Description | 11811| ----------- | ------ | -----|------|------------------- | 11812| headerKey | string | Yes| Yes| Key of the request/response header. | 11813| headerValue | string | Yes| Yes| Value of the request/response header.| 11814 11815## RequestInfo<sup>12+</sup> 11816 11817Describes the information about the resource request sent by the **Web** component. 11818 11819**System capability**: SystemCapability.Web.Webview.Core 11820 11821| Name | Type | Readable| Writable|Description | 11822| ---------| ------ | -----|------|-------- | 11823| url | string | Yes| Yes| URL of the request. | 11824| method | string | Yes| Yes| Method of the request. | 11825| formData | string | Yes| Yes| Form data in the request body.| 11826 11827## WebHitTestType 11828 11829The [getLastHitTest](#getlasthittest18) API is used to indicate a cursor node. 11830 11831**System capability**: SystemCapability.Web.Webview.Core 11832 11833| Name | Value| Description | 11834| ------------- | -- |----------------------------------------- | 11835| EditText | 0 |Editable area. | 11836| Email | 1 |Email address. | 11837| HttpAnchor | 2 |Hyperlink, where **src** is **http**. | 11838| HttpAnchorImg | 3 |Image with a hyperlink, where **src** is http + HTML::img.| 11839| Img | 4 |HTML::img tag. | 11840| Map | 5 |Geographical address. | 11841| Phone | 6 |Phone number. | 11842| Unknown | 7 |Unknown content. | 11843 11844## SecurityLevel<sup>11+</sup> 11845 11846Defines the security level of the web page. 11847 11848**System capability**: SystemCapability.Web.Webview.Core 11849 11850| Name | Value| Description | 11851| ------------- | -- |----------------------------------------- | 11852| 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.| 11853| SECURE | 1 |The web page is secure, using the HTTPS protocol and a trusted certificate.| 11854| WARNING | 2 |The web page is insecure. A typical example is a web page that uses the HTTP or HTTPS protocol but an outdated TLS version.| 11855| DANGEROUS | 3 |The web page is dangerous. 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.| 11856 11857## HitTestValue 11858 11859Provides the element information of the area being clicked. For details about the sample code, see [getLastHitTest](#getlasthittest18). 11860 11861**System capability**: SystemCapability.Web.Webview.Core 11862 11863| Name| Type| Readable| Writable| Description| 11864| ---- | ---- | ---- | ---- |---- | 11865| type | [WebHitTestType](#webhittesttype) | Yes| Yes| Element type of the area being clicked.| 11866| 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.| 11867 11868## WebMessage 11869 11870type WebMessage = ArrayBuffer | string 11871 11872Describes the data types supported for [WebMessagePort](#webmessageport). 11873 11874**System capability**: SystemCapability.Web.Webview.Core 11875 11876| Type | Description | 11877| -------- | -------------------------------------- | 11878| string | String type.| 11879| ArrayBuffer | Binary type.| 11880 11881## JsMessageType<sup>10+</sup> 11882 11883Describes the type of the returned result of script execution using [runJavaScriptExt](#runjavascriptext10). 11884 11885**System capability**: SystemCapability.Web.Webview.Core 11886 11887| Name | Value| Description | 11888| ------------ | -- |--------------------------------- | 11889| NOT_SUPPORT | 0 |Unsupported data type.| 11890| STRING | 1 |String type.| 11891| NUMBER | 2 |Number type.| 11892| BOOLEAN | 3 |Boolean type.| 11893| ARRAY_BUFFER | 4 |Raw binary data buffer.| 11894| ARRAY | 5 |Array type.| 11895 11896## WebMessageType<sup>10+</sup> 11897 11898Describes the data type supported by the [webMessagePort](#webmessageport) API. 11899 11900**System capability**: SystemCapability.Web.Webview.Core 11901 11902| Name | Value| Description | 11903| ------------ | -- |------------------------------- | 11904| NOT_SUPPORT | 0 |Unsupported data type.| 11905| STRING | 1 |String type.| 11906| NUMBER | 2 |Number type.| 11907| BOOLEAN | 3 |Boolean type.| 11908| ARRAY_BUFFER | 4 |Raw binary data buffer.| 11909| ARRAY | 5 |Array type.| 11910| ERROR | 6 |Error object type.| 11911 11912## MediaPlaybackState<sup>12+</sup> 11913 11914Enumerates the playback states on the current web page. 11915 11916**System capability**: SystemCapability.Web.Webview.Core 11917 11918| Name | Value | Description | 11919| ------- | ---- | ------------------ | 11920| NONE | 0 | No audio or video playback is started on the page.| 11921| PLAYING | 1 | The audio and video on the page are being played.| 11922| PAUSED | 2 | The audio and video on the page are paused. | 11923| STOPPED | 3 | The audio and video on the page are stopped. | 11924 11925## RenderProcessMode<sup>12+</sup> 11926 11927Enumerates the ArkWeb render subprocess modes. 11928 11929**System capability**: SystemCapability.Web.Webview.Core 11930 11931| Name | Value| Description | 11932| ------------- | -- |----------------------------------------- | 11933| SINGLE | 0 |ArkWeb single render subprocess mode. In this mode, multiple **Web** components share one render subprocess.| 11934| MULTIPLE | 1 |ArkWeb multi-render subprocess mode. In this mode, each **Web** component has a rendering subprocess.| 11935 11936 11937## JsMessageExt<sup>10+</sup> 11938 11939Implements the **JsMessageExt** data object that is returned after script execution using the [runJavaScriptExt](#runjavascriptext10) API. 11940 11941### getType<sup>10+</sup> 11942 11943getType(): JsMessageType 11944 11945Obtains the type of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 11946 11947**System capability**: SystemCapability.Web.Webview.Core 11948 11949**Return value** 11950 11951| Type | Description | 11952| --------------| --------------------------------------------------------- | 11953| [JsMessageType](#jsmessagetype10) | Type of the data object that is returned after script execution using the [runJavaScriptExt](#runjavascriptext10) API.| 11954 11955### getString<sup>10+</sup> 11956 11957getString(): string 11958 11959Obtains string-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 11960 11961**System capability**: SystemCapability.Web.Webview.Core 11962 11963**Return value** 11964 11965| Type | Description | 11966| --------------| ------------- | 11967| string | Data of the string type.| 11968 11969**Error codes** 11970 11971For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11972 11973| ID| Error Message | 11974| -------- | ------------------------------------- | 11975| 17100014 | The type and value of the message do not match. | 11976 11977### getNumber<sup>10+</sup> 11978 11979getNumber(): number 11980 11981Obtains number-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 11982 11983**System capability**: SystemCapability.Web.Webview.Core 11984 11985**Return value** 11986 11987| Type | Description | 11988| --------------| ------------- | 11989| number | Data of the number type.| 11990 11991**Error codes** 11992 11993For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11994 11995| ID| Error Message | 11996| -------- | ------------------------------------- | 11997| 17100014 | The type and value of the message do not match. | 11998 11999### getBoolean<sup>10+</sup> 12000 12001getBoolean(): boolean 12002 12003Obtains Boolean-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 12004 12005**System capability**: SystemCapability.Web.Webview.Core 12006 12007**Return value** 12008 12009| Type | Description | 12010| --------------| ------------- | 12011| boolean | Data of the Boolean type.| 12012 12013**Error codes** 12014 12015For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12016 12017| ID| Error Message | 12018| -------- | ------------------------------------- | 12019| 17100014 | The type and value of the message do not match. | 12020 12021### getArrayBuffer<sup>10+</sup> 12022 12023getArrayBuffer(): ArrayBuffer 12024 12025Obtains raw binary data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 12026 12027**System capability**: SystemCapability.Web.Webview.Core 12028 12029**Return value** 12030 12031| Type | Description | 12032| --------------| ------------- | 12033| ArrayBuffer | Raw binary data.| 12034 12035**Error codes** 12036 12037For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12038 12039| ID| Error Message | 12040| -------- | ------------------------------------- | 12041| 17100014 | The type and value of the message do not match. | 12042 12043### getArray<sup>10+</sup> 12044 12045getArray(): Array\<string | number | boolean\> 12046 12047Obtains array-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 12048 12049**System capability**: SystemCapability.Web.Webview.Core 12050 12051**Return value** 12052 12053| Type | Description | 12054| --------------| ------------- | 12055| Array\<string \| number \| boolean\> | Data of the array type.| 12056 12057**Error codes** 12058 12059For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12060 12061| ID| Error Message | 12062| -------- | ------------------------------------- | 12063| 17100014 | The type and value of the message do not match. | 12064 12065## WebMessageExt<sup>10+</sup> 12066 12067Represents a data object received and sent through the [webMessagePort](#webmessageport) API. 12068 12069### getType<sup>10+</sup> 12070 12071getType(): WebMessageType 12072 12073Obtains the type of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12074 12075**System capability**: SystemCapability.Web.Webview.Core 12076 12077**Return value** 12078 12079| Type | Description | 12080| --------------| --------------------------------------------------------- | 12081| [WebMessageType](#webmessagetype10) | Data type supported by the [webMessagePort](#webmessageport) API.| 12082 12083### getString<sup>10+</sup> 12084 12085getString(): string 12086 12087Obtains string-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12088 12089**System capability**: SystemCapability.Web.Webview.Core 12090 12091**Return value** 12092 12093| Type | Description | 12094| --------------| ------------- | 12095| string | Data of the string type.| 12096 12097**Error codes** 12098 12099For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12100 12101| ID| Error Message | 12102| -------- | ------------------------------------- | 12103| 17100014 | The type and value of the message do not match. | 12104 12105### getNumber<sup>10+</sup> 12106 12107getNumber(): number 12108 12109Obtains number-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12110 12111**System capability**: SystemCapability.Web.Webview.Core 12112 12113**Return value** 12114 12115| Type | Description | 12116| --------------| ------------- | 12117| number | Data of the number type.| 12118 12119**Error codes** 12120 12121For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12122 12123| ID| Error Message | 12124| -------- | ------------------------------------- | 12125| 17100014 | The type and value of the message do not match. | 12126 12127### getBoolean<sup>10+</sup> 12128 12129getBoolean(): boolean 12130 12131Obtains Boolean-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12132 12133**System capability**: SystemCapability.Web.Webview.Core 12134 12135**Return value** 12136 12137| Type | Description | 12138| --------------| ------------- | 12139| boolean | Data of the Boolean type.| 12140 12141**Error codes** 12142 12143For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12144 12145| ID| Error Message | 12146| -------- | ------------------------------------- | 12147| 17100014 | The type and value of the message do not match. | 12148 12149### getArrayBuffer<sup>10+</sup> 12150 12151getArrayBuffer(): ArrayBuffer 12152 12153Obtains raw binary data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12154 12155**System capability**: SystemCapability.Web.Webview.Core 12156 12157**Return value** 12158 12159| Type | Description | 12160| --------------| ------------- | 12161| ArrayBuffer | Raw binary data.| 12162 12163**Error codes** 12164 12165For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12166 12167| ID| Error Message | 12168| -------- | ------------------------------------- | 12169| 17100014 | The type and value of the message do not match. | 12170 12171### getArray<sup>10+</sup> 12172 12173getArray(): Array\<string | number | boolean\> 12174 12175Obtains array-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12176 12177**System capability**: SystemCapability.Web.Webview.Core 12178 12179**Return value** 12180 12181| Type | Description | 12182| --------------| ------------- | 12183| Array\<string \| number \| boolean\> | Data of the array type.| 12184 12185**Error codes** 12186 12187For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12188 12189| ID| Error Message | 12190| -------- | ------------------------------------- | 12191| 17100014 | The type and value of the message do not match. | 12192 12193### getError<sup>10+</sup> 12194 12195getError(): Error 12196 12197Obtains the error-object-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12198 12199**System capability**: SystemCapability.Web.Webview.Core 12200 12201**Return value** 12202 12203| Type | Description | 12204| --------------| ------------- | 12205| Error | Data of the error object type.| 12206 12207**Error codes** 12208 12209For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12210 12211| ID| Error Message | 12212| -------- | ------------------------------------- | 12213| 17100014 | The type and value of the message do not match. | 12214 12215### setType<sup>10+</sup> 12216 12217setType(type: WebMessageType): void 12218 12219Sets the type for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12220 12221**System capability**: SystemCapability.Web.Webview.Core 12222 12223**Parameters** 12224 12225| Name| Type | Mandatory| Description | 12226| ------ | ------ | ---- | ---------------------- | 12227| type | [WebMessageType](#webmessagetype10) | Yes | Data type supported by the [webMessagePort](#webmessageport) API.| 12228 12229**Error codes** 12230 12231| ID| Error Message | 12232| -------- | ------------------------------------- | 12233| 17100014 | The type and value of the message do not match. | 12234| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12235 12236### setString<sup>10+</sup> 12237 12238setString(message: string): void 12239 12240Sets the string-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12241 12242**System capability**: SystemCapability.Web.Webview.Core 12243 12244**Parameters** 12245 12246| Name| Type | Mandatory| Description | 12247| ------ | ------ | ---- | -------------------- | 12248| message | string | Yes | String type.| 12249 12250**Error codes** 12251 12252| ID| Error Message | 12253| -------- | ------------------------------------- | 12254| 17100014 | The type and value of the message do not match. | 12255| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12256 12257### setNumber<sup>10+</sup> 12258 12259setNumber(message: number): void 12260 12261Sets the number-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12262 12263**System capability**: SystemCapability.Web.Webview.Core 12264 12265**Parameters** 12266 12267| Name| Type | Mandatory| Description | 12268| ------ | ------ | ---- | -------------------- | 12269| message | number | Yes | Data of the number type.| 12270 12271**Error codes** 12272 12273| ID| Error Message | 12274| -------- | ------------------------------------- | 12275| 17100014 | The type and value of the message do not match. | 12276| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12277 12278### setBoolean<sup>10+</sup> 12279 12280setBoolean(message: boolean): void 12281 12282Sets the Boolean-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12283 12284**System capability**: SystemCapability.Web.Webview.Core 12285 12286**Parameters** 12287 12288| Name| Type | Mandatory| Description | 12289| ------ | ------ | ---- | -------------------- | 12290| message | boolean | Yes | Data of the Boolean type.| 12291 12292**Error codes** 12293 12294| ID| Error Message | 12295| -------- | ------------------------------------- | 12296| 17100014 | The type and value of the message do not match. | 12297| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12298 12299### setArrayBuffer<sup>10+</sup> 12300 12301setArrayBuffer(message: ArrayBuffer): void 12302 12303Sets the raw binary data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12304 12305**System capability**: SystemCapability.Web.Webview.Core 12306 12307**Parameters** 12308 12309| Name| Type | Mandatory| Description | 12310| ------ | ------ | ---- | -------------------- | 12311| message | ArrayBuffer | Yes | Raw binary data.| 12312 12313**Error codes** 12314 12315For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12316 12317| ID| Error Message | 12318| -------- | ------------------------------------- | 12319| 17100014 | The type and value of the message do not match. | 12320| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12321 12322### setArray<sup>10+</sup> 12323 12324setArray(message: Array\<string | number | boolean\>): void 12325 12326Sets the array-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12327 12328**System capability**: SystemCapability.Web.Webview.Core 12329 12330**Parameters** 12331 12332| Name| Type | Mandatory| Description | 12333| ------ | ------ | ---- | -------------------- | 12334| message | Array\<string \| number \| boolean\> | Yes | Data of the array type.| 12335 12336**Error codes** 12337 12338For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12339 12340| ID| Error Message | 12341| -------- | ------------------------------------- | 12342| 17100014 | The type and value of the message do not match. | 12343| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12344 12345### setError<sup>10+</sup> 12346 12347setError(message: Error): void 12348 12349Sets the error-object-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12350 12351**System capability**: SystemCapability.Web.Webview.Core 12352 12353**Parameters** 12354 12355| Name| Type | Mandatory| Description | 12356| ------ | ------ | ---- | -------------------- | 12357| message | Error | Yes | Data of the error object type.| 12358 12359**Error codes** 12360 12361For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12362 12363| ID| Error Message | 12364| -------- | ------------------------------------- | 12365| 17100014 | The type and value of the message do not match. | 12366| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12367 12368## WebStorageOrigin 12369 12370Provides usage information of the Web SQL Database. 12371 12372**System capability**: SystemCapability.Web.Webview.Core 12373 12374| Name | Type | Readable| Writable| Description| 12375| ------ | ------ | ---- | ---- | ---- | 12376| origin | string | Yes | Yes| Index of the origin.| 12377| usage | number | Yes | Yes| Storage usage of the origin. | 12378| quota | number | Yes | Yes| Storage quota of the origin. | 12379 12380## BackForwardList 12381 12382Provides the historical information list of the current webview. 12383 12384**System capability**: SystemCapability.Web.Webview.Core 12385 12386| Name | Type | Readable| Writable| Description | 12387| ------------ | ------ | ---- | ---- | ------------------------------------------------------------ | 12388| currentIndex | number | Yes | Yes | Index of the current page in the page history stack. | 12389| 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.| 12390 12391### getItemAtIndex 12392 12393getItemAtIndex(index: number): HistoryItem 12394 12395Obtains the page record with the specified index in the history stack. 12396 12397**System capability**: SystemCapability.Web.Webview.Core 12398 12399**Parameters** 12400 12401| Name| Type | Mandatory| Description | 12402| ------ | ------ | ---- | ---------------------- | 12403| index | number | Yes | Index of the target page record in the history stack.| 12404 12405**Return value** 12406 12407| Type | Description | 12408| --------------------------- | ------------ | 12409| [HistoryItem](#historyitem) | Historical page record.| 12410 12411**Error codes** 12412 12413For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12414 12415| ID| Error Message | 12416| -------- | ------------------------------------------------------ | 12417| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12418 12419**Example** 12420 12421```ts 12422// xxx.ets 12423import { webview } from '@kit.ArkWeb'; 12424import { BusinessError } from '@kit.BasicServicesKit'; 12425import { image } from '@kit.ImageKit'; 12426 12427@Entry 12428@Component 12429struct WebComponent { 12430 controller: webview.WebviewController = new webview.WebviewController(); 12431 @State icon: image.PixelMap | undefined = undefined; 12432 12433 build() { 12434 Column() { 12435 Button('getBackForwardEntries') 12436 .onClick(() => { 12437 try { 12438 let list = this.controller.getBackForwardEntries(); 12439 let historyItem = list.getItemAtIndex(list.currentIndex); 12440 console.log("HistoryItem: " + JSON.stringify(historyItem)); 12441 this.icon = historyItem.icon; 12442 } catch (error) { 12443 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12444 } 12445 }) 12446 Web({ src: 'www.example.com', controller: this.controller }) 12447 } 12448 } 12449} 12450``` 12451 12452## HistoryItem 12453 12454Describes a historical page record. 12455 12456**System capability**: SystemCapability.Web.Webview.Core 12457 12458| Name | Type | Readable| Writable| Description | 12459| ------------- | -------------------------------------- | ---- | ---- | ---------------------------- | 12460| icon | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | No | **PixelMap** object of the icon on the historical page.| 12461| historyUrl | string | Yes | Yes | URL of the historical page. | 12462| historyRawUrl | string | Yes | Yes | Original URL of the historical page. | 12463| title | string | Yes | Yes | Title of the historical page. | 12464 12465## WebCustomScheme 12466 12467Defines a custom URL scheme. 12468 12469**System capability**: SystemCapability.Web.Webview.Core 12470 12471| Name | Type | Readable| Writable| Description | 12472| -------------- | --------- | ---- | ---- | ---------------------------- | 12473| 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. | 12474| isSupportCORS | boolean | Yes | Yes | Whether to support cross-origin resource sharing (CORS). | 12475| isSupportFetch | boolean | Yes | Yes | Whether to support fetch requests. | 12476| 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. | 12477| isLocal<sup>12+</sup> | boolean | Yes | Yes | Whether the scheme is treated with the same security rules as those applied to file URLs. | 12478| 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. | 12479| isSecure<sup>12+</sup> | boolean | Yes | Yes | Whether the scheme is treated with the same security rules as those applied to HTTPS URLs. | 12480| 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**. | 12481| isCodeCacheSupported<sup>12+</sup> | boolean | Yes | Yes | Whether JavaScript resources loaded with the scheme can be used to create a code cache. The default value is **false**. | 12482 12483## SecureDnsMode<sup>10+</sup> 12484 12485Describes the mode in which the **Web** component uses HTTPDNS. 12486 12487**System capability**: SystemCapability.Web.Webview.Core 12488 12489| Name | Value| Description | 12490| ------------- | -- |----------------------------------------- | 12491| OFF | 0 |HTTPDNS is not used. This value can be used to revoke the previously used HTTPDNS configuration.| 12492| 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.| 12493| SECURE_ONLY | 2 |The specified HTTPDNS server is forcibly used for DNS resolution.| 12494 12495## WebDownloadState<sup>11+</sup> 12496 12497Describes the state of a download task. 12498 12499**System capability**: SystemCapability.Web.Webview.Core 12500 12501| Name | Value| Description | 12502| ------------- | -- |----------------------------------------- | 12503| IN_PROGRESS | 0 |The download task is in progress.| 12504| COMPLETED | 1 |The download task is completed.| 12505| CANCELED | 2 |The download task has been canceled.| 12506| INTERRUPTED | 3 |The download task is interrupted.| 12507| PENDING | 4 |The download task is pending.| 12508| PAUSED | 5 |The download task is paused.| 12509| UNKNOWN | 6 |The state of the download task is unknown.| 12510 12511## WebDownloadErrorCode<sup>11+</sup> 12512 12513Describes the download task error code. 12514 12515**System capability**: SystemCapability.Web.Webview.Core 12516 12517| Name | Value| Description | 12518| ------------- | -- |----------------------------------------- | 12519| ERROR_UNKNOWN | 0 |Unknown error.| 12520| FILE_FAILED | 1 | Failed to operate the file.| 12521| FILE_ACCESS_DENIED | 2 | No permission to access the file.| 12522| FILE_NO_SPACE | 3 | The disk space is insufficient.| 12523| FILE_NAME_TOO_LONG | 5 | The file name is too long.| 12524| FILE_TOO_LARGE | 6 | The file is too large.| 12525| FILE_TRANSIENT_ERROR | 10 | Some temporary issues occur, such as insufficient memory, files in use, and too many files open at the same time.| 12526| FILE_BLOCKED | 11 | Access to the file is blocked due to certain local policies.| 12527| FILE_TOO_SHORT | 13 | The file to resume downloading is not long enough. It may not exist.| 12528| FILE_HASH_MISMATCH | 14 | Hash mismatch.| 12529| FILE_SAME_AS_SOURCE | 15 | The file already exists.| 12530| NETWORK_FAILED | 20 | Common network error.| 12531| NETWORK_TIMEOUT | 21 | Network connection timeout.| 12532| NETWORK_DISCONNECTED | 22 | Network disconnected.| 12533| NETWORK_SERVER_DOWN | 23 | The server is shut down.| 12534| NETWORK_INVALID_REQUEST | 24 | Invalid network request. The request may be redirected to an unsupported scheme or an invalid URL.| 12535| SERVER_FAILED | 30 | The server returns a general error.| 12536| SERVER_NO_RANGE | 31 | The server does not support the range request.| 12537| SERVER_BAD_CONTENT | 33 | The server does not have the requested data.| 12538| SERVER_UNAUTHORIZED | 34 | The file cannot be downloaded from the server.| 12539| SERVER_CERT_PROBLEM | 35 | The server certificate is incorrect.| 12540| SERVER_FORBIDDEN | 36 | The access to the server is forbidden.| 12541| SERVER_UNREACHABLE | 37 | The server cannot be accessed.| 12542| SERVER_CONTENT_LENGTH_MISMATCH | 38 | The received data does not match the content length.| 12543| SERVER_CROSS_ORIGIN_REDIRECT | 39 | An unexpected cross-site redirection occurs.| 12544| USER_CANCELED | 40 | The user cancels the download.| 12545| USER_SHUTDOWN | 41 | The user closes the application.| 12546| CRASH | 50 | The application crashes.| 12547 12548## WebDownloadItem<sup>11+</sup> 12549 12550 Implements a **WebDownloadItem** object. You can use this object to perform operations on the corresponding download task. 12551 12552> **NOTE** 12553> 12554> During the download, the download process is notified to the user through **WebDownloadDelegate**. The user can operate the download task through the **WebDownloadItem** parameter. 12555 12556### getGuid<sup>11+</sup> 12557 12558getGuid(): string 12559 12560Obtains the unique ID of this download task. 12561 12562**System capability**: SystemCapability.Web.Webview.Core 12563 12564**Return value** 12565 12566| Type | Description | 12567| ------ | ------------------------- | 12568| string | Unique ID of the download task.| 12569 12570**Example** 12571 12572```ts 12573// xxx.ets 12574import { webview } from '@kit.ArkWeb'; 12575import { BusinessError } from '@kit.BasicServicesKit'; 12576 12577@Entry 12578@Component 12579struct WebComponent { 12580 controller: webview.WebviewController = new webview.WebviewController(); 12581 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12582 12583 build() { 12584 Column() { 12585 Button('setDownloadDelegate') 12586 .onClick(() => { 12587 try { 12588 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12589 console.log("will start a download."); 12590 // Pass in a download path and start the download. 12591 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12592 }) 12593 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12594 console.log("download update guid: " + webDownloadItem.getGuid()); 12595 }) 12596 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12597 console.log("download failed guid: " + webDownloadItem.getGuid()); 12598 }) 12599 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12600 console.log("download finish guid: " + webDownloadItem.getGuid()); 12601 }) 12602 this.controller.setDownloadDelegate(this.delegate); 12603 } catch (error) { 12604 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12605 } 12606 }) 12607 Button('startDownload') 12608 .onClick(() => { 12609 try { 12610 this.controller.startDownload('https://www.example.com'); 12611 } catch (error) { 12612 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12613 } 12614 }) 12615 Web({ src: 'www.example.com', controller: this.controller }) 12616 } 12617 } 12618} 12619``` 12620 12621### getCurrentSpeed<sup>11+</sup> 12622 12623getCurrentSpeed(): number 12624 12625Obtains the download speed, in bytes per second. 12626 12627**System capability**: SystemCapability.Web.Webview.Core 12628 12629**Return value** 12630 12631| Type | Description | 12632| ------ | ------------------------- | 12633| number | Download speed, in bytes per second.| 12634 12635**Example** 12636 12637```ts 12638// xxx.ets 12639import { webview } from '@kit.ArkWeb'; 12640import { BusinessError } from '@kit.BasicServicesKit'; 12641 12642@Entry 12643@Component 12644struct WebComponent { 12645 controller: webview.WebviewController = new webview.WebviewController(); 12646 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12647 12648 build() { 12649 Column() { 12650 Button('setDownloadDelegate') 12651 .onClick(() => { 12652 try { 12653 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12654 console.log("will start a download."); 12655 // Pass in a download path and start the download. 12656 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12657 }) 12658 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12659 console.log("download update current speed: " + webDownloadItem.getCurrentSpeed()); 12660 }) 12661 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12662 console.log("download failed guid: " + webDownloadItem.getGuid()); 12663 }) 12664 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12665 console.log("download finish guid: " + webDownloadItem.getGuid()); 12666 }) 12667 this.controller.setDownloadDelegate(this.delegate); 12668 } catch (error) { 12669 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12670 } 12671 }) 12672 Button('startDownload') 12673 .onClick(() => { 12674 try { 12675 this.controller.startDownload('https://www.example.com'); 12676 } catch (error) { 12677 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12678 } 12679 }) 12680 Web({ src: 'www.example.com', controller: this.controller }) 12681 } 12682 } 12683} 12684``` 12685 12686### getPercentComplete<sup>11+</sup> 12687 12688getPercentComplete(): number 12689 12690Obtains the download progress. The value **100** indicates that the download is complete. 12691 12692**System capability**: SystemCapability.Web.Webview.Core 12693 12694**Return value** 12695 12696| Type | Description | 12697| ------ | ------------------------- | 12698| number | Download progress. The value **100** indicates that the download is complete.| 12699 12700**Example** 12701 12702```ts 12703// xxx.ets 12704import { webview } from '@kit.ArkWeb'; 12705import { BusinessError } from '@kit.BasicServicesKit'; 12706 12707@Entry 12708@Component 12709struct WebComponent { 12710 controller: webview.WebviewController = new webview.WebviewController(); 12711 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12712 12713 build() { 12714 Column() { 12715 Button('setDownloadDelegate') 12716 .onClick(() => { 12717 try { 12718 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12719 console.log("will start a download."); 12720 // Pass in a download path and start the download. 12721 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12722 }) 12723 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12724 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12725 }) 12726 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12727 console.log("download failed guid: " + webDownloadItem.getGuid()); 12728 }) 12729 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12730 console.log("download finish guid: " + webDownloadItem.getGuid()); 12731 }) 12732 this.controller.setDownloadDelegate(this.delegate); 12733 } catch (error) { 12734 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12735 } 12736 }) 12737 Button('startDownload') 12738 .onClick(() => { 12739 try { 12740 this.controller.startDownload('https://www.example.com'); 12741 } catch (error) { 12742 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12743 } 12744 }) 12745 Web({ src: 'www.example.com', controller: this.controller }) 12746 } 12747 } 12748} 12749``` 12750 12751### getTotalBytes<sup>11+</sup> 12752 12753getTotalBytes(): number 12754 12755Obtains the total length of the file to be downloaded. 12756 12757**System capability**: SystemCapability.Web.Webview.Core 12758 12759**Return value** 12760 12761| Type | Description | 12762| ------ | ------------------------- | 12763| number | Total length of the file to be downloaded.| 12764 12765**Example** 12766 12767```ts 12768// xxx.ets 12769import { webview } from '@kit.ArkWeb'; 12770import { BusinessError } from '@kit.BasicServicesKit'; 12771 12772@Entry 12773@Component 12774struct WebComponent { 12775 controller: webview.WebviewController = new webview.WebviewController(); 12776 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12777 12778 build() { 12779 Column() { 12780 Button('setDownloadDelegate') 12781 .onClick(() => { 12782 try { 12783 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12784 console.log("will start a download."); 12785 // Pass in a download path and start the download. 12786 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12787 }) 12788 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12789 console.log("download update total bytes: " + webDownloadItem.getTotalBytes()); 12790 }) 12791 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12792 console.log("download failed guid: " + webDownloadItem.getGuid()); 12793 }) 12794 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12795 console.log("download finish guid: " + webDownloadItem.getGuid()); 12796 }) 12797 this.controller.setDownloadDelegate(this.delegate); 12798 } catch (error) { 12799 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12800 } 12801 }) 12802 Button('startDownload') 12803 .onClick(() => { 12804 try { 12805 this.controller.startDownload('https://www.example.com'); 12806 } catch (error) { 12807 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12808 } 12809 }) 12810 Web({ src: 'www.example.com', controller: this.controller }) 12811 } 12812 } 12813} 12814``` 12815 12816### getState<sup>11+</sup> 12817 12818getState(): WebDownloadState 12819 12820Obtains the download state. 12821 12822**System capability**: SystemCapability.Web.Webview.Core 12823 12824**Return value** 12825 12826| Type | Description | 12827| ------ | ------------------------- | 12828| [WebDownloadState](#webdownloadstate11) | Download state.| 12829 12830**Example** 12831 12832```ts 12833// xxx.ets 12834import { webview } from '@kit.ArkWeb'; 12835import { BusinessError } from '@kit.BasicServicesKit'; 12836 12837@Entry 12838@Component 12839struct WebComponent { 12840 controller: webview.WebviewController = new webview.WebviewController(); 12841 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12842 12843 build() { 12844 Column() { 12845 Button('setDownloadDelegate') 12846 .onClick(() => { 12847 try { 12848 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12849 console.log("will start a download."); 12850 // Pass in a download path and start the download. 12851 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12852 }) 12853 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12854 console.log("download update download state: " + webDownloadItem.getState()); 12855 }) 12856 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12857 console.log("download failed guid: " + webDownloadItem.getGuid()); 12858 }) 12859 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12860 console.log("download finish guid: " + webDownloadItem.getGuid()); 12861 }) 12862 this.controller.setDownloadDelegate(this.delegate); 12863 } catch (error) { 12864 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12865 } 12866 }) 12867 Button('startDownload') 12868 .onClick(() => { 12869 try { 12870 this.controller.startDownload('https://www.example.com'); 12871 } catch (error) { 12872 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12873 } 12874 }) 12875 Web({ src: 'www.example.com', controller: this.controller }) 12876 } 12877 } 12878} 12879``` 12880 12881### getLastErrorCode<sup>11+</sup> 12882 12883getLastErrorCode(): WebDownloadErrorCode 12884 12885Obtains the download error code. 12886 12887**System capability**: SystemCapability.Web.Webview.Core 12888 12889**Return value** 12890 12891| Type | Description | 12892| ------ | ------------------------- | 12893| [WebDownloadErrorCode](#webdownloaderrorcode11) | Error code returned when the download error occurs.| 12894 12895**Example** 12896 12897```ts 12898// xxx.ets 12899import { webview } from '@kit.ArkWeb'; 12900import { BusinessError } from '@kit.BasicServicesKit'; 12901 12902@Entry 12903@Component 12904struct WebComponent { 12905 controller: webview.WebviewController = new webview.WebviewController(); 12906 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12907 12908 build() { 12909 Column() { 12910 Button('setDownloadDelegate') 12911 .onClick(() => { 12912 try { 12913 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12914 console.log("will start a download."); 12915 // Pass in a download path and start the download. 12916 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12917 }) 12918 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12919 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12920 }) 12921 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12922 console.log("download failed guid: " + webDownloadItem.getGuid()); 12923 console.log("download error code: " + webDownloadItem.getLastErrorCode()); 12924 }) 12925 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12926 console.log("download finish guid: " + webDownloadItem.getGuid()); 12927 }) 12928 this.controller.setDownloadDelegate(this.delegate); 12929 } catch (error) { 12930 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12931 } 12932 }) 12933 Button('startDownload') 12934 .onClick(() => { 12935 try { 12936 this.controller.startDownload('https://www.example.com'); 12937 } catch (error) { 12938 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12939 } 12940 }) 12941 Web({ src: 'www.example.com', controller: this.controller }) 12942 } 12943 } 12944} 12945``` 12946 12947### getMethod<sup>11+</sup> 12948 12949getMethod(): string 12950 12951Obtains the request mode of this download task. 12952 12953**System capability**: SystemCapability.Web.Webview.Core 12954 12955**Return value** 12956 12957| Type | Description | 12958| ------ | ------------------------- | 12959| string | Request mode of the download task.| 12960 12961**Example** 12962 12963```ts 12964// xxx.ets 12965import { webview } from '@kit.ArkWeb'; 12966import { BusinessError } from '@kit.BasicServicesKit'; 12967 12968@Entry 12969@Component 12970struct WebComponent { 12971 controller: webview.WebviewController = new webview.WebviewController(); 12972 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12973 12974 build() { 12975 Column() { 12976 Button('setDownloadDelegate') 12977 .onClick(() => { 12978 try { 12979 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12980 console.log("Download will start. Method:" + webDownloadItem.getMethod()); 12981 // Pass in a download path and start the download. 12982 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12983 }) 12984 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12985 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12986 }) 12987 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12988 console.log("download failed guid: " + webDownloadItem.getGuid()); 12989 }) 12990 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12991 console.log("download finish guid: " + webDownloadItem.getGuid()); 12992 }) 12993 this.controller.setDownloadDelegate(this.delegate); 12994 } catch (error) { 12995 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12996 } 12997 }) 12998 Button('startDownload') 12999 .onClick(() => { 13000 try { 13001 this.controller.startDownload('https://www.example.com'); 13002 } catch (error) { 13003 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13004 } 13005 }) 13006 Web({ src: 'www.example.com', controller: this.controller }) 13007 } 13008 } 13009} 13010``` 13011 13012### getMimeType<sup>11+</sup> 13013 13014getMimeType(): string 13015 13016Obtains 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). 13017 13018**System capability**: SystemCapability.Web.Webview.Core 13019 13020**Return value** 13021 13022| Type | Description | 13023| ------ | ------------------------- | 13024| string | MIME type (for example, audio/ogg for a sound file, and image/png for an image file).| 13025 13026**Example** 13027 13028```ts 13029// xxx.ets 13030import { webview } from '@kit.ArkWeb'; 13031import { BusinessError } from '@kit.BasicServicesKit'; 13032 13033@Entry 13034@Component 13035struct WebComponent { 13036 controller: webview.WebviewController = new webview.WebviewController(); 13037 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13038 13039 build() { 13040 Column() { 13041 Button('setDownloadDelegate') 13042 .onClick(() => { 13043 try { 13044 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13045 console.log("Download will start. MIME type:" + webDownloadItem.getMimeType()); 13046 // Pass in a download path and start the download. 13047 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13048 }) 13049 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13050 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13051 }) 13052 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13053 console.log("download failed guid: " + webDownloadItem.getGuid()); 13054 }) 13055 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13056 console.log("download finish guid: " + webDownloadItem.getGuid()); 13057 }) 13058 this.controller.setDownloadDelegate(this.delegate); 13059 } catch (error) { 13060 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13061 } 13062 }) 13063 Button('startDownload') 13064 .onClick(() => { 13065 try { 13066 this.controller.startDownload('https://www.example.com'); 13067 } catch (error) { 13068 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13069 } 13070 }) 13071 Web({ src: 'www.example.com', controller: this.controller }) 13072 } 13073 } 13074} 13075``` 13076 13077### getUrl<sup>11+</sup> 13078 13079getUrl(): string 13080 13081Obtains the download request URL. 13082 13083**System capability**: SystemCapability.Web.Webview.Core 13084 13085**Return value** 13086 13087| Type | Description | 13088| ------ | ------------------------- | 13089| string | Download request URL.| 13090 13091**Example** 13092 13093```ts 13094// xxx.ets 13095import { webview } from '@kit.ArkWeb'; 13096import { BusinessError } from '@kit.BasicServicesKit'; 13097 13098@Entry 13099@Component 13100struct WebComponent { 13101 controller: webview.WebviewController = new webview.WebviewController(); 13102 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13103 13104 build() { 13105 Column() { 13106 Button('setDownloadDelegate') 13107 .onClick(() => { 13108 try { 13109 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13110 console.log("will start a download, url:" + webDownloadItem.getUrl()); 13111 // Pass in a download path and start the download. 13112 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13113 }) 13114 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13115 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13116 }) 13117 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13118 console.log("download failed guid: " + webDownloadItem.getGuid()); 13119 }) 13120 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13121 console.log("download finish guid: " + webDownloadItem.getGuid()); 13122 }) 13123 this.controller.setDownloadDelegate(this.delegate); 13124 } catch (error) { 13125 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13126 } 13127 }) 13128 Button('startDownload') 13129 .onClick(() => { 13130 try { 13131 this.controller.startDownload('https://www.example.com'); 13132 } catch (error) { 13133 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13134 } 13135 }) 13136 Web({ src: 'www.example.com', controller: this.controller }) 13137 } 13138 } 13139} 13140``` 13141 13142### getSuggestedFileName<sup>11+</sup> 13143 13144getSuggestedFileName(): string 13145 13146Obtains the suggested file name for this download task. 13147 13148**System capability**: SystemCapability.Web.Webview.Core 13149 13150**Return value** 13151 13152| Type | Description | 13153| ------ | ------------------------- | 13154| string | Suggested file name.| 13155 13156**Example** 13157 13158```ts 13159// xxx.ets 13160import { webview } from '@kit.ArkWeb'; 13161import { BusinessError } from '@kit.BasicServicesKit'; 13162 13163@Entry 13164@Component 13165struct WebComponent { 13166 controller: webview.WebviewController = new webview.WebviewController(); 13167 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13168 13169 build() { 13170 Column() { 13171 Button('setDownloadDelegate') 13172 .onClick(() => { 13173 try { 13174 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13175 console.log("will start a download, suggest name:" + webDownloadItem.getSuggestedFileName()); 13176 // Pass in a download path and start the download. 13177 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13178 }) 13179 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13180 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13181 }) 13182 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13183 console.log("download failed guid: " + webDownloadItem.getGuid()); 13184 }) 13185 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13186 console.log("download finish guid: " + webDownloadItem.getGuid()); 13187 }) 13188 this.controller.setDownloadDelegate(this.delegate); 13189 } catch (error) { 13190 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13191 } 13192 }) 13193 Button('startDownload') 13194 .onClick(() => { 13195 try { 13196 this.controller.startDownload('https://www.example.com'); 13197 } catch (error) { 13198 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13199 } 13200 }) 13201 Web({ src: 'www.example.com', controller: this.controller }) 13202 } 13203 } 13204} 13205``` 13206 13207### getReceivedBytes<sup>11+</sup> 13208 13209getReceivedBytes(): number 13210 13211Obtains the number of received bytes. 13212 13213**System capability**: SystemCapability.Web.Webview.Core 13214 13215**Return value** 13216 13217| Type | Description | 13218| ------ | ------------------------- | 13219| number | Number of received bytes.| 13220 13221**Example** 13222 13223```ts 13224// xxx.ets 13225import { webview } from '@kit.ArkWeb'; 13226import { BusinessError } from '@kit.BasicServicesKit'; 13227 13228@Entry 13229@Component 13230struct WebComponent { 13231 controller: webview.WebviewController = new webview.WebviewController(); 13232 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13233 13234 build() { 13235 Column() { 13236 Button('setDownloadDelegate') 13237 .onClick(() => { 13238 try { 13239 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13240 console.log("will start a download."); 13241 // Pass in a download path and start the download. 13242 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13243 }) 13244 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13245 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13246 console.log("download update received bytes: " + webDownloadItem.getReceivedBytes()); 13247 }) 13248 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13249 console.log("download failed guid: " + webDownloadItem.getGuid()); 13250 }) 13251 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13252 console.log("download finish guid: " + webDownloadItem.getGuid()); 13253 }) 13254 this.controller.setDownloadDelegate(this.delegate); 13255 } catch (error) { 13256 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13257 } 13258 }) 13259 Button('startDownload') 13260 .onClick(() => { 13261 try { 13262 this.controller.startDownload('https://www.example.com'); 13263 } catch (error) { 13264 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13265 } 13266 }) 13267 Web({ src: 'www.example.com', controller: this.controller }) 13268 } 13269 } 13270} 13271``` 13272 13273### getFullPath<sup>11+</sup> 13274 13275getFullPath(): string 13276 13277Obtains the full path of the downloaded file on the disk. 13278 13279**System capability**: SystemCapability.Web.Webview.Core 13280 13281**Return value** 13282 13283| Type | Description | 13284| ------ | ------------------------- | 13285| string | Full path of the downloaded file on the disk.| 13286 13287**Example** 13288 13289```ts 13290// xxx.ets 13291import { webview } from '@kit.ArkWeb'; 13292import { BusinessError } from '@kit.BasicServicesKit'; 13293 13294@Entry 13295@Component 13296struct WebComponent { 13297 controller: webview.WebviewController = new webview.WebviewController(); 13298 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13299 13300 build() { 13301 Column() { 13302 Button('setDownloadDelegate') 13303 .onClick(() => { 13304 try { 13305 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13306 console.log("will start a download."); 13307 // Pass in a download path and start the download. 13308 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13309 }) 13310 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13311 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13312 }) 13313 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13314 console.log("download failed guid: " + webDownloadItem.getGuid()); 13315 }) 13316 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13317 console.log("download finish guid: " + webDownloadItem.getGuid()); 13318 console.log("download finish full path: " + webDownloadItem.getFullPath()); 13319 }) 13320 this.controller.setDownloadDelegate(this.delegate); 13321 } catch (error) { 13322 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13323 } 13324 }) 13325 Button('startDownload') 13326 .onClick(() => { 13327 try { 13328 this.controller.startDownload('https://www.example.com'); 13329 } catch (error) { 13330 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13331 } 13332 }) 13333 Web({ src: 'www.example.com', controller: this.controller }) 13334 } 13335 } 13336} 13337``` 13338 13339### serialize<sup>11+</sup> 13340 13341serialize(): Uint8Array 13342 13343Serializes the failed download to a byte array. 13344 13345**System capability**: SystemCapability.Web.Webview.Core 13346 13347**Return value** 13348 13349| Type | Description | 13350| ------ | ------------------------- | 13351| Uint8Array | Byte array into which the failed download is serialized.| 13352 13353**Example** 13354 13355```ts 13356// xxx.ets 13357import { webview } from '@kit.ArkWeb'; 13358import { BusinessError } from '@kit.BasicServicesKit'; 13359 13360@Entry 13361@Component 13362struct WebComponent { 13363 controller: webview.WebviewController = new webview.WebviewController(); 13364 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13365 failedData: Uint8Array = new Uint8Array(); 13366 13367 build() { 13368 Column() { 13369 Button('setDownloadDelegate') 13370 .onClick(() => { 13371 try { 13372 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13373 console.log("will start a download."); 13374 // Pass in a download path and start the download. 13375 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13376 }) 13377 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13378 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13379 }) 13380 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13381 console.log("download failed guid: " + webDownloadItem.getGuid()); 13382 // Serialize the failed download to a byte array. 13383 this.failedData = webDownloadItem.serialize(); 13384 }) 13385 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13386 console.log("download finish guid: " + webDownloadItem.getGuid()); 13387 }) 13388 this.controller.setDownloadDelegate(this.delegate); 13389 } catch (error) { 13390 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13391 } 13392 }) 13393 Button('startDownload') 13394 .onClick(() => { 13395 try { 13396 this.controller.startDownload('https://www.example.com'); 13397 } catch (error) { 13398 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13399 } 13400 }) 13401 Web({ src: 'www.example.com', controller: this.controller }) 13402 } 13403 } 13404} 13405``` 13406 13407### deserialize<sup>11+</sup> 13408 13409static deserialize(serializedData: Uint8Array): WebDownloadItem 13410 13411Deserializes the serialized byte array into a **WebDownloadItem** object. 13412 13413**System capability**: SystemCapability.Web.Webview.Core 13414 13415**Parameters** 13416 13417| Name | Type | Mandatory | Description| 13418| ------------------ | ------- | ---- | ------------- | 13419| serializedData | Uint8Array | Yes | Byte array into which the download is serialized.| 13420 13421**Return value** 13422 13423| Type | Description | 13424| ------ | ------------------------- | 13425| [WebDownloadItem](#webdownloaditem11) | **WebDownloadItem** object.| 13426 13427**Error codes** 13428 13429For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 13430 13431| ID| Error Message | 13432| -------- | ------------------------------------------------------------ | 13433| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. 2. Parameter verification failed. | 13434 13435**Example** 13436 13437```ts 13438// xxx.ets 13439import { webview } from '@kit.ArkWeb'; 13440import { BusinessError } from '@kit.BasicServicesKit'; 13441 13442@Entry 13443@Component 13444struct WebComponent { 13445 controller: webview.WebviewController = new webview.WebviewController(); 13446 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13447 failedData: Uint8Array = new Uint8Array(); 13448 13449 build() { 13450 Column() { 13451 Button('setDownloadDelegate') 13452 .onClick(() => { 13453 try { 13454 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13455 console.log("will start a download."); 13456 // Pass in a download path and start the download. 13457 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13458 }) 13459 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13460 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13461 }) 13462 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13463 console.log("download failed guid: " + webDownloadItem.getGuid()); 13464 // Serialize the failed download to a byte array. 13465 this.failedData = webDownloadItem.serialize(); 13466 }) 13467 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13468 console.log("download finish guid: " + webDownloadItem.getGuid()); 13469 }) 13470 this.controller.setDownloadDelegate(this.delegate); 13471 } catch (error) { 13472 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13473 } 13474 }) 13475 Button('startDownload') 13476 .onClick(() => { 13477 try { 13478 this.controller.startDownload('https://www.example.com'); 13479 } catch (error) { 13480 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13481 } 13482 }) 13483 Button('resumeDownload') 13484 .onClick(() => { 13485 try { 13486 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13487 } catch (error) { 13488 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13489 } 13490 }) 13491 Web({ src: 'www.example.com', controller: this.controller }) 13492 } 13493 } 13494} 13495``` 13496 13497### start<sup>11+</sup> 13498 13499start(downloadPath: string): void 13500 13501Starts a download to a specified directory. 13502 13503> **NOTE** 13504> 13505>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 and is downloaded to a temporary directory. After the target path is specified by **WebDownloadItem.start**, the temporary files are renamed to the target path and the unfinished files are directly downloaded to the target path. If you do not want to download the file to the temporary directory before invoking **WebDownloadItem.start**, you can call **WebDownloadItem.cancel** to cancel the current download task and then call **WebDownloadManager.resumeDownload** to resume the task. 13506 13507**System capability**: SystemCapability.Web.Webview.Core 13508 13509**Parameters** 13510 13511| Name| Type | Mandatory| Description | 13512| ------ | ---------------------- | ---- | ------------------------------| 13513| downloadPath | string | Yes | Path (including the file name) of the file to download.| 13514 13515**Error codes** 13516 13517For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 13518 13519| ID| Error Message | 13520| -------- | ------------------------------------------------------------ | 13521| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. 2. Parameter verification failed. | 13522 13523**Example** 13524 13525```ts 13526// xxx.ets 13527import { webview } from '@kit.ArkWeb'; 13528import { BusinessError } from '@kit.BasicServicesKit'; 13529 13530@Entry 13531@Component 13532struct WebComponent { 13533 controller: webview.WebviewController = new webview.WebviewController(); 13534 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13535 failedData: Uint8Array = new Uint8Array(); 13536 13537 build() { 13538 Column() { 13539 Button('setDownloadDelegate') 13540 .onClick(() => { 13541 try { 13542 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13543 console.log("will start a download."); 13544 // Pass in a download path and start the download. 13545 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13546 }) 13547 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13548 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13549 }) 13550 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13551 console.log("download failed guid: " + webDownloadItem.getGuid()); 13552 // Serialize the failed download to a byte array. 13553 this.failedData = webDownloadItem.serialize(); 13554 }) 13555 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13556 console.log("download finish guid: " + webDownloadItem.getGuid()); 13557 }) 13558 this.controller.setDownloadDelegate(this.delegate); 13559 } catch (error) { 13560 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13561 } 13562 }) 13563 Button('startDownload') 13564 .onClick(() => { 13565 try { 13566 this.controller.startDownload('https://www.example.com'); 13567 } catch (error) { 13568 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13569 } 13570 }) 13571 Button('resumeDownload') 13572 .onClick(() => { 13573 try { 13574 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13575 } catch (error) { 13576 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13577 } 13578 }) 13579 Web({ src: 'www.example.com', controller: this.controller }) 13580 } 13581 } 13582} 13583``` 13584 13585### cancel<sup>11+</sup> 13586 13587cancel(): void 13588 13589Cancels a download task. 13590 13591**System capability**: SystemCapability.Web.Webview.Core 13592 13593**Example** 13594 13595```ts 13596// xxx.ets 13597import { webview } from '@kit.ArkWeb'; 13598import { BusinessError } from '@kit.BasicServicesKit'; 13599 13600@Entry 13601@Component 13602struct WebComponent { 13603 controller: webview.WebviewController = new webview.WebviewController(); 13604 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13605 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13606 failedData: Uint8Array = new Uint8Array(); 13607 13608 build() { 13609 Column() { 13610 Button('setDownloadDelegate') 13611 .onClick(() => { 13612 try { 13613 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13614 console.log("will start a download."); 13615 // Pass in a download path and start the download. 13616 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13617 }) 13618 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13619 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13620 this.download = webDownloadItem; 13621 }) 13622 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13623 console.log("download failed guid: " + webDownloadItem.getGuid()); 13624 // Serialize the failed download to a byte array. 13625 this.failedData = webDownloadItem.serialize(); 13626 }) 13627 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13628 console.log("download finish guid: " + webDownloadItem.getGuid()); 13629 }) 13630 this.controller.setDownloadDelegate(this.delegate); 13631 } catch (error) { 13632 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13633 } 13634 }) 13635 Button('startDownload') 13636 .onClick(() => { 13637 try { 13638 this.controller.startDownload('https://www.example.com'); 13639 } catch (error) { 13640 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13641 } 13642 }) 13643 Button('resumeDownload') 13644 .onClick(() => { 13645 try { 13646 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13647 } catch (error) { 13648 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13649 } 13650 }) 13651 Button('cancel') 13652 .onClick(() => { 13653 try { 13654 this.download.cancel(); 13655 } catch (error) { 13656 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13657 } 13658 }) 13659 Web({ src: 'www.example.com', controller: this.controller }) 13660 } 13661 } 13662} 13663``` 13664 13665### pause<sup>11+</sup> 13666 13667pause(): void 13668 13669Pauses a download task. 13670 13671**System capability**: SystemCapability.Web.Webview.Core 13672 13673**Error codes** 13674 13675For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 13676 13677| ID | Error Message | 13678| -------- | ------------------------------------------------------------ | 13679| 17100019 | The download task is not started yet. | 13680 13681**Example** 13682 13683```ts 13684// xxx.ets 13685import { webview } from '@kit.ArkWeb'; 13686import { BusinessError } from '@kit.BasicServicesKit'; 13687 13688@Entry 13689@Component 13690struct WebComponent { 13691 controller: webview.WebviewController = new webview.WebviewController(); 13692 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13693 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13694 failedData: Uint8Array = new Uint8Array(); 13695 13696 build() { 13697 Column() { 13698 Button('setDownloadDelegate') 13699 .onClick(() => { 13700 try { 13701 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13702 console.log("will start a download."); 13703 // Pass in a download path and start the download. 13704 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13705 }) 13706 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13707 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13708 this.download = webDownloadItem; 13709 }) 13710 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13711 console.log("download failed guid: " + webDownloadItem.getGuid()); 13712 // Serialize the failed download to a byte array. 13713 this.failedData = webDownloadItem.serialize(); 13714 }) 13715 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13716 console.log("download finish guid: " + webDownloadItem.getGuid()); 13717 }) 13718 this.controller.setDownloadDelegate(this.delegate); 13719 } catch (error) { 13720 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13721 } 13722 }) 13723 Button('startDownload') 13724 .onClick(() => { 13725 try { 13726 this.controller.startDownload('https://www.example.com'); 13727 } catch (error) { 13728 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13729 } 13730 }) 13731 Button('resumeDownload') 13732 .onClick(() => { 13733 try { 13734 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13735 } catch (error) { 13736 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13737 } 13738 }) 13739 Button('cancel') 13740 .onClick(() => { 13741 try { 13742 this.download.cancel(); 13743 } catch (error) { 13744 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13745 } 13746 }) 13747 Button('pause') 13748 .onClick(() => { 13749 try { 13750 this.download.pause(); 13751 } catch (error) { 13752 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13753 } 13754 }) 13755 Web({ src: 'www.example.com', controller: this.controller }) 13756 } 13757 } 13758} 13759``` 13760 13761### resume<sup>11+</sup> 13762 13763resume(): void 13764 13765Resumes a download task. 13766 13767**System capability**: SystemCapability.Web.Webview.Core 13768 13769**Error codes** 13770 13771For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 13772 13773| ID | Error Message | 13774| -------- | ------------------------------------------------------------ | 13775| 17100016 | The download task is not paused. | 13776 13777**Example** 13778 13779```ts 13780// xxx.ets 13781import { webview } from '@kit.ArkWeb'; 13782import { BusinessError } from '@kit.BasicServicesKit'; 13783 13784@Entry 13785@Component 13786struct WebComponent { 13787 controller: webview.WebviewController = new webview.WebviewController(); 13788 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13789 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13790 failedData: Uint8Array = new Uint8Array(); 13791 13792 build() { 13793 Column() { 13794 Button('setDownloadDelegate') 13795 .onClick(() => { 13796 try { 13797 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13798 console.log("will start a download."); 13799 // Pass in a download path and start the download. 13800 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13801 }) 13802 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13803 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13804 this.download = webDownloadItem; 13805 }) 13806 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13807 console.log("download failed guid: " + webDownloadItem.getGuid()); 13808 // Serialize the failed download to a byte array. 13809 this.failedData = webDownloadItem.serialize(); 13810 }) 13811 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13812 console.log("download finish guid: " + webDownloadItem.getGuid()); 13813 }) 13814 this.controller.setDownloadDelegate(this.delegate); 13815 } catch (error) { 13816 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13817 } 13818 }) 13819 Button('startDownload') 13820 .onClick(() => { 13821 try { 13822 this.controller.startDownload('https://www.example.com'); 13823 } catch (error) { 13824 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13825 } 13826 }) 13827 Button('resumeDownload') 13828 .onClick(() => { 13829 try { 13830 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13831 } catch (error) { 13832 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13833 } 13834 }) 13835 Button('cancel') 13836 .onClick(() => { 13837 try { 13838 this.download.cancel(); 13839 } catch (error) { 13840 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13841 } 13842 }) 13843 Button('pause') 13844 .onClick(() => { 13845 try { 13846 this.download.pause(); 13847 } catch (error) { 13848 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13849 } 13850 }) 13851 Button('resume') 13852 .onClick(() => { 13853 try { 13854 this.download.resume(); 13855 } catch (error) { 13856 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13857 } 13858 }) 13859 Web({ src: 'www.example.com', controller: this.controller }) 13860 } 13861 } 13862} 13863``` 13864 13865## WebDownloadDelegate<sup>11+</sup> 13866 13867 Implements a **WebDownloadDelegate** class. You can use the callbacks of this class to notify users of the download state. 13868 13869### onBeforeDownload<sup>11+</sup> 13870 13871onBeforeDownload(callback: Callback\<WebDownloadItem>): void 13872 13873Invoked 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. 13874 13875> **NOTE** 13876> 13877>The file of the download task in the PENDING state is saved to a temporary directory. After the target path is specified by invoking **WebDownloadItem.start**, the temporary file is renamed as the target file, and the unfinished part is directly downloaded to the target path. To avoid generating temporary files before invoking **WebDownloadItem.start**, you can call **WebDownloadItem.cancel** to cancel the current download task and then call **WebDownloadManager.resumeDownload** to resume it. 13878 13879**System capability**: SystemCapability.Web.Webview.Core 13880 13881**Parameters** 13882 13883| Name | Type | Mandatory| Description | 13884| ------- | ------ | ---- | :------------- | 13885| callback | Callback\<[WebDownloadItem](#webdownloaditem11)> | Yes | Callback for triggering a download.| 13886 13887**Example** 13888 13889```ts 13890// xxx.ets 13891import { webview } from '@kit.ArkWeb'; 13892import { BusinessError } from '@kit.BasicServicesKit'; 13893 13894@Entry 13895@Component 13896struct WebComponent { 13897 controller: webview.WebviewController = new webview.WebviewController(); 13898 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13899 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13900 failedData: Uint8Array = new Uint8Array(); 13901 13902 build() { 13903 Column() { 13904 Button('setDownloadDelegate') 13905 .onClick(() => { 13906 try { 13907 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13908 console.log("will start a download."); 13909 // Pass in a download path and start the download. 13910 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13911 }) 13912 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13913 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13914 this.download = webDownloadItem; 13915 }) 13916 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13917 console.log("download failed guid: " + webDownloadItem.getGuid()); 13918 // Serialize the failed download to a byte array. 13919 this.failedData = webDownloadItem.serialize(); 13920 }) 13921 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13922 console.log("download finish guid: " + webDownloadItem.getGuid()); 13923 }) 13924 this.controller.setDownloadDelegate(this.delegate); 13925 } catch (error) { 13926 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13927 } 13928 }) 13929 Button('startDownload') 13930 .onClick(() => { 13931 try { 13932 this.controller.startDownload('https://www.example.com'); 13933 } catch (error) { 13934 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13935 } 13936 }) 13937 Button('resumeDownload') 13938 .onClick(() => { 13939 try { 13940 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13941 } catch (error) { 13942 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13943 } 13944 }) 13945 Button('cancel') 13946 .onClick(() => { 13947 try { 13948 this.download.cancel(); 13949 } catch (error) { 13950 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13951 } 13952 }) 13953 Button('pause') 13954 .onClick(() => { 13955 try { 13956 this.download.pause(); 13957 } catch (error) { 13958 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13959 } 13960 }) 13961 Button('resume') 13962 .onClick(() => { 13963 try { 13964 this.download.resume(); 13965 } catch (error) { 13966 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13967 } 13968 }) 13969 Web({ src: 'www.example.com', controller: this.controller }) 13970 } 13971 } 13972} 13973``` 13974 13975### onDownloadUpdated<sup>11+</sup> 13976 13977onDownloadUpdated(callback: Callback\<WebDownloadItem>): void 13978 13979Invoked when the download progress is updated. 13980 13981**System capability**: SystemCapability.Web.Webview.Core 13982 13983**Parameters** 13984 13985| Name | Type | Mandatory| Description | 13986| ------- | ------ | ---- | :------------- | 13987| callback | Callback\<[WebDownloadItem](#webdownloaditem11)> | Yes | Callback invoked when the downloaded progress is updated.| 13988 13989**Example** 13990 13991```ts 13992// xxx.ets 13993import { webview } from '@kit.ArkWeb'; 13994import { BusinessError } from '@kit.BasicServicesKit'; 13995 13996@Entry 13997@Component 13998struct WebComponent { 13999 controller: webview.WebviewController = new webview.WebviewController(); 14000 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 14001 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 14002 failedData: Uint8Array = new Uint8Array(); 14003 14004 build() { 14005 Column() { 14006 Button('setDownloadDelegate') 14007 .onClick(() => { 14008 try { 14009 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 14010 console.log("will start a download."); 14011 // Pass in a download path and start the download. 14012 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 14013 }) 14014 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 14015 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 14016 this.download = webDownloadItem; 14017 }) 14018 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 14019 console.log("download failed guid: " + webDownloadItem.getGuid()); 14020 // Serialize the failed download to a byte array. 14021 this.failedData = webDownloadItem.serialize(); 14022 }) 14023 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 14024 console.log("download finish guid: " + webDownloadItem.getGuid()); 14025 }) 14026 this.controller.setDownloadDelegate(this.delegate); 14027 } catch (error) { 14028 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14029 } 14030 }) 14031 Button('startDownload') 14032 .onClick(() => { 14033 try { 14034 this.controller.startDownload('https://www.example.com'); 14035 } catch (error) { 14036 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14037 } 14038 }) 14039 Button('resumeDownload') 14040 .onClick(() => { 14041 try { 14042 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 14043 } catch (error) { 14044 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14045 } 14046 }) 14047 Button('cancel') 14048 .onClick(() => { 14049 try { 14050 this.download.cancel(); 14051 } catch (error) { 14052 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14053 } 14054 }) 14055 Button('pause') 14056 .onClick(() => { 14057 try { 14058 this.download.pause(); 14059 } catch (error) { 14060 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14061 } 14062 }) 14063 Button('resume') 14064 .onClick(() => { 14065 try { 14066 this.download.resume(); 14067 } catch (error) { 14068 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14069 } 14070 }) 14071 Web({ src: 'www.example.com', controller: this.controller }) 14072 } 14073 } 14074} 14075``` 14076 14077### onDownloadFinish<sup>11+</sup> 14078 14079onDownloadFinish(callback: Callback\<WebDownloadItem>): void 14080 14081Invoked when the download is complete. 14082 14083**System capability**: SystemCapability.Web.Webview.Core 14084 14085**Parameters** 14086 14087| Name | Type | Mandatory| Description | 14088| ------- | ------ | ---- | :------------- | 14089| callback | Callback\<[WebDownloadItem](#webdownloaditem11)> | Yes | Callback invoked when the download is complete.| 14090 14091**Example** 14092 14093```ts 14094// xxx.ets 14095import { webview } from '@kit.ArkWeb'; 14096import { BusinessError } from '@kit.BasicServicesKit'; 14097 14098@Entry 14099@Component 14100struct WebComponent { 14101 controller: webview.WebviewController = new webview.WebviewController(); 14102 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 14103 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 14104 failedData: Uint8Array = new Uint8Array(); 14105 14106 build() { 14107 Column() { 14108 Button('setDownloadDelegate') 14109 .onClick(() => { 14110 try { 14111 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 14112 console.log("will start a download."); 14113 // Pass in a download path and start the download. 14114 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 14115 }) 14116 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 14117 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 14118 this.download = webDownloadItem; 14119 }) 14120 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 14121 console.log("download failed guid: " + webDownloadItem.getGuid()); 14122 // Serialize the failed download to a byte array. 14123 this.failedData = webDownloadItem.serialize(); 14124 }) 14125 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 14126 console.log("download finish guid: " + webDownloadItem.getGuid()); 14127 }) 14128 this.controller.setDownloadDelegate(this.delegate); 14129 } catch (error) { 14130 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14131 } 14132 }) 14133 Button('startDownload') 14134 .onClick(() => { 14135 try { 14136 this.controller.startDownload('https://www.example.com'); 14137 } catch (error) { 14138 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14139 } 14140 }) 14141 Button('resumeDownload') 14142 .onClick(() => { 14143 try { 14144 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 14145 } catch (error) { 14146 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14147 } 14148 }) 14149 Button('cancel') 14150 .onClick(() => { 14151 try { 14152 this.download.cancel(); 14153 } catch (error) { 14154 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14155 } 14156 }) 14157 Button('pause') 14158 .onClick(() => { 14159 try { 14160 this.download.pause(); 14161 } catch (error) { 14162 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14163 } 14164 }) 14165 Button('resume') 14166 .onClick(() => { 14167 try { 14168 this.download.resume(); 14169 } catch (error) { 14170 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14171 } 14172 }) 14173 Web({ src: 'www.example.com', controller: this.controller }) 14174 } 14175 } 14176} 14177``` 14178 14179### onDownloadFailed<sup>11+</sup> 14180 14181onDownloadFailed(callback: Callback\<WebDownloadItem>): void 14182 14183Invoked when the download fails. 14184 14185**System capability**: SystemCapability.Web.Webview.Core 14186 14187**Parameters** 14188 14189| Name | Type | Mandatory| Description | 14190| ------- | ------ | ---- | :------------- | 14191| callback | Callback\<[WebDownloadItem](#webdownloaditem11)> | Yes | Callback invoked when the download fails.| 14192 14193**Example** 14194 14195```ts 14196// xxx.ets 14197import { webview } from '@kit.ArkWeb'; 14198import { BusinessError } from '@kit.BasicServicesKit'; 14199 14200@Entry 14201@Component 14202struct WebComponent { 14203 controller: webview.WebviewController = new webview.WebviewController(); 14204 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 14205 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 14206 failedData: Uint8Array = new Uint8Array(); 14207 14208 build() { 14209 Column() { 14210 Button('setDownloadDelegate') 14211 .onClick(() => { 14212 try { 14213 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 14214 console.log("will start a download."); 14215 // Pass in a download path and start the download. 14216 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 14217 }) 14218 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 14219 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 14220 this.download = webDownloadItem; 14221 }) 14222 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 14223 console.log("download failed guid: " + webDownloadItem.getGuid()); 14224 // Serialize the failed download to a byte array. 14225 this.failedData = webDownloadItem.serialize(); 14226 }) 14227 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 14228 console.log("download finish guid: " + webDownloadItem.getGuid()); 14229 }) 14230 this.controller.setDownloadDelegate(this.delegate); 14231 } catch (error) { 14232 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14233 } 14234 }) 14235 Button('startDownload') 14236 .onClick(() => { 14237 try { 14238 this.controller.startDownload('https://www.example.com'); 14239 } catch (error) { 14240 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14241 } 14242 }) 14243 Button('resumeDownload') 14244 .onClick(() => { 14245 try { 14246 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 14247 } catch (error) { 14248 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14249 } 14250 }) 14251 Button('cancel') 14252 .onClick(() => { 14253 try { 14254 this.download.cancel(); 14255 } catch (error) { 14256 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14257 } 14258 }) 14259 Button('pause') 14260 .onClick(() => { 14261 try { 14262 this.download.pause(); 14263 } catch (error) { 14264 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14265 } 14266 }) 14267 Button('resume') 14268 .onClick(() => { 14269 try { 14270 this.download.resume(); 14271 } catch (error) { 14272 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14273 } 14274 }) 14275 Web({ src: 'www.example.com', controller: this.controller }) 14276 } 14277 } 14278} 14279``` 14280 14281## WebDownloadManager<sup>11+</sup> 14282 14283Implements a **WebDownloadManager** class. You can use the APIs of this class to resume failed download tasks. 14284 14285### setDownloadDelegate<sup>11+</sup> 14286 14287static setDownloadDelegate(delegate: WebDownloadDelegate): void 14288 14289Sets the delegate used to receive download progress triggered from **WebDownloadManager**. 14290 14291**System capability**: SystemCapability.Web.Webview.Core 14292 14293**Parameters** 14294 14295| Name | Type | Mandatory | Description | 14296| ---------------| ------- | ---- | ------------- | 14297| delegate | [WebDownloadDelegate](#webdownloaddelegate11) | Yes | Delegate used to receive the download progress.| 14298 14299**Example** 14300 14301```ts 14302// xxx.ets 14303import { webview } from '@kit.ArkWeb'; 14304import { BusinessError } from '@kit.BasicServicesKit'; 14305 14306@Entry 14307@Component 14308struct WebComponent { 14309 controller: webview.WebviewController = new webview.WebviewController(); 14310 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 14311 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 14312 failedData: Uint8Array = new Uint8Array(); 14313 14314 build() { 14315 Column() { 14316 Button('setDownloadDelegate') 14317 .onClick(() => { 14318 try { 14319 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 14320 console.log("will start a download."); 14321 // Pass in a download path and start the download. 14322 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 14323 }) 14324 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 14325 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 14326 this.download = webDownloadItem; 14327 }) 14328 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 14329 console.log("download failed guid: " + webDownloadItem.getGuid()); 14330 // Serialize the failed download to a byte array. 14331 this.failedData = webDownloadItem.serialize(); 14332 }) 14333 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 14334 console.log("download finish guid: " + webDownloadItem.getGuid()); 14335 }) 14336 this.controller.setDownloadDelegate(this.delegate); 14337 webview.WebDownloadManager.setDownloadDelegate(this.delegate); 14338 } catch (error) { 14339 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14340 } 14341 }) 14342 Button('startDownload') 14343 .onClick(() => { 14344 try { 14345 this.controller.startDownload('https://www.example.com'); 14346 } catch (error) { 14347 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14348 } 14349 }) 14350 Button('resumeDownload') 14351 .onClick(() => { 14352 try { 14353 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 14354 } catch (error) { 14355 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14356 } 14357 }) 14358 Button('cancel') 14359 .onClick(() => { 14360 try { 14361 this.download.cancel(); 14362 } catch (error) { 14363 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14364 } 14365 }) 14366 Button('pause') 14367 .onClick(() => { 14368 try { 14369 this.download.pause(); 14370 } catch (error) { 14371 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14372 } 14373 }) 14374 Button('resume') 14375 .onClick(() => { 14376 try { 14377 this.download.resume(); 14378 } catch (error) { 14379 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14380 } 14381 }) 14382 Web({ src: 'www.example.com', controller: this.controller }) 14383 } 14384 } 14385} 14386``` 14387 14388### resumeDownload<sup>11+</sup> 14389 14390static resumeDownload(webDownloadItem: WebDownloadItem): void 14391 14392Resumes a failed download task. 14393 14394**System capability**: SystemCapability.Web.Webview.Core 14395 14396**Parameters** 14397 14398| Name | Type | Mandatory | Description | 14399| ---------------| ------- | ---- | ------------- | 14400| webDownloadItem | [WebDownloadItem](#webdownloaditem11) | Yes | Download task to resume.| 14401 14402**Error codes** 14403 14404For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14405 14406| ID| Error Message | 14407| -------- | ------------------------------------- | 14408| 17100018 | No WebDownloadDelegate has been set yet. | 14409 14410**Example** 14411 14412```ts 14413// xxx.ets 14414import { webview } from '@kit.ArkWeb'; 14415import { BusinessError } from '@kit.BasicServicesKit'; 14416 14417@Entry 14418@Component 14419struct WebComponent { 14420 controller: webview.WebviewController = new webview.WebviewController(); 14421 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 14422 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 14423 failedData: Uint8Array = new Uint8Array(); 14424 14425 build() { 14426 Column() { 14427 Button('setDownloadDelegate') 14428 .onClick(() => { 14429 try { 14430 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 14431 console.log("will start a download."); 14432 // Pass in a download path and start the download. 14433 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 14434 }) 14435 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 14436 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 14437 this.download = webDownloadItem; 14438 }) 14439 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 14440 console.log("download failed guid: " + webDownloadItem.getGuid()); 14441 // Serialize the failed download to a byte array. 14442 this.failedData = webDownloadItem.serialize(); 14443 }) 14444 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 14445 console.log("download finish guid: " + webDownloadItem.getGuid()); 14446 }) 14447 this.controller.setDownloadDelegate(this.delegate); 14448 webview.WebDownloadManager.setDownloadDelegate(this.delegate); 14449 } catch (error) { 14450 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14451 } 14452 }) 14453 Button('startDownload') 14454 .onClick(() => { 14455 try { 14456 this.controller.startDownload('https://www.example.com'); 14457 } catch (error) { 14458 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14459 } 14460 }) 14461 Button('resumeDownload') 14462 .onClick(() => { 14463 try { 14464 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 14465 } catch (error) { 14466 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14467 } 14468 }) 14469 Button('cancel') 14470 .onClick(() => { 14471 try { 14472 this.download.cancel(); 14473 } catch (error) { 14474 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14475 } 14476 }) 14477 Button('pause') 14478 .onClick(() => { 14479 try { 14480 this.download.pause(); 14481 } catch (error) { 14482 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14483 } 14484 }) 14485 Button('resume') 14486 .onClick(() => { 14487 try { 14488 this.download.resume(); 14489 } catch (error) { 14490 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14491 } 14492 }) 14493 Web({ src: 'www.example.com', controller: this.controller }) 14494 } 14495 } 14496} 14497``` 14498 14499## ProxySchemeFilter<sup>15+</sup> 14500 14501Filters the scheme that uses the proxy. 14502 14503**System capability**: SystemCapability.Web.Webview.Core 14504 14505| Name | Value| Description | 14506| ------------- | -- |----------------------------------------- | 14507| MATCH_ALL_SCHEMES | 0 |All schemes use proxies.| 14508| MATCH_HTTP | 1 |HTTP requests use proxies.| 14509| MATCH_HTTPS | 2 |HTTPS requests use proxies.| 14510 14511## ProxyConfig<sup>15+</sup> 14512 14513Implements a ProxyConfig class. You can use the APIs of this class to configure proxies. 14514 14515### insertProxyRule<sup>15+</sup> 14516 14517insertProxyRule(proxyRule: string, schemeFilter?: ProxySchemeFilter): void 14518 14519Inserts a rule to specify a proxy for URLs matching **schemeFilter**. If **schemeFilter** is empty, all URLs use the specified proxy. 14520 14521**System capability**: SystemCapability.Web.Webview.Core 14522 14523**Parameters** 14524 14525| Name | Type | Mandatory | Description | 14526| ---------------| ------- | ---- | ------------- | 14527| proxyRule | string | Yes | The specified proxy.| 14528| schemeFilter | [ProxySchemeFilter](#proxyschemefilter15) | No | Used to filter URLs to use the proxy. Default value: **MATCH_ALL_SCHEMES**.| 14529 14530**Error codes** 14531 14532For details about the following error codes, see [Universal Error Codes](../errorcode-universal.md). 14533 14534| ID| Error Message | 14535| -------- | ------------------------------------- | 14536| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 14537 14538**Example** 14539 14540For details, see [removeProxyOverride](#removeproxyoverride15). 14541 14542### insertDirectRule<sup>15+</sup> 14543 14544insertDirectRule(schemeFilter?: ProxySchemeFilter): void 14545 14546Inserts a proxy rule to specify that URLs matching **schemeFilter** are directly connected to the server. 14547 14548**System capability**: SystemCapability.Web.Webview.Core 14549 14550**Parameters** 14551 14552| Name | Type | Mandatory | Description | 14553| ---------------| ------- | ---- | ------------- | 14554| schemeFilter | [ProxySchemeFilter](#proxyschemefilter15) | No | Used to filter URLs to be directly connected to the server. Default value: **MATCH_ALL_SCHEMES**.| 14555 14556**Error codes** 14557 14558For details about the following error codes, see [Universal Error Codes](../errorcode-universal.md). 14559 14560| ID| Error Message | 14561| -------- | ------------------------------------- | 14562| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 14563 14564**Example** 14565 14566For details, see [removeProxyOverride](#removeproxyoverride15). 14567 14568### insertBypassRule<sup>15+</sup> 14569 14570insertBypassRule(bypassRule: string): void 14571 14572Inserts a bypass rule to specify the URLs that should bypass the proxy and directly connect to the server. 14573 14574**System capability**: SystemCapability.Web.Webview.Core 14575 14576**Parameters** 14577 14578| Name | Type | Mandatory | Description | 14579| ---------------| ------- | ---- | ------------- | 14580| bypassRule | string | Yes | Used to specify the URLs that should bypass the proxy.| 14581 14582**Error codes** 14583 14584For details about the following error codes, see [Universal Error Codes](../errorcode-universal.md). 14585 14586| ID| Error Message | 14587| -------- | ------------------------------------- | 14588| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 14589 14590**Example** 14591 14592For details, see [removeProxyOverride](#removeproxyoverride15). 14593 14594### bypassHostnamesWithoutPeriod<sup>15+</sup> 14595 14596bypassHostnamesWithoutPeriod(): void 14597 14598Specifies that domain names without a period should bypass the proxy and directly connect to the server. 14599 14600**System capability**: SystemCapability.Web.Webview.Core 14601 14602**Example** 14603 14604For details, see [removeProxyOverride](#removeproxyoverride15). 14605 14606### clearImplicitRules<sup>15+</sup> 14607 14608clearImplicitRules(): void 14609 14610Overrides the default behavior and forces local host or local IP address to be sent through the proxy. (By default, if host names are local IP addresses or local host addresses, they bypass the proxy.) 14611 14612**System capability**: SystemCapability.Web.Webview.Core 14613 14614**Example** 14615 14616For details, see [removeProxyOverride](#removeproxyoverride15). 14617 14618### enableReverseBypass<sup>15+</sup> 14619 14620enableReverseBypass(reverse: boolean): void 14621 14622Reverses the bypass rule. 14623 14624**System capability**: SystemCapability.Web.Webview.Core 14625 14626**Parameters** 14627 14628| Name | Type | Mandatory | Description | 14629| ---------------| ------- | ---- | ------------- | 14630| reverse | boolean | Yes | Whether to reverse the bypass rule. The default value is **false**, indicating the bypass rule set in [insertBypassRule](#insertbypassrule15) is not reversed. The value **true** indicates the opposite.| 14631 14632**Error codes** 14633 14634For details about the following error codes, see [Universal Error Codes](../errorcode-universal.md). 14635 14636| ID| Error Message | 14637| -------- | ------------------------------------- | 14638| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 14639 14640**Example** 14641 14642For details, see [removeProxyOverride](#removeproxyoverride15). 14643 14644### getBypassRules<sup>15+</sup> 14645 14646getBypassRules(): Array\<string\> 14647 14648Obtains the list of URLs that do not use the proxy. 14649 14650**System capability**: SystemCapability.Web.Webview.Core 14651 14652**Return value** 14653 14654| Type | Description | 14655| ------ | ------------------------- | 14656| Array\<string\> | List of URLs that do not use the proxy.| 14657 14658**Example** 14659 14660For details, see [removeProxyOverride](#removeproxyoverride15). 14661 14662### getProxyRules<sup>15+</sup> 14663 14664getProxyRules(): Array\<ProxyRule\> 14665 14666Obtains proxy rules. 14667 14668**System capability**: SystemCapability.Web.Webview.Core 14669 14670**Return value** 14671 14672| Type | Description | 14673| ------ | ------------------------- | 14674| Array\<[ProxyRule](#proxyrule15)\> | Proxy rule.| 14675 14676**Example** 14677 14678For details, see [removeProxyOverride](#removeproxyoverride15). 14679 14680### isReverseBypassEnabled<sup>15+</sup> 14681 14682isReverseBypassEnabled(): boolean 14683 14684Obtains the value of [enableReverseBypass](#enablereversebypass15). For details, see [enableReverseBypass](#enablereversebypass15). 14685 14686**System capability**: SystemCapability.Web.Webview.Core 14687 14688**Return value** 14689 14690| Type | Description | 14691| ------ | ------------------------- | 14692| boolean | Value of [enableReverseBypass](#enablereversebypass15). The default value is **false**, indicating the bypass rule set in [insertBypassRule](#insertbypassrule15) is not reversed. The value **true** indicates the opposite.| 14693 14694**Example** 14695 14696For details, see [removeProxyOverride](#removeproxyoverride15). 14697 14698 14699## ProxyRule<sup>15+</sup> 14700 14701Indicates the proxy rule used in the [insertProxyRule](#insertproxyrule15). 14702 14703### getSchemeFilter<sup>15+</sup> 14704 14705getSchemeFilter(): ProxySchemeFilter 14706 14707Obtains the [ProxySchemeFilter](#proxyschemefilter15) information in the proxy rule. 14708 14709**System capability**: SystemCapability.Web.Webview.Core 14710 14711**Return value** 14712 14713| Type | Description | 14714| ------ | ------------------------- | 14715| [ProxySchemeFilter](#proxyschemefilter15) | The [ProxySchemeFilter](#proxyschemefilter15) information in the proxy rule.| 14716 14717**Example** 14718 14719For details, see [removeProxyOverride](#removeproxyoverride15). 14720 14721### getUrl<sup>15+</sup> 14722 14723getUrl(): string 14724 14725Obtains the URL specified in the proxy rule. 14726 14727**System capability**: SystemCapability.Web.Webview.Core 14728 14729**Return value** 14730 14731| Type | Description | 14732| ------ | ------------------------- | 14733| string | The URL specified in the proxy rule.| 14734 14735**Example** 14736 14737For details, see [removeProxyOverride](#removeproxyoverride15). 14738 14739## OnProxyConfigChangeCallback<sup>15+</sup> 14740 14741type OnProxyConfigChangeCallback = () => void 14742 14743Called when the proxy is set successfully. 14744 14745**System capability**: SystemCapability.Web.Webview.Core 14746 14747**Example** 14748 14749For details, see [removeProxyOverride](#removeproxyoverride15). 14750 14751## ProxyController<sup>15+</sup> 14752 14753Implements a **ProxyController** object to set a proxy for an application. 14754 14755### applyProxyOverride<sup>15+</sup> 14756 14757static applyProxyOverride(proxyConfig: ProxyConfig, callback: OnProxyConfigChangeCallback): void 14758 14759Set the proxy used by all webs in an application. URLs that match the bypass rule inserted through [insertBypassRule](#insertbypassrule15) do not use the proxy. Instead, their requests are directly sent to the source addresses specified by the URLs. The new proxy may not be used immediately after the network is connected. Before loading the page, wait for the listener to be triggered in the UI thread. 14760 14761**System capability**: SystemCapability.Web.Webview.Core 14762 14763**Parameters** 14764 14765| Name | Type | Mandatory | Description | 14766| ---------------| ------- | ---- | ------------- | 14767| proxyConfig | [ProxyConfig](#proxyconfig15) | Yes | Configuration of the proxy.| 14768| callback | [OnProxyConfigChangeCallback](#onproxyconfigchangecallback15) | Yes | Callback used when the proxy is successfully set.| 14769 14770**Error codes** 14771 14772For details about the following error codes, see [Universal Error Codes](../errorcode-universal.md). 14773 14774| ID| Error Message | 14775| -------- | ------------------------------------- | 14776| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 14777 14778**Example** 14779 14780For details, see [removeProxyOverride](#removeproxyoverride15). 14781 14782### removeProxyOverride<sup>15+</sup> 14783 14784static removeProxyOverride(callback: OnProxyConfigChangeCallback): void 14785 14786Removes the proxy configuration. The new proxy may not be used immediately after the network is connected. Before loading the page, wait for the listener to be triggered in the UI thread. 14787 14788**System capability**: SystemCapability.Web.Webview.Core 14789 14790**Parameters** 14791 14792| Name | Type | Mandatory | Description | 14793| ---------------| ------- | ---- | ------------- | 14794| callback | [OnProxyConfigChangeCallback](#onproxyconfigchangecallback15) | Yes | Callback used when the proxy is successfully set.| 14795 14796**Error codes** 14797 14798For details about the following error codes, see [Universal Error Codes](../errorcode-universal.md). 14799 14800| ID| Error Message | 14801| -------- | ------------------------------------- | 14802| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 14803 14804**Example** 14805 14806```ts 14807// xxx.ets 14808import { webview } from '@kit.ArkWeb'; 14809import { BusinessError } from '@kit.BasicServicesKit'; 14810 14811@Entry 14812@Component 14813struct WebComponent { 14814 controller: webview.WebviewController = new webview.WebviewController(); 14815 proxyRules: webview.ProxyRule[] = []; 14816 14817 build() { 14818 Row() { 14819 Column() { 14820 Button("applyProxyOverride").onClick(()=>{ 14821 let proxyConfig:webview.ProxyConfig = new webview.ProxyConfig(); 14822 // The first proxy configuration https://proxy.XXX.com is preferentially used. 14823 // When the proxy fails, insertDirectRule is used. 14824 try { 14825 proxyConfig.insertProxyRule("https://proxy.XXX.com", webview.ProxySchemeFilter.MATCH_ALL_SCHEMES); 14826 } catch (error) { 14827 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14828 } 14829 try { 14830 proxyConfig.insertDirectRule(webview.ProxySchemeFilter.MATCH_HTTP); 14831 } catch (error) { 14832 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14833 } 14834 try { 14835 proxyConfig.insertBypassRule("*.example.com"); 14836 } catch (error) { 14837 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14838 } 14839 proxyConfig.clearImplicitRules(); 14840 proxyConfig.bypassHostnamesWithoutPeriod(); 14841 try { 14842 proxyConfig.enableReverseBypass(true); 14843 } catch (error) { 14844 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14845 } 14846 let bypassRules = proxyConfig.getBypassRules(); 14847 for (let i = 0; i < bypassRules.length; i++) { 14848 console.log("bypassRules: " + bypassRules[i]); 14849 } 14850 this.proxyRules = proxyConfig.getProxyRules(); 14851 for (let i = 0; i < this.proxyRules.length; i++) { 14852 console.log("SchemeFiletr: " + this.proxyRules[i].getSchemeFilter()); 14853 console.log("Url: " + this.proxyRules[i].getUrl()); 14854 } 14855 let isReverseBypassRule = proxyConfig.isReverseBypassEnabled(); 14856 console.log("isReverseBypassRules: " + isReverseBypassRule); 14857 try { 14858 webview.ProxyController.applyProxyOverride(proxyConfig, () => { 14859 console.log("PROXYCONTROLLER proxy changed"); 14860 }); 14861 } catch (error) { 14862 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14863 } 14864 }) 14865 Button("loadUrl-https").onClick(()=>{ 14866 this.controller.loadUrl("https://www.example.com") 14867 }) 14868 Button("loadUrl-http").onClick(()=>{ 14869 this.controller.loadUrl("http://www.example.com") 14870 }) 14871 Button("removeProxyOverride").onClick(()=>{ 14872 try { 14873 webview.ProxyController.removeProxyOverride(() => { 14874 console.log("PROXYCONTROLLER proxy changed"); 14875 }); 14876 } catch (error) { 14877 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14878 } 14879 }) 14880 Web({ src: 'www.example.com', controller: this.controller}) 14881 } 14882 .width('100%') 14883 } 14884 .height('100%') 14885 } 14886} 14887 14888``` 14889 14890## WebHttpBodyStream<sup>12+</sup> 14891 14892Represents 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. 14893 14894### initialize<sup>12+</sup> 14895 14896initialize(): Promise\<void\> 14897 14898Initializes this **WebHttpBodyStream** instance. 14899 14900**System capability**: SystemCapability.Web.Webview.Core 14901 14902**Return value** 14903 14904| Type | Description | 14905| ------ | ------------------------- | 14906| Promise\<void\> | Promise used to return the result.| 14907 14908**Error codes** 14909 14910For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14911 14912| ID| Error Message | 14913| -------- | ------------------------------------- | 14914| 17100022 | Failed to initialize the HTTP body stream. | 14915 14916**Example** 14917 14918```ts 14919// xxx.ets 14920import { webview } from '@kit.ArkWeb'; 14921import { BusinessError } from '@kit.BasicServicesKit'; 14922import { buffer } from '@kit.ArkTS'; 14923import { WebNetErrorList } from '@ohos.web.netErrorList' 14924 14925@Entry 14926@Component 14927struct WebComponent { 14928 controller: webview.WebviewController = new webview.WebviewController(); 14929 schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); 14930 htmlData: string = "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>"; 14931 14932 build() { 14933 Column() { 14934 Button('postUrl') 14935 .onClick(() => { 14936 try { 14937 let postData = buffer.from(this.htmlData); 14938 this.controller.postUrl('https://www.example.com', postData.buffer); 14939 } catch (error) { 14940 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14941 } 14942 }) 14943 Web({ src: 'https://www.example.com', controller: this.controller }) 14944 .onControllerAttached(() => { 14945 try { 14946 this.schemeHandler.onRequestStart((request: webview.WebSchemeHandlerRequest, resourceHandler: webview.WebResourceHandler) => { 14947 console.log("[schemeHandler] onRequestStart"); 14948 try { 14949 let stream = request.getHttpBodyStream(); 14950 if (stream) { 14951 stream.initialize().then(() => { 14952 if (!stream) { 14953 return; 14954 } 14955 console.log("[schemeHandler] onRequestStart postDataStream size:" + stream.getSize()); 14956 console.log("[schemeHandler] onRequestStart postDataStream position:" + stream.getPosition()); 14957 console.log("[schemeHandler] onRequestStart postDataStream isChunked:" + stream.isChunked()); 14958 console.log("[schemeHandler] onRequestStart postDataStream isEof:" + stream.isEof()); 14959 console.log("[schemeHandler] onRequestStart postDataStream isInMemory:" + stream.isInMemory()); 14960 stream.read(stream.getSize()).then((buffer) => { 14961 if (!stream) { 14962 return; 14963 } 14964 console.log("[schemeHandler] onRequestStart postDataStream readlength:" + buffer.byteLength); 14965 console.log("[schemeHandler] onRequestStart postDataStream isEof:" + stream.isEof()); 14966 console.log("[schemeHandler] onRequestStart postDataStream position:" + stream.getPosition()); 14967 }).catch((error: BusinessError) => { 14968 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 14969 }) 14970 }).catch((error: BusinessError) => { 14971 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 14972 }) 14973 } else { 14974 console.log("[schemeHandler] onRequestStart has no http body stream"); 14975 } 14976 } catch (error) { 14977 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14978 } 14979 14980 return false; 14981 }) 14982 14983 this.schemeHandler.onRequestStop((request: webview.WebSchemeHandlerRequest) => { 14984 console.log("[schemeHandler] onRequestStop"); 14985 }); 14986 14987 this.controller.setWebSchemeHandler('https', this.schemeHandler); 14988 } catch (error) { 14989 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14990 } 14991 }) 14992 .javaScriptAccess(true) 14993 .domStorageAccess(true) 14994 } 14995 } 14996} 14997 14998``` 14999 15000### read<sup>12+</sup> 15001 15002read(size: number): Promise\<ArrayBuffer\> 15003 15004Reads data from this **WebHttpBodyStream** instance. 15005 15006**System capability**: SystemCapability.Web.Webview.Core 15007 15008**Parameters** 15009 15010| Name | Type | Mandatory | Description | 15011| --------| ------- | ---- | ---------------------------| 15012| size | number | Yes | Number of bytes obtained from the **WebHttpBodyStream** instance.| 15013 15014**Return value** 15015 15016| Type | Description | 15017| ------ | ------------------------- | 15018| Promise\<ArrayBuffer\> | Promise used to return the result.| 15019 15020**Error codes** 15021 15022For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15023 15024| ID| Error Message | 15025| -------- | ------------------------------------- | 15026| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 15027 15028**Example** 15029 15030For the complete sample code, see [initialize](#initialize12)). 15031 15032### getSize<sup>12+</sup> 15033 15034getSize(): number 15035 15036Obtains the size of data in this **WebHttpBodyStream** instance. This API always returns zero when chunked transfer is used. 15037 15038**System capability**: SystemCapability.Web.Webview.Core 15039 15040**Return value** 15041 15042| Type | Description | 15043| ------ | ------------------------- | 15044| number | Size of data in the current **WebHttpBodyStream** instance.| 15045 15046**Example** 15047 15048For the complete sample code, see [initialize](#initialize12)). 15049 15050### getPosition<sup>12+</sup> 15051 15052getPosition(): number 15053 15054Reads the current read position in this **WebHttpBodyStream** instance. 15055 15056**System capability**: SystemCapability.Web.Webview.Core 15057 15058**Return value** 15059 15060| Type | Description | 15061| ------ | ------------------------- | 15062| number | Current read position in the **WebHttpBodyStream** instance.| 15063 15064**Example** 15065 15066For the complete sample code, see [initialize](#initialize12)). 15067 15068### isChunked<sup>12+</sup> 15069 15070isChunked(): boolean 15071 15072Checks whether this **WebHttpBodyStream** instance is transmitted by chunk. 15073 15074**System capability**: SystemCapability.Web.Webview.Core 15075 15076**Return value** 15077 15078| Type | Description | 15079| ------ | ------------------------- | 15080| boolean | Whether the **WebHttpBodyStream** instance is transmitted by chunk.| 15081 15082**Example** 15083 15084For the complete sample code, see [initialize](#initialize12)). 15085 15086### isEof<sup>12+</sup> 15087 15088isEof(): boolean 15089 15090Checks 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. 15091 15092**System capability**: SystemCapability.Web.Webview.Core 15093 15094**Return value** 15095 15096| Type | Description | 15097| ------ | ------------------------- | 15098| boolean | Whether all data in the **WebHttpBodyStream** instance has been read.| 15099 15100**Example** 15101 15102For the complete sample code, see [initialize](#initialize12)). 15103 15104### isInMemory<sup>12+</sup> 15105 15106isInMemory(): boolean 15107 15108Checks 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. 15109 15110**System capability**: SystemCapability.Web.Webview.Core 15111 15112**Return value** 15113 15114| Type | Description | 15115| ------ | ------------------------- | 15116| boolean | Whether the uploaded data in the **WebHttpBodyStream** instance is stored in memory.| 15117 15118**Example** 15119 15120For the complete sample code, see [initialize](#initialize12)). 15121 15122## WebSchemeHandlerRequest<sup>12+</sup> 15123 15124Represents a request intercepted by the **WebSchemeHandler** object. 15125 15126### getHeader<sup>12+</sup> 15127 15128getHeader(): Array\<WebHeader\> 15129 15130Obtains the information about the resource request header. 15131 15132**System capability**: SystemCapability.Web.Webview.Core 15133 15134**Return value** 15135 15136| Type | Description | 15137| -------------------------- | ---------- | 15138| Array\<[WebHeader](#webheader)\> | Information about the resource request header.| 15139 15140**Example** 15141 15142For the complete sample code, see [onRequestStart](#onrequeststart12). 15143 15144### getRequestUrl<sup>12+</sup> 15145 15146getRequestUrl(): string 15147 15148Obtains the URL of the resource request. 15149 15150**System capability**: SystemCapability.Web.Webview.Core 15151 15152**Return value** 15153 15154| Type | Description | 15155| ------ | ------------- | 15156| string | URL of the resource request.| 15157 15158**Example** 15159 15160For the complete sample code, see [onRequestStart](#onrequeststart12). 15161 15162### getRequestMethod<sup>12+</sup> 15163 15164getRequestMethod(): string 15165 15166Obtains the request method. 15167 15168**System capability**: SystemCapability.Web.Webview.Core 15169 15170**Return value** 15171 15172| Type | Description | 15173| ------ | ------------- | 15174| string | Request method.| 15175 15176**Example** 15177 15178For the complete sample code, see [onRequestStart](#onrequeststart12). 15179 15180### getReferrer<sup>12+</sup> 15181 15182getReferrer(): string 15183 15184Obtains the referrer. 15185 15186**System capability**: SystemCapability.Web.Webview.Core 15187 15188**Return value** 15189 15190| Type | Description | 15191| ------ | ------------- | 15192| string | Obtained referrer.| 15193 15194**Example** 15195 15196For the complete sample code, see [onRequestStart](#onrequeststart12). 15197 15198### isMainFrame<sup>12+</sup> 15199 15200isMainFrame(): boolean 15201 15202Checks whether the resource request is for the main frame. 15203 15204**System capability**: SystemCapability.Web.Webview.Core 15205 15206**Return value** 15207 15208| Type | Description | 15209| ------ | ------------- | 15210| boolean | Whether the resource request is for the main frame.| 15211 15212**Example** 15213 15214For the complete sample code, see [onRequestStart](#onrequeststart12). 15215 15216### hasGesture<sup>12+</sup> 15217 15218hasGesture(): boolean 15219 15220Checks whether the resource request is associated with a gesture (for example, a tap). 15221 15222**System capability**: SystemCapability.Web.Webview.Core 15223 15224**Return value** 15225 15226| Type | Description | 15227| ------ | ------------- | 15228| boolean | Whether the resource request is associated with a gesture (for example, a tap).| 15229 15230**Example** 15231 15232For the complete sample code, see [onRequestStart](#onrequeststart12). 15233 15234### getHttpBodyStream<sup>12+</sup> 15235 15236getHttpBodyStream(): WebHttpBodyStream | null 15237 15238Obtains the **WebHttpBodyStream** instance in this resource request. 15239 15240**System capability**: SystemCapability.Web.Webview.Core 15241 15242**Return value** 15243 15244| Type | Description | 15245| ------ | ------------- | 15246| [WebHttpBodyStream](#webhttpbodystream12) \| null | **WebHttpBodyStream** instance in the resource request. If there is no **WebHttpBodyStream** instance, **null** is returned.| 15247 15248**Example** 15249 15250For the complete sample code, see [onRequestStart](#onrequeststart12). 15251 15252### getRequestResourceType<sup>12+</sup> 15253 15254getRequestResourceType(): WebResourceType 15255 15256Obtains the resource type of this resource request. 15257 15258**System capability**: SystemCapability.Web.Webview.Core 15259 15260**Return value** 15261 15262| Type | Description | 15263| ------ | ------------- | 15264| [WebResourceType](#webresourcetype12) | Resource type of the resource request.| 15265 15266**Example** 15267 15268For the complete sample code, see [onRequestStart](#onrequeststart12). 15269 15270### getFrameUrl<sup>12+</sup> 15271 15272getFrameUrl(): string 15273 15274Obtains the URL of the frame that triggers this request. 15275 15276**System capability**: SystemCapability.Web.Webview.Core 15277 15278**Return value** 15279 15280| Type | Description | 15281| ------ | ------------- | 15282| string | URL of the frame that triggers the request.| 15283 15284**Example** 15285 15286For the complete sample code, see [onRequestStart](#onrequeststart12). 15287 15288## WebSchemeHandlerResponse<sup>12+</sup> 15289 15290Represents a request response. You can create a response for an intercepted request, fill in custom content, and return the response to the **Web** component. 15291 15292### constructor<sup>12+</sup> 15293 15294constructor() 15295 15296A constructor used to create a **Response** object. 15297 15298**System capability**: SystemCapability.Web.Webview.Core 15299 15300**Example** 15301 15302```ts 15303// xxx.ets 15304import { webview } from '@kit.ArkWeb'; 15305import { BusinessError } from '@kit.BasicServicesKit'; 15306import { WebNetErrorList } from '@ohos.web.netErrorList'; 15307 15308@Entry 15309@Component 15310struct WebComponent { 15311 controller: webview.WebviewController = new webview.WebviewController(); 15312 schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); 15313 15314 build() { 15315 Column() { 15316 Button('response').onClick(() => { 15317 let response = new webview.WebSchemeHandlerResponse(); 15318 try { 15319 response.setUrl("http://www.example.com") 15320 response.setStatus(200) 15321 response.setStatusText("OK") 15322 response.setMimeType("text/html") 15323 response.setEncoding("utf-8") 15324 response.setHeaderByName("header1", "value1", false) 15325 response.setNetErrorCode(WebNetErrorList.NET_OK) 15326 console.log("[schemeHandler] getUrl:" + response.getUrl()) 15327 console.log("[schemeHandler] getStatus:" + response.getStatus()) 15328 console.log("[schemeHandler] getStatusText:" + response.getStatusText()) 15329 console.log("[schemeHandler] getMimeType:" + response.getMimeType()) 15330 console.log("[schemeHandler] getEncoding:" + response.getEncoding()) 15331 console.log("[schemeHandler] getHeaderByValue:" + response.getHeaderByName("header1")) 15332 console.log("[schemeHandler] getNetErrorCode:" + response.getNetErrorCode()) 15333 15334 } catch (error) { 15335 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 15336 } 15337 }) 15338 Web({ src: 'https://www.example.com', controller: this.controller }) 15339 } 15340 } 15341} 15342 15343``` 15344 15345### setUrl<sup>12+</sup> 15346 15347setUrl(url: string): void 15348 15349Sets 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. 15350 15351**System capability**: SystemCapability.Web.Webview.Core 15352 15353**Parameters** 15354 15355| Name | Type | Mandatory | Description | 15356| --------| ------- | ---- | ---------------------------| 15357| url | string | Yes | URL to be redirected to.| 15358 15359**Example** 15360 15361For the complete sample code, see [constructor](#constructor12). 15362 15363**Error codes** 15364 15365For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15366 15367| ID| Error Message | 15368| -------- | ----------------------- | 15369| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 15370 15371### setNetErrorCode<sup>12+</sup> 15372 15373setNetErrorCode(code: WebNetErrorList): void 15374 15375Sets the network error code for this response. 15376 15377**System capability**: SystemCapability.Web.Webview.Core 15378 15379**Parameters** 15380 15381| Name | Type | Mandatory | Description | 15382| --------| ------- | ---- | ---------------------------| 15383| code | [WebNetErrorList](js-apis-netErrorList.md#webneterrorlist) | Yes | Network error code.| 15384 15385**Error codes** 15386 15387For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15388 15389| ID| Error Message | 15390| -------- | ----------------------- | 15391| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 15392 15393**Example** 15394 15395For the complete sample code, see [constructor](#constructor12). 15396 15397### setStatus<sup>12+</sup> 15398 15399setStatus(code: number): void 15400 15401Sets the HTTP status code for this response. 15402 15403**System capability**: SystemCapability.Web.Webview.Core 15404 15405**Parameters** 15406 15407| Name | Type | Mandatory | Description | 15408| --------| ------- | ---- | ---------------------------| 15409| code | number | Yes | HTTP status code.| 15410 15411**Error codes** 15412 15413For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15414 15415| ID| Error Message | 15416| -------- | ----------------------- | 15417| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 15418 15419**Example** 15420 15421For the complete sample code, see [constructor](#constructor12). 15422 15423### setStatusText<sup>12+</sup> 15424 15425setStatusText(text: string): void 15426 15427Sets the status text for this response. 15428 15429**System capability**: SystemCapability.Web.Webview.Core 15430 15431**Parameters** 15432 15433| Name | Type | Mandatory | Description | 15434| --------| ------- | ---- | ---------------------------| 15435| text | string | Yes | Status text.| 15436 15437**Error codes** 15438 15439For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15440 15441| ID| Error Message | 15442| -------- | ----------------------- | 15443| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 15444 15445**Example** 15446 15447For the complete sample code, see [constructor](#constructor12). 15448 15449### setMimeType<sup>12+</sup> 15450 15451setMimeType(type: string): void 15452 15453Sets the MIME type for this response. 15454 15455**System capability**: SystemCapability.Web.Webview.Core 15456 15457**Parameters** 15458 15459| Name | Type | Mandatory | Description | 15460| --------| ------- | ---- | ---------------------------| 15461| type | string | Yes | MIME type.| 15462 15463**Error codes** 15464 15465For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15466 15467| ID| Error Message | 15468| -------- | ----------------------- | 15469| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 15470 15471**Example** 15472 15473For the complete sample code, see [constructor](#constructor12). 15474 15475### setEncoding<sup>12+</sup> 15476 15477setEncoding(encoding: string): void 15478 15479Sets the character set for this response. 15480 15481**System capability**: SystemCapability.Web.Webview.Core 15482 15483**Parameters** 15484 15485| Name | Type | Mandatory | Description | 15486| --------| ------- | ---- | ---------------------------| 15487| encoding | string | Yes | Character set.| 15488 15489**Error codes** 15490 15491For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15492 15493| ID| Error Message | 15494| -------- | ----------------------- | 15495| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 15496 15497**Example** 15498 15499For the complete sample code, see [constructor](#constructor12). 15500 15501### setHeaderByName<sup>12+</sup> 15502 15503setHeaderByName(name: string, value: string, overwrite: boolean): void 15504 15505Sets the header information for this response. 15506 15507**System capability**: SystemCapability.Web.Webview.Core 15508 15509**Parameters** 15510 15511| Name | Type | Mandatory | Description | 15512| --------| ------- | ---- | ---------------------------| 15513| name | string | Yes | Name of the header.| 15514| value | string | Yes | Value of the header.| 15515| overwrite | boolean | Yes | Whether to override the existing header. The value **true** means to override the existing header, and **false** means the opposite.| 15516 15517**Error codes** 15518 15519For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15520 15521| ID| Error Message | 15522| -------- | ----------------------- | 15523| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 15524 15525**Example** 15526 15527For the complete sample code, see [constructor](#constructor12). 15528 15529### getUrl<sup>12+</sup> 15530 15531getUrl(): string 15532 15533Obtains the redirection URL or the URL changed due to HSTS. 15534Caution: To obtain the URL for JavaScriptProxy communication API authentication, use [getLastJavascriptProxyCallingFrameUrl<sup>12+</sup>](#getlastjavascriptproxycallingframeurl12). 15535 15536**System capability**: SystemCapability.Web.Webview.Core 15537 15538**Return value** 15539 15540| Type | Description | 15541| ------- | --------------------------------------- | 15542| string | Redirection URL or the URL changed due to HSTS.| 15543 15544**Example** 15545 15546For the complete sample code, see [constructor](#constructor12). 15547 15548### getNetErrorCode<sup>12+</sup> 15549 15550getNetErrorCode(): WebNetErrorList 15551 15552Obtains the network error code of the response. 15553 15554**System capability**: SystemCapability.Web.Webview.Core 15555 15556**Return value** 15557 15558| Type | Description | 15559| ------- | --------------------------------------- | 15560| [WebNetErrorList](js-apis-netErrorList.md#webneterrorlist) | Network error code of the response.| 15561 15562**Example** 15563 15564For the complete sample code, see [constructor](#constructor12). 15565 15566### getStatus<sup>12+</sup> 15567 15568getStatus(): number 15569 15570Obtains the HTTP status code of the response. 15571 15572**System capability**: SystemCapability.Web.Webview.Core 15573 15574**Return value** 15575 15576| Type | Description | 15577| ------- | --------------------------------------- | 15578| number | HTTP status code of the response.| 15579 15580**Example** 15581 15582For the complete sample code, see [constructor](#constructor12). 15583 15584### getStatusText<sup>12+</sup> 15585 15586getStatusText(): string 15587 15588Obtains the status text of this response. 15589 15590**System capability**: SystemCapability.Web.Webview.Core 15591 15592**Return value** 15593 15594| Type | Description | 15595| ------- | --------------------------------------- | 15596| string | Status text.| 15597 15598**Example** 15599 15600For the complete sample code, see [constructor](#constructor12). 15601 15602### getMimeType<sup>12+</sup> 15603 15604getMimeType(): string 15605 15606Obtains the MIME type of this response. 15607 15608**System capability**: SystemCapability.Web.Webview.Core 15609 15610**Return value** 15611 15612| Type | Description | 15613| ------- | --------------------------------------- | 15614| string | MIME type.| 15615 15616**Example** 15617 15618For the complete sample code, see [constructor](#constructor12). 15619 15620### getEncoding<sup>12+</sup> 15621 15622getEncoding(): string 15623 15624Obtains the character set of this response. 15625 15626**System capability**: SystemCapability.Web.Webview.Core 15627 15628**Return value** 15629 15630| Type | Description | 15631| ------- | --------------------------------------- | 15632| string | Character set.| 15633 15634**Example** 15635 15636For the complete sample code, see [constructor](#constructor12). 15637 15638### getHeaderByName<sup>12+</sup> 15639 15640getHeaderByName(name: string): string 15641 15642Obtains the character set of this response. 15643 15644**System capability**: SystemCapability.Web.Webview.Core 15645 15646**Parameters** 15647 15648| Name | Type | Mandatory| Description | 15649| ------- | ---------------- | ---- | -------------------- | 15650| name | string | Yes | Name of the header. | 15651 15652 15653**Return value** 15654 15655| Type | Description | 15656| ------- | --------------------------------------- | 15657| string | Value of the header.| 15658 15659**Example** 15660 15661For the complete sample code, see [constructor](#constructor12). 15662 15663## WebResourceHandler<sup>12+</sup> 15664 15665Represents a **WebResourceHandler** object, which can return custom response headers and response bodies to the **Web** component. 15666 15667### didReceiveResponse<sup>12+</sup> 15668 15669didReceiveResponse(response: WebSchemeHandlerResponse): void 15670 15671Sends a response header for this request. 15672 15673**System capability**: SystemCapability.Web.Webview.Core 15674 15675**Parameters** 15676 15677| Name | Type | Mandatory | Description | 15678| ---------------| ------- | ---- | ------------- | 15679| response | [WebSchemeHandlerResponse](#webschemehandlerresponse12) | Yes | Response to send.| 15680 15681**Error codes** 15682 15683For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15684 15685| ID| Error Message | 15686| -------- | ------------------------------------- | 15687| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 15688| 17100021 | The resource handler is invalid. | 15689 15690**Example** 15691 15692See [OnRequestStart](#onrequeststart12). 15693 15694### didReceiveResponseBody<sup>12+</sup> 15695 15696didReceiveResponseBody(data: ArrayBuffer): void 15697 15698Sends a response body for this request. 15699 15700**System capability**: SystemCapability.Web.Webview.Core 15701 15702**Parameters** 15703 15704| Name | Type | Mandatory | Description | 15705| ---------------| ------- | ---- | ------------- | 15706| data | ArrayBuffer | Yes | Response body.| 15707 15708**Error codes** 15709 15710For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15711 15712| ID| Error Message | 15713| -------- | ------------------------------------- | 15714| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 15715| 17100021 | The resource handler is invalid. | 15716 15717**Example** 15718 15719See [OnRequestStart](#onrequeststart12). 15720 15721### didFinish<sup>12+</sup> 15722 15723didFinish(): void 15724 15725Notifies 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. 15726 15727**System capability**: SystemCapability.Web.Webview.Core 15728 15729**Error codes** 15730 15731For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15732 15733| ID| Error Message | 15734| -------- | ------------------------------------- | 15735| 17100021 | The resource handler is invalid. | 15736 15737**Example** 15738 15739See [OnRequestStart](#onrequeststart12). 15740 15741### didFail<sup>12+</sup> 15742 15743didFail(code: WebNetErrorList): void 15744 15745Notifies the ArkWeb kernel that this request fails. Before calling this API, call [didReceiveResponse](#didreceiveresponse12) to send a response header to this request. 15746 15747**System capability**: SystemCapability.Web.Webview.Core 15748 15749**Parameters** 15750 15751| Name | Type | Mandatory | Description | 15752| --------| ------- | ---- | ---------------------------| 15753| code | [WebNetErrorList](js-apis-netErrorList.md#webneterrorlist) | Yes | Network error code.| 15754 15755**Error codes** 15756 15757For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15758 15759| ID| Error Message | 15760| -------- | ------------------------------------- | 15761| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 15762| 17100021 | The resource handler is invalid. | 15763 15764**System capability**: SystemCapability.Web.Webview.Core 15765 15766**Example** 15767 15768See [OnRequestStart](#onrequeststart12). 15769 15770## WebSchemeHandler<sup>12+</sup> 15771 15772Represents a **WebSchemeHandler** object used to intercept requests for a specific scheme. 15773 15774### onRequestStart<sup>12+</sup> 15775 15776onRequestStart(callback: (request: WebSchemeHandlerRequest, handler: WebResourceHandler) => boolean): void 15777 15778Called 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. 15779 15780**System capability**: SystemCapability.Web.Webview.Core 15781 15782**Parameters** 15783 15784| Name | Type | Mandatory| Description | 15785| -------- | -------------------- | ---- | ---------- | 15786| 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.| 15787 15788**Error codes** 15789 15790For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15791 15792| ID| Error Message | 15793| -------- | ------------------------------------- | 15794| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 15795 15796**Example** 15797 15798```ts 15799// xxx.ets 15800import { webview } from '@kit.ArkWeb'; 15801import { BusinessError } from '@kit.BasicServicesKit'; 15802import { buffer } from '@kit.ArkTS'; 15803import { WebNetErrorList } from '@ohos.web.netErrorList'; 15804 15805@Entry 15806@Component 15807struct WebComponent { 15808 controller: webview.WebviewController = new webview.WebviewController(); 15809 schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); 15810 htmlData: string = "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>"; 15811 15812 build() { 15813 Column() { 15814 Web({ src: 'https://www.example.com', controller: this.controller }) 15815 .onControllerAttached(() => { 15816 try { 15817 this.schemeHandler.onRequestStart((request: webview.WebSchemeHandlerRequest, resourceHandler: webview.WebResourceHandler) => { 15818 console.log("[schemeHandler] onRequestStart"); 15819 try { 15820 console.log("[schemeHandler] onRequestStart url:" + request.getRequestUrl()); 15821 console.log("[schemeHandler] onRequestStart method:" + request.getRequestMethod()); 15822 console.log("[schemeHandler] onRequestStart referrer:" + request.getReferrer()); 15823 console.log("[schemeHandler] onRequestStart isMainFrame:" + request.isMainFrame()); 15824 console.log("[schemeHandler] onRequestStart hasGesture:" + request.hasGesture()); 15825 console.log("[schemeHandler] onRequestStart header size:" + request.getHeader().length); 15826 console.log("[schemeHandler] onRequestStart resource type:" + request.getRequestResourceType()); 15827 console.log("[schemeHandler] onRequestStart frame url:" + request.getFrameUrl()); 15828 let header = request.getHeader(); 15829 for (let i = 0; i < header.length; i++) { 15830 console.log("[schemeHandler] onRequestStart header:" + header[i].headerKey + " " + header[i].headerValue); 15831 } 15832 let stream = request.getHttpBodyStream(); 15833 if (stream) { 15834 console.log("[schemeHandler] onRequestStart has http body stream"); 15835 } else { 15836 console.log("[schemeHandler] onRequestStart has no http body stream"); 15837 } 15838 } catch (error) { 15839 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 15840 } 15841 15842 if (request.getRequestUrl().endsWith("example.com")) { 15843 return false; 15844 } 15845 15846 let response = new webview.WebSchemeHandlerResponse(); 15847 try { 15848 response.setNetErrorCode(WebNetErrorList.NET_OK); 15849 response.setStatus(200); 15850 response.setStatusText("OK"); 15851 response.setMimeType("text/html"); 15852 response.setEncoding("utf-8"); 15853 response.setHeaderByName("header1", "value1", false); 15854 } catch (error) { 15855 console.error(`[schemeHandler] ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 15856 } 15857 15858 // Before calling didFinish or didFail, call didReceiveResponse to send a response header to this request. 15859 let buf = buffer.from(this.htmlData) 15860 try { 15861 if (buf.length == 0) { 15862 console.log("[schemeHandler] length 0"); 15863 resourceHandler.didReceiveResponse(response); 15864 // If the value of buf.length is 0 in normal cases, call resourceHandler.didFinish(). Otherwise, call resourceHandler.didFail(). 15865 resourceHandler.didFail(WebNetErrorList.ERR_FAILED); 15866 } else { 15867 console.log("[schemeHandler] length 1"); 15868 resourceHandler.didReceiveResponse(response); 15869 resourceHandler.didReceiveResponseBody(buf.buffer); 15870 resourceHandler.didFinish(); 15871 } 15872 } catch (error) { 15873 console.error(`[schemeHandler] ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 15874 } 15875 return true; 15876 }) 15877 15878 this.schemeHandler.onRequestStop((request: webview.WebSchemeHandlerRequest) => { 15879 console.log("[schemeHandler] onRequestStop"); 15880 }); 15881 15882 this.controller.setWebSchemeHandler('https', this.schemeHandler); 15883 } catch (error) { 15884 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 15885 } 15886 }) 15887 .javaScriptAccess(true) 15888 .domStorageAccess(true) 15889 } 15890 } 15891} 15892``` 15893### onRequestStop<sup>12+</sup> 15894 15895onRequestStop(callback: Callback\<WebSchemeHandlerRequest\>): void 15896 15897Called 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: 15898 158991. The **WebResourceHandler** object calls **didFail** or **didFinish**. 15900 159012. The request is interrupted due to other reasons. 15902 15903**System capability**: SystemCapability.Web.Webview.Core 15904 15905**Parameters** 15906 15907| Name | Type | Mandatory| Description | 15908| -------- | -------------------- | ---- | ---------- | 15909| callback | Callback\<[WebSchemeHandlerRequest](#webschemehandlerrequest12)\> | Yes | Callback invoked when the request is complete.| 15910 15911**Error codes** 15912 15913For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15914 15915| ID| Error Message | 15916| -------- | ------------------------------------- | 15917| 401 | Invalid input parameter. | 15918 15919**Example** 15920 15921For the complete sample code, see [onRequestStart](#onrequeststart12). 15922 15923## CacheOptions<sup>12+</sup> 15924 15925Represents 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. 15926 15927**System capability**: SystemCapability.Web.Webview.Core 15928 15929| Name | Type | Readable| Writable|Description | 15930| ----------- | ------ | -----|------|------------------- | 15931| 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. | 15932 15933## PlaybackStatus<sup>12+</sup> 15934 15935Represents the playback status of the player, functioning as a parameter in [handleStatusChanged](#handlestatuschanged12). 15936 15937**System capability**: SystemCapability.Web.Webview.Core 15938 15939| Name| Value| Description| 15940|------|----|------| 15941| PAUSED | 0 | Playing.| 15942| PLAYING | 1 | Paused.| 15943 15944## NetworkState<sup>12+<sup> 15945 15946Describes the network status of the player. 15947 15948**System capability**: SystemCapability.Web.Webview.Core 15949 15950| Name| Value| Description| 15951|------|----|------| 15952| EMPTY | 0 | The player has not started downloading data.| 15953| 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.| 15954| LOADING | 2 | The player is downloading media data.| 15955| NETWORK_ERROR | 3 | A network error occurs.| 15956 15957## ReadyState<sup>12+<sup> 15958 15959Enumerates the cache states of the player. 15960 15961**System capability**: SystemCapability.Web.Webview.Core 15962 15963| Name| Value| Description| 15964|------|----|------| 15965| HAVE_NOTHING | 0 | There is no data cached.| 15966| HAVE_METADATA | 1 | Only media metadata is cached.| 15967| HAVE_CURRENT_DATA | 2 | Data up to the current playback position is cached.| 15968| HAVE_FUTURE_DATA | 3 | Data beyond the current playback position is cached, but there might still be stutters during playback.| 15969| HAVE_ENOUGH_DATA | 4 | Sufficient data has been cached to ensure smooth playback.| 15970 15971## MediaError<sup>12+<sup> 15972 15973Enumerates the error types of the player. 15974 15975**System capability**: SystemCapability.Web.Webview.Core 15976 15977| Name| Value| Description| 15978|------|----|------| 15979| NETWORK_ERROR | 1 | Network error.| 15980| FORMAT_ERROR | 2 | Media format error.| 15981| DECODE_ERROR | 3 | Decoding error.| 15982 15983## NativeMediaPlayerHandler<sup>12+<sup> 15984 15985Represents a **NativeMediaPlayerHandler** object used as the parameter of the [CreateNativeMediaPlayerCallback](#createnativemediaplayercallback12) callback. 15986The application uses this object to report the player status to the ArkWeb engine. 15987 15988### handleStatusChanged<sup>12+<sup> 15989 15990handleStatusChanged(status: PlaybackStatus): void 15991 15992Called to notify the ArkWeb engine of the playback status of the player when the playback status changes. 15993 15994**System capability**: SystemCapability.Web.Webview.Core 15995 15996**Parameters** 15997 15998| Name| Type| Mandatory| Description| 15999|--------|------|------|------| 16000| status | [PlaybackStatus](#playbackstatus12) | Yes| Player status.| 16001 16002**Example** 16003 16004For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16005 16006### handleVolumeChanged<sup>12+<sup> 16007 16008handleVolumeChanged(volume: number): void 16009 16010Called to notify the ArkWeb engine of the volume of the player when the volume changes. 16011 16012**System capability**: SystemCapability.Web.Webview.Core 16013 16014**Parameters** 16015 16016| Name| Type| Mandatory| Description| 16017|--------|------|------|------| 16018| volume | number | Yes| Volume of the player.| 16019 16020**Example** 16021 16022For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16023 16024### handleMutedChanged<sup>12+<sup> 16025 16026handleMutedChanged(muted: boolean): void 16027 16028Called to notify the ArkWeb engine of the muted status of the player when the muted status changes. 16029 16030**System capability**: SystemCapability.Web.Webview.Core 16031 16032**Parameters** 16033 16034| Name| Type| Mandatory| Description| 16035|--------|------|------|------| 16036| muted | boolean | Yes| Whether the player is muted.| 16037 16038**Example** 16039 16040For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16041 16042### handlePlaybackRateChanged<sup>12+<sup> 16043 16044handlePlaybackRateChanged(playbackRate: number): void 16045 16046Called to notify the ArkWeb engine of the playback rate of the player when the playback rate changes. 16047 16048**System capability**: SystemCapability.Web.Webview.Core 16049 16050**Parameters** 16051 16052| Name| Type| Mandatory| Description| 16053|--------|------|------|------| 16054| playbackRate | number | Yes| Playback rate.| 16055 16056**Example** 16057 16058For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16059 16060### handleDurationChanged<sup>12+<sup> 16061 16062handleDurationChanged(duration: number): void 16063 16064Called to notify the ArkWeb engine of the total duration of the media. 16065 16066**System capability**: SystemCapability.Web.Webview.Core 16067 16068**Parameters** 16069 16070| Name| Type| Mandatory| Description| 16071|--------|------|------|------| 16072| duration | number | Yes| Total duration of the media. Unit: second.| 16073 16074**Example** 16075 16076For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16077 16078### handleTimeUpdate<sup>12+<sup> 16079 16080handleTimeUpdate(currentPlayTime: number): void 16081 16082Called to notify the ArkWeb engine of the playback progress when the playback progress changes. 16083 16084**System capability**: SystemCapability.Web.Webview.Core 16085 16086**Parameters** 16087 16088| Name| Type| Mandatory| Description| 16089|--------|------|------|------| 16090| currentPlayTime | number | Yes| Current progress. Unit: second. | 16091 16092**Example** 16093 16094For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16095 16096### handleBufferedEndTimeChanged<sup>12+<sup> 16097 16098handleBufferedEndTimeChanged(bufferedEndTime: number): void 16099 16100Called to notify the ArkWeb engine of the buffer time when the buffer time changes. 16101 16102**System capability**: SystemCapability.Web.Webview.Core 16103 16104**Parameters** 16105 16106| Name| Type| Mandatory| Description| 16107|--------|------|------|------| 16108| bufferedEndTime | number | Yes| Duration of media data in the buffer.| 16109 16110**Example** 16111 16112For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16113 16114### handleEnded<sup>12+<sup> 16115 16116handleEnded(): void 16117 16118Called to notify the ArkWeb engine that the media playback ends. 16119 16120**System capability**: SystemCapability.Web.Webview.Core 16121 16122**Example** 16123 16124For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16125 16126### handleNetworkStateChanged<sup>12+<sup> 16127 16128handleNetworkStateChanged(state: NetworkState): void 16129 16130Called to notify the ArkWeb engine of the network status of the player when the network status changes. 16131 16132**System capability**: SystemCapability.Web.Webview.Core 16133 16134**Parameters** 16135 16136| Name| Type| Mandatory| Description| 16137|--------|------|------|------| 16138| state | [NetworkState](#networkstate12) | Yes| Network status of the player.| 16139 16140**Example** 16141 16142For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16143 16144### handleReadyStateChanged<sup>12+<sup> 16145 16146handleReadyStateChanged(state: ReadyState): void 16147 16148Called to notify the ArkWeb engine of the cache status of the player when the cache status changes. 16149 16150**System capability**: SystemCapability.Web.Webview.Core 16151 16152**Parameters** 16153 16154| Name| Type| Mandatory| Description| 16155|--------|------|------|------| 16156| state | [ReadyState](#readystate12) | Yes| Cache status of the player.| 16157 16158**Example** 16159 16160For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16161 16162### handleFullscreenChanged<sup>12+<sup> 16163 16164handleFullscreenChanged(fullscreen: boolean): void 16165 16166Called to notify the ArkWeb engine of the full screen status of the player when the full screen status changes. 16167 16168**System capability**: SystemCapability.Web.Webview.Core 16169 16170**Parameters** 16171 16172| Name| Type| Mandatory| Description| 16173|--------|------|------|------| 16174| fullscreen | boolean | Yes| Whether the player is in full screen.| 16175 16176**Example** 16177 16178For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16179 16180### handleSeeking<sup>12+<sup> 16181 16182handleSeeking(): void 16183 16184Called to notify the ArkWeb engine that the player enters the seek state. 16185 16186**System capability**: SystemCapability.Web.Webview.Core 16187 16188**Example** 16189 16190For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16191 16192### handleSeekFinished<sup>12+<sup> 16193 16194handleSeekFinished(): void 16195 16196Called to notify the ArkWeb engine that the seek operation is complete. 16197 16198**System capability**: SystemCapability.Web.Webview.Core 16199 16200**Example** 16201 16202For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16203 16204### handleError<sup>12+<sup> 16205 16206handleError(error: MediaError, errorMessage: string): void 16207 16208Called to notify the ArkWeb engine that an error occurs with the player. 16209 16210**System capability**: SystemCapability.Web.Webview.Core 16211 16212**Parameters** 16213 16214| Name| Type| Mandatory| Description| 16215|--------|------|------|------| 16216| error | [MediaError](#mediaerror12) | Yes| Error object type.| 16217| errorMessage | string | Yes| Error message.| 16218 16219**Example** 16220 16221For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16222 16223### handleVideoSizeChanged<sup>12+<sup> 16224 16225handleVideoSizeChanged(width: number, height: number): void 16226 16227Called to notify the ArkWeb engine of the video size of the player. 16228 16229**System capability**: SystemCapability.Web.Webview.Core 16230 16231**Parameters** 16232 16233| Name| Type| Mandatory| Description| 16234|--------|------|------|------| 16235| width | number | Yes| Video width.| 16236| height | number | Yes| Video height.| 16237 16238**Example** 16239 16240For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16241 16242## SuspendType<sup>12+<sup> 16243 16244Enumerates the suspension types of the player. 16245 16246**System capability**: SystemCapability.Web.Webview.Core 16247 16248| Name| Value| Description| 16249|------|----|------| 16250| ENTER_BACK_FORWARD_CACHE | 0 | The page enters the BFCache.| 16251| ENTER_BACKGROUND | 1 | The page is displayed in the background.| 16252| AUTO_CLEANUP | 2 | The page is automatically cleaned up by the system.| 16253 16254## NativeMediaPlayerBridge<sup>12+<sup> 16255 16256Implements a **NativeMediaPlayerBridge** object, which is the return value of the [CreateNativeMediaPlayerCallback](#createnativemediaplayercallback12) callback. 16257It is an API class that acts as a bridge between the web media player and the ArkWeb kernel. 16258The ArkWeb engine uses an object of this interface class to control the player created by the application to take over web page media. 16259 16260### updateRect<sup>12+<sup> 16261 16262updateRect(x: number, y: number, width: number, height: number): void 16263 16264Updates the surface position information. 16265 16266**System capability**: SystemCapability.Web.Webview.Core 16267 16268**Parameters** 16269 16270| Name| Type| Mandatory| Description| 16271|--------|------|------|------| 16272| x | number | Yes| X coordinate of the surface relative to the web component.| 16273| y | number | Yes| Y coordinate of the surface relative to the web component.| 16274| width | number | Yes| Width of the surface.| 16275| height | number | Yes| Height of the surface.| 16276 16277**Example** 16278 16279For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16280 16281### play<sup>12+<sup> 16282 16283play(): void 16284 16285Plays this video. 16286 16287**System capability**: SystemCapability.Web.Webview.Core 16288 16289**Example** 16290 16291For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16292 16293### pause<sup>12+<sup> 16294 16295pause(): void 16296 16297Pauses playback. 16298 16299**System capability**: SystemCapability.Web.Webview.Core 16300 16301**Example** 16302 16303For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16304 16305### seek<sup>12+<sup> 16306 16307seek(targetTime: number): void 16308 16309Seeks to a specific time point in the media. 16310 16311**System capability**: SystemCapability.Web.Webview.Core 16312 16313**Parameters** 16314 16315| Name| Type| Mandatory| Description| 16316|--------|------|------|------| 16317| targetTime | number | Yes| Target time point. Unit: second.| 16318 16319**Example** 16320 16321For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16322 16323### setVolume<sup>12+<sup> 16324 16325setVolume(volume: number): void 16326 16327Sets the playback volume. 16328The value range is [0, 1.0]. 16329 16330**Parameters** 16331 16332| Name| Type| Mandatory| Description| 16333|--------|------|------|------| 16334| 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.| 16335 16336**System capability**: SystemCapability.Web.Webview.Core 16337 16338**Example** 16339 16340For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16341 16342### setMuted<sup>12+<sup> 16343 16344setMuted(muted: boolean): void 16345 16346Sets the muted status. 16347 16348**System capability**: SystemCapability.Web.Webview.Core 16349 16350**Parameters** 16351 16352| Name| Type| Mandatory| Description| 16353|--------|------|------|------| 16354| muted | boolean | Yes| Whether to mute the player.| 16355 16356**Example** 16357 16358For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16359 16360### setPlaybackRate<sup>12+<sup> 16361 16362setPlaybackRate(playbackRate: number): void 16363 16364Sets the playback rate. 16365The value range is [0, 10.0]. 16366 16367**System capability**: SystemCapability.Web.Webview.Core 16368 16369**Parameters** 16370 16371| Name| Type| Mandatory| Description| 16372|--------|------|------|------| 16373| playbackRate | number | Yes| Playback rate. The value range is [0, 10.0]. The value **1** indicates the original speed of playback.| 16374 16375**Example** 16376 16377For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16378 16379### release<sup>12+<sup> 16380 16381release(): void 16382 16383Releases this player. 16384 16385**System capability**: SystemCapability.Web.Webview.Core 16386 16387**Example** 16388 16389For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16390 16391### enterFullscreen<sup>12+<sup> 16392 16393enterFullscreen(): void 16394 16395Enables the player to enter full screen mode. 16396 16397**System capability**: SystemCapability.Web.Webview.Core 16398 16399**Example** 16400 16401For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16402 16403### exitFullscreen<sup>12+<sup> 16404 16405exitFullscreen(): void 16406 16407Enables the player to exit full screen mode. 16408 16409**System capability**: SystemCapability.Web.Webview.Core 16410 16411**Example** 16412 16413For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16414 16415### resumePlayer<sup>12+<sup> 16416 16417resumePlayer?(): void 16418 16419Resumes the player and its status information. 16420 16421**System capability**: SystemCapability.Web.Webview.Core 16422 16423**Example** 16424 16425For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16426 16427### suspendPlayer<sup>12+<sup> 16428 16429suspendPlayer?(type: SuspendType): void 16430 16431Suspends the player and save its status information. 16432 16433**System capability**: SystemCapability.Web.Webview.Core 16434 16435**Parameters** 16436 16437| Name| Type| Mandatory| Description| 16438|--------|------|------|------| 16439| type | [SuspendType](#suspendtype12) | Yes| Suspension type of the player.| 16440 16441**Example** 16442 16443For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16444 16445## MediaType<sup>12+<sup> 16446 16447Enumerates the media types. 16448 16449**System capability**: SystemCapability.Web.Webview.Core 16450 16451| Name| Value| Description| 16452|------|----|------| 16453| VIDEO | 0 | Video.| 16454| AUDIO | 1 | Audio.| 16455 16456## SourceType<sup>12+<sup> 16457 16458Enumerates the media source types. 16459 16460**System capability**: SystemCapability.Web.Webview.Core 16461 16462| Name| Value| Description| 16463|------|----|------| 16464| URL | 0 | URL.| 16465| MSE | 1 | Blob.| 16466 16467## MediaSourceInfo<sup>12+<sup> 16468 16469Provides the information about the media source. 16470 16471**System capability**: SystemCapability.Web.Webview.Core 16472 16473| Name| Type| Mandatory| Description| 16474|------|------|------|------| 16475| type | [SourceType](#sourcetype12) | Yes| Type of the media source.| 16476| source | string | Yes| Address of the media source.| 16477| format | string | Yes| Format of the media source, which may be empty. You need to determine the format by yourself.| 16478 16479## NativeMediaPlayerSurfaceInfo<sup>12+<sup> 16480 16481Provides 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). 16482 16483**System capability**: SystemCapability.Web.Webview.Core 16484 16485| Name| Type| Mandatory| Description| 16486|------|------|------|------| 16487| 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).| 16488| rect | [RectEvent](#rectevent12) | Yes| Position of the surface.| 16489 16490## Preload<sup>12+<sup> 16491 16492Defines how the player preloads media data. 16493 16494**System capability**: SystemCapability.Web.Webview.Core 16495 16496| Name| Value| Description| 16497|------|----|------| 16498| NONE | 0 | No media data is preloaded.| 16499| METADATA | 1 | Only the metadata of the media is preloaded.| 16500| AUTO | 2 | A sufficient amount of media data is preloaded to ensure smooth playback| 16501 16502## MediaInfo<sup>12+<sup> 16503 16504Represents a **MediaInfo** object used as a parameter of the [CreateNativeMediaPlayerCallback](#createnativemediaplayercallback12) callback. 16505The 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 . 16506 16507**System capability**: SystemCapability.Web.Webview.Core 16508 16509| Name| Type| Mandatory| Description| 16510|------|------|------|------| 16511| embedID | string | Yes| ID of **\<video>** or **\<audio>** on the web page.| 16512| mediaType | [MediaType](#mediatype12) | Yes| Type of the media.| 16513| mediaSrcList | [MediaSourceInfo](#mediasourceinfo12)[] | Yes| Source of the media. There may be multiple sources. The application needs to select a supported source to play.| 16514| surfaceInfo | [NativeMediaPlayerSurfaceInfo](#nativemediaplayersurfaceinfo12) | Yes| Surface information used for same-layer rendering.| 16515| controlsShown | boolean | Yes| Whether the **controls** attribute exists in **\<video>** or **\<audio>**.| 16516| controlList | string[] | Yes| Value of the **controlslist** attribute in **\<video>** or **\<audio>**.| 16517| muted | boolean | Yes| Whether to mute the player.| 16518| posterUrl | string | Yes| URL of a poster.| 16519| preload | [Preload](#preload12) | Yes| Whether preloading is required.| 16520| headers | Record\<string, string\> | Yes| HTTP headers that need to be included in the player's request for media resources.| 16521| attributes | Record\<string, string\> | Yes| Attributes in **\<video>** or **\<audio>**.| 16522 16523 16524## CreateNativeMediaPlayerCallback<sup>12+<sup> 16525 16526type CreateNativeMediaPlayerCallback = (handler: NativeMediaPlayerHandler, mediaInfo: MediaInfo) => NativeMediaPlayerBridge 16527 16528Represents a **CreateNativeMediaPlayerCallback** object used as a parameter of the [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12) callback. 16529This object is used to create a player to take over media playback of the web page. 16530 16531**System capability**: SystemCapability.Web.Webview.Core 16532 16533**Parameters** 16534 16535| Name| Type| Mandatory| Description| 16536|--------|------|------|------| 16537| handler | [NativeMediaPlayerHandler](#nativemediaplayerhandler12) | Yes| Object used to report the player status to the ArkWeb engine.| 16538| mediaInfo | [MediaInfo](#mediainfo12) | Yes| Information about the media on the web page.| 16539 16540**Return value** 16541 16542| Type| Description| 16543|------|------| 16544| [NativeMediaPlayerBridge](#nativemediaplayerbridge12) | Instance of the API 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 engine.| 16545 16546**Example** 16547 16548For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16549 16550## OfflineResourceMap<sup>12+</sup> 16551 16552Implements 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. 16553 16554**System capability**: SystemCapability.Web.Webview.Core 16555 16556| Name | Type | Readable| Writable|Description | 16557| ----------- | ------ | -----|------|------------------- | 16558| 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. | 16559| resource | Uint8Array | Yes | Yes | Content of a local offline resource. | 16560| 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**. | 16561| type | [OfflineResourceType](#offlineresourcetype12) | Yes | Yes | Resource type. Currently, only the JavaScript, image, and CSS types are supported. | 16562 16563## OfflineResourceType<sup>12+</sup> 16564 16565Represents the local offline resource type corresponding to an [OfflineResourceMap](#offlineresourcemap12) object. 16566 16567**System capability**: SystemCapability.Web.Webview.Core 16568 16569| Name | Value| Description | 16570| ------------ | -- |--------------------------------- | 16571| IMAGE | 0 | Resource of the image type.| 16572| CSS | 1 | Resource of the CSS type.| 16573| CLASSIC_JS | 2 | Javascript resource loaded through the <script src="" /\> tag.| 16574| MODULE_JS | 3 |Javascript resource loaded through the <script src="" type="module" /\> tag.| 16575 16576## WebResourceType<sup>12+</sup> 16577 16578Enumerates the types of requested resources. 16579 16580**System capability**: SystemCapability.Web.Webview.Core 16581 16582| Name | Value| Description | 16583| ------------ | -- |--------------------------------- | 16584| MAIN_FRAME | 0 | Top-level page.| 16585| SUB_FRAME | 1 | Frame or Iframe.| 16586| STYLE_SHEET | 2 | CSS style sheet.| 16587| SCRIPT | 3 | External script.| 16588| IMAGE | 4 | Image (JPG, GIF, PNG, or other format).| 16589| FONT_RESOURCE | 5 | Font.| 16590| SUB_RESOURCE | 6 | Other sub-resource. If the type is unknown, it is used as the default type.| 16591| OBJECT | 7 | Object (or embed) tag of the plug-in, or the resource requested by the plug-in.| 16592| MEDIA | 8 | Media resource.| 16593| WORKER | 9 | Main resource of a dedicated worker thread.| 16594| SHARED_WORKER | 10 | Main resource of a shared worker thread.| 16595| PREFETCH | 11 | Explicit prefetch request.| 16596| FAVICON | 12 | Website icon.| 16597| XHR | 13 | XMLHttpRequest.| 16598| PING | 14 | <a ping\>/sendBeacon ping request.| 16599| SERVICE_WORKER | 15 | Main resource of a service worker.| 16600| CSP_REPORT | 16 | Report of Content Security Policy violation.| 16601| PLUGIN_RESOURCE | 17 | Resource requested by the plug-in.| 16602| NAVIGATION_PRELOAD_MAIN_FRAME | 19 | Main frame redirection request that triggers service worker preloading.| 16603| NAVIGATION_PRELOAD_SUB_FRAME | 20 | Subframe redirection request that triggers service worker preloading.| 16604 16605## RectEvent<sup>12+<sup> 16606 16607Defines a rectangle. 16608 16609**System capability**: SystemCapability.Web.Webview.Core 16610 16611| Name | Type | Readable| Writable| Description | 16612| -------------- | --------- | ---- | ---- | ---------------------------- | 16613| x | number | Yes | Yes | X-axis coordinate of the upper left corner of the rectangle. | 16614| y | number | Yes | Yes | Y-axis coordinate of the upper left corner of the rectangle. | 16615| width | number | Yes | Yes | Width of the rectangle. | 16616| height | number | Yes | Yes | Height of the rectangle. | 16617 16618## BackForwardCacheSupportedFeatures<sup>12+<sup> 16619 16620Adds a page that uses any of the following features to the back-forward cache. For the complete sample code, see [enableBackForwardCache](#enablebackforwardcache12). 16621 16622**System capability**: SystemCapability.Web.Webview.Core 16623 16624| Name| Type| Mandatory| Description| 16625|------|------|------|------| 16626| nativeEmbed | boolean | 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.| 16627| mediaTakeOver | boolean | 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.| 16628 16629### constructor<sup>12+</sup> 16630 16631constructor() 16632 16633Constructs a **BackForwardCacheOptions** instance. 16634 16635**System capability**: SystemCapability.Web.Webview.Core 16636 16637## BackForwardCacheOptions<sup>12+<sup> 16638 16639Implements a **BackForwardCacheOptions** object to set back-forward cache options of the **Web** component. For the complete sample code, see [BackForwardCacheOptions](#backforwardcacheoptions12). 16640 16641**System capability**: SystemCapability.Web.Webview.Core 16642 16643| Name| Type| Mandatory| Description| 16644|------|------|------|------| 16645| 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.| 16646| 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.| 16647 16648### constructor<sup>12+</sup> 16649 16650constructor() 16651 16652Constructs a **BackForwardCacheOptions** instance. 16653 16654**System capability**: SystemCapability.Web.Webview.Core 16655 16656## AdsBlockManager<sup>12+</sup> 16657 16658Implements 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. 16659 16660### setAdsBlockRules<sup>12+</sup> 16661 16662static setAdsBlockRules(rulesFile: string, replace: boolean): void 16663 16664Sets a custom ad blocking rule file that conforms to the universal EasyList syntax in the **Web** components. 16665 16666> **NOTE** 16667> 16668> 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. 16669 16670**System capability**: SystemCapability.Web.Webview.Core 16671 16672**Parameters** 16673 16674| Name | Type | Mandatory| Description | 16675| ---------- | ------ | ---- | -------------------------------- | 16676| 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.| 16677| 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.| 16678 16679**Error codes** 16680 16681For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 16682 16683| ID| Error Message | 16684| -------- | ----------------------- | 16685| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 16686 16687**Example** 16688 16689```ts 16690// xxx.ets 16691import { webview } from '@kit.ArkWeb'; 16692import { picker, fileUri } from '@kit.CoreFileKit'; 16693 16694// 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. 16695@Entry 16696@Component 16697struct WebComponent { 16698 controller: webview.WebviewController = new webview.WebviewController(); 16699 16700 build() { 16701 Row() { 16702 Flex() { 16703 Button({ type: ButtonType.Capsule }) { 16704 Text("setAdsBlockRules") 16705 } 16706 .onClick(() => { 16707 try { 16708 let documentSelectionOptions: ESObject = new picker.DocumentSelectOptions(); 16709 let documentPicker: ESObject = new picker.DocumentViewPicker(); 16710 documentPicker.select(documentSelectionOptions).then((documentSelectResult: ESObject) => { 16711 if (documentSelectResult && documentSelectResult.length > 0) { 16712 let fileRealPath = new fileUri.FileUri(documentSelectResult[0]); 16713 console.info('DocumentViewPicker.select successfully, uri: ' + fileRealPath); 16714 webview.AdsBlockManager.setAdsBlockRules(fileRealPath.path, true); 16715 } 16716 }) 16717 } catch (err) { 16718 console.error('DocumentViewPicker.select failed with err:' + err); 16719 } 16720 }) 16721 } 16722 } 16723 } 16724} 16725``` 16726 16727### addAdsBlockDisallowedList<sup>12+</sup> 16728 16729static addAdsBlockDisallowedList(domainSuffixes: Array\<string\>): void 16730 16731Adds 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. 16732 16733> **NOTE** 16734> 16735> The domain name set by this API is not persistent; they need to be set again after the application is restarted. 16736> 16737> 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**. 16738 16739**System capability**: SystemCapability.Web.Webview.Core 16740 16741**Parameters** 16742 16743| Name | Type | Mandatory| Description | 16744| ---------- | ------ | ---- | -------------------------------- | 16745| domainSuffixes | Array\<string\> | Yes | Array of domain names, for example, ['example.com', 'abcd.efg.com'].| 16746 16747**Error codes** 16748 16749For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 16750 16751| ID| Error Message | 16752| -------- | ----------------------- | 16753| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 16754 16755**Example** 16756 16757```ts 16758// xxx.ets 16759import { webview } from '@kit.ArkWeb'; 16760 16761// This example demonstrates how to click a button to add an array of domain names to the disallowed list. 16762@Entry 16763@Component 16764struct WebComponent { 16765 main_url: string = 'https://www.example.com'; 16766 text_input_controller: TextInputController = new TextInputController(); 16767 controller: webview.WebviewController = new webview.WebviewController(); 16768 @State input_text: string = 'https://www.example.com'; 16769 16770 build() { 16771 Column() { 16772 Row() { 16773 Flex() { 16774 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 16775 .id("input_url") 16776 .height(40) 16777 .margin(5) 16778 .borderColor(Color.Blue) 16779 .onChange((value: string) => { 16780 this.input_text = value; 16781 }) 16782 16783 Button({type: ButtonType.Capsule}) { Text("Go") } 16784 .onClick(() => { 16785 this.controller.loadUrl(this.input_text); 16786 }) 16787 16788 Button({type: ButtonType.Capsule}) { Text("addAdsBlockDisallowedList") } 16789 .onClick(() => { 16790 let arrDomainSuffixes = new Array<string>(); 16791 arrDomainSuffixes.push('example.com'); 16792 arrDomainSuffixes.push('abcdefg.cn'); 16793 webview.AdsBlockManager.addAdsBlockDisallowedList(arrDomainSuffixes); 16794 }) 16795 } 16796 } 16797 Web({ src: this.main_url, controller: this.controller }) 16798 .onControllerAttached(()=>{ 16799 this.controller.enableAdsBlock(true); 16800 }) 16801 } 16802 } 16803} 16804``` 16805 16806### removeAdsBlockDisallowedList<sup>12+</sup> 16807 16808static removeAdsBlockDisallowedList(domainSuffixes: Array\<string\>): void 16809 16810Removes an array of domain names from the disallowed list of this **AdsBlockManager** object. 16811 16812> **NOTE** 16813> 16814> 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. 16815 16816**System capability**: SystemCapability.Web.Webview.Core 16817 16818**Parameters** 16819 16820| Name | Type | Mandatory| Description | 16821| ---------- | ------ | ---- | -------------------------------- | 16822| domainSuffixes | Array\<string\> | Yes | Array of domain names, for example, ['example.com', 'abcd.efg.com'].| 16823 16824**Error codes** 16825 16826For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 16827 16828| ID| Error Message | 16829| -------- | ----------------------- | 16830| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 16831 16832**Example** 16833 16834```ts 16835// xxx.ets 16836import { webview } from '@kit.ArkWeb'; 16837 16838// This example demonstrates how to click a button to remove an array of domain names from the disallowed list. 16839@Entry 16840@Component 16841struct WebComponent { 16842 main_url: string = 'https://www.example.com'; 16843 text_input_controller: TextInputController = new TextInputController(); 16844 controller: webview.WebviewController = new webview.WebviewController(); 16845 @State input_text: string = 'https://www.example.com'; 16846 16847 build() { 16848 Column() { 16849 Row() { 16850 Flex() { 16851 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 16852 .id("input_url") 16853 .height(40) 16854 .margin(5) 16855 .borderColor(Color.Blue) 16856 .onChange((value: string) => { 16857 this.input_text = value; 16858 }) 16859 16860 Button({type: ButtonType.Capsule}) { Text("Go") } 16861 .onClick(() => { 16862 this.controller.loadUrl(this.input_text); 16863 }) 16864 16865 Button({type: ButtonType.Capsule}) { Text("removeAdsBlockDisallowedList") } 16866 .onClick(() => { 16867 let arrDomainSuffixes = new Array<string>(); 16868 arrDomainSuffixes.push('example.com'); 16869 arrDomainSuffixes.push('abcdefg.cn'); 16870 webview.AdsBlockManager.removeAdsBlockDisallowedList(arrDomainSuffixes); 16871 }) 16872 } 16873 } 16874 Web({ src: this.main_url, controller: this.controller }) 16875 .onControllerAttached(()=>{ 16876 this.controller.enableAdsBlock(true); 16877 }) 16878 } 16879 } 16880} 16881``` 16882 16883### clearAdsBlockDisallowedList<sup>12+</sup> 16884 16885static clearAdsBlockDisallowedList(): void 16886 16887Clears the disallowed list of this **AdsBlockManager** object. 16888 16889**System capability**: SystemCapability.Web.Webview.Core 16890 16891**Example** 16892 16893```ts 16894// xxx.ets 16895import { webview } from '@kit.ArkWeb'; 16896 16897@Entry 16898@Component 16899struct WebComponent { 16900 main_url: string = 'https://www.example.com'; 16901 text_input_controller: TextInputController = new TextInputController(); 16902 controller: webview.WebviewController = new webview.WebviewController(); 16903 @State input_text: string = 'https://www.example.com'; 16904 16905 build() { 16906 Column() { 16907 Row() { 16908 Flex() { 16909 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 16910 .id("input_url") 16911 .height(40) 16912 .margin(5) 16913 .borderColor(Color.Blue) 16914 .onChange((value: string) => { 16915 this.input_text = value; 16916 }) 16917 16918 Button({type: ButtonType.Capsule}) { Text("Go") } 16919 .onClick(() => { 16920 this.controller.loadUrl(this.input_text); 16921 }) 16922 16923 Button({type: ButtonType.Capsule}) { Text("clearAdsBlockDisallowedList") } 16924 .onClick(() => { 16925 webview.AdsBlockManager.clearAdsBlockDisallowedList(); 16926 }) 16927 } 16928 } 16929 Web({ src: this.main_url, controller: this.controller }) 16930 .onControllerAttached(()=>{ 16931 this.controller.enableAdsBlock(true); 16932 }) 16933 } 16934 } 16935} 16936``` 16937 16938### addAdsBlockAllowedList<sup>12+</sup> 16939 16940static addAdsBlockAllowedList(domainSuffixes: Array\<string\>): void 16941 16942Adds 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. 16943 16944> **NOTE** 16945> 16946> The domain name set by this API is not persistent; they need to be set again after the application is restarted. 16947> 16948> 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. 16949 16950**System capability**: SystemCapability.Web.Webview.Core 16951 16952**Parameters** 16953 16954| Name | Type | Mandatory| Description | 16955| ---------- | ------ | ---- | -------------------------------- | 16956| domainSuffixes | Array\<string\> | Yes | Array of domain names, for example, ['example.com', 'abcd.efg.com'].| 16957 16958**Error codes** 16959 16960For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 16961 16962| ID| Error Message | 16963| -------- | ----------------------- | 16964| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 16965 16966**Example** 16967 16968```ts 16969// xxx.ets 16970import { webview } from '@kit.ArkWeb'; 16971 16972// This example demonstrates how to click a button to add an array of domain names to the disallowed list. 16973@Entry 16974@Component 16975struct WebComponent { 16976 main_url: string = 'https://www.example.com'; 16977 text_input_controller: TextInputController = new TextInputController(); 16978 controller: webview.WebviewController = new webview.WebviewController(); 16979 @State input_text: string = 'https://www.example.com'; 16980 16981 build() { 16982 Column() { 16983 Row() { 16984 Flex() { 16985 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 16986 .id("input_url") 16987 .height(40) 16988 .margin(5) 16989 .borderColor(Color.Blue) 16990 .onChange((value: string) => { 16991 this.input_text = value; 16992 }) 16993 16994 Button({type: ButtonType.Capsule}) { Text("Go") } 16995 .onClick(() => { 16996 this.controller.loadUrl(this.input_text); 16997 }) 16998 16999 Button({type: ButtonType.Capsule}) { Text("addAdsBlockAllowedList") } 17000 .onClick(() => { 17001 let arrDisallowDomainSuffixes = new Array<string>(); 17002 arrDisallowDomainSuffixes.push('example.com'); 17003 webview.AdsBlockManager.addAdsBlockDisallowedList(arrDisallowDomainSuffixes); 17004 17005 let arrAllowedDomainSuffixes = new Array<string>(); 17006 arrAllowedDomainSuffixes.push('news.example.com'); 17007 webview.AdsBlockManager.addAdsBlockAllowedList(arrAllowedDomainSuffixes); 17008 }) 17009 } 17010 } 17011 Web({ src: this.main_url, controller: this.controller }) 17012 .onControllerAttached(()=>{ 17013 this.controller.enableAdsBlock(true) 17014 }) 17015 } 17016 } 17017} 17018``` 17019 17020### removeAdsBlockAllowedList<sup>12+</sup> 17021 17022static removeAdsBlockAllowedList(domainSuffixes: Array\<string\>): void 17023 17024Removes an array of domain names from the allowed list of this **AdsBlockManager** object. 17025 17026> **NOTE** 17027> 17028> 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. 17029 17030**System capability**: SystemCapability.Web.Webview.Core 17031 17032**Parameters** 17033 17034| Name | Type | Mandatory| Description | 17035| ---------- | ------ | ---- | -------------------------------- | 17036| domainSuffixes | Array\<string\> | Yes | Array of domain names, for example, ['example.com', 'abcd.efg.com'].| 17037 17038**Error codes** 17039 17040For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 17041 17042| ID| Error Message | 17043| -------- | ----------------------- | 17044| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 17045 17046**Example** 17047 17048```ts 17049// xxx.ets 17050import { webview } from '@kit.ArkWeb'; 17051 17052// This example demonstrates how to click a button to remove an array of domain names from the disallowed list. 17053@Entry 17054@Component 17055struct WebComponent { 17056 main_url: string = 'https://www.example.com'; 17057 text_input_controller: TextInputController = new TextInputController(); 17058 controller: webview.WebviewController = new webview.WebviewController(); 17059 @State input_text: string = 'https://www.example.com'; 17060 17061 build() { 17062 Column() { 17063 Row() { 17064 Flex() { 17065 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 17066 .id("input_url") 17067 .height(40) 17068 .margin(5) 17069 .borderColor(Color.Blue) 17070 .onChange((value: string) => { 17071 this.input_text = value; 17072 }) 17073 17074 Button({type: ButtonType.Capsule}) { Text("Go") } 17075 .onClick(() => { 17076 this.controller.loadUrl(this.input_text); 17077 }) 17078 17079 Button({type: ButtonType.Capsule}) { Text("removeAdsBlockAllowedList") } 17080 .onClick(() => { 17081 let arrDomainSuffixes = new Array<string>(); 17082 arrDomainSuffixes.push('example.com'); 17083 arrDomainSuffixes.push('abcdefg.cn'); 17084 webview.AdsBlockManager.removeAdsBlockAllowedList(arrDomainSuffixes); 17085 }) 17086 } 17087 } 17088 Web({ src: this.main_url, controller: this.controller }) 17089 .onControllerAttached(()=>{ 17090 this.controller.enableAdsBlock(true); 17091 }) 17092 } 17093 } 17094} 17095``` 17096 17097### clearAdsBlockAllowedList<sup>12+</sup> 17098 17099static clearAdsBlockAllowedList(): void 17100 17101Clears the allowed list of this **AdsBlockManager** object. 17102 17103**System capability**: SystemCapability.Web.Webview.Core 17104 17105**Example** 17106 17107```ts 17108// xxx.ets 17109import { webview } from '@kit.ArkWeb'; 17110 17111@Entry 17112@Component 17113struct WebComponent { 17114 main_url: string = 'https://www.example.com'; 17115 text_input_controller: TextInputController = new TextInputController(); 17116 controller: webview.WebviewController = new webview.WebviewController(); 17117 @State input_text: string = 'https://www.example.com'; 17118 17119 17120 build() { 17121 Column() { 17122 Row() { 17123 Flex() { 17124 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 17125 .id("input_url") 17126 .height(40) 17127 .margin(5) 17128 .borderColor(Color.Blue) 17129 .onChange((value: string) => { 17130 this.input_text = value; 17131 }) 17132 17133 Button({type: ButtonType.Capsule}) { Text("Go") } 17134 .onClick(() => { 17135 this.controller.loadUrl(this.input_text); 17136 }) 17137 17138 Button({type: ButtonType.Capsule}) { Text("clearAdsBlockAllowedList") } 17139 .onClick(() => { 17140 webview.AdsBlockManager.clearAdsBlockAllowedList(); 17141 }) 17142 } 17143 } 17144 Web({ src: this.main_url, controller: this.controller }) 17145 .onControllerAttached(()=>{ 17146 this.controller.enableAdsBlock(true); 17147 }) 17148 } 17149 } 17150} 17151``` 17152 17153## SnapshotInfo<sup>12+</sup> 17154 17155Provides information used to obtain a full drawing result. 17156 17157**System capability**: SystemCapability.Web.Webview.Core 17158 17159| Name| Type| Mandatory| Description| 17160|------|------|------|------| 17161| id | string | No| Snapshot ID.| 17162| 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.| 17163 17164## SnapshotResult<sup>12+</sup> 17165 17166Represents a full drawing result. 17167 17168**System capability**: SystemCapability.Web.Webview.Core 17169 17170| Name| Type| Mandatory| Description| 17171|------|------|--|---------| 17172| id | string | No| Snapshot ID.| 17173| 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.| 17174| 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.| 17175| imagePixelMap | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | No| Full drawing result in image.pixelMap format.| 17176 17177> **NOTE** 17178> 17179> Only static images and texts in the rendering process can be captured. 17180> Videos cannot be captured. If there is a video on the page, the placeholder image of the video is displayed when you take a screenshot. 17181 17182## ScrollType<sup>12+</sup> 17183 17184Represents a scroll type, which is used in [setScrollable](#setscrollable12). 17185 17186**System capability**: SystemCapability.Web.Webview.Core 17187 17188| Name | Value| Description | 17189| ------------ | -- |--------------------------------- | 17190| EVENT | 0 | Scrolling event, indicating that a web page is scrolled by using a touchscreen, a touchpad, or a mouse.| 17191 17192## PressureLevel<sup>14+</sup> 17193 17194Represents 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. 17195 17196**System capability**: SystemCapability.Web.Webview.Core 17197 17198| Name| Value| Description| 17199| ------------------------------- | - | ---------- | 17200| 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.| 17201| MEMORY_PRESSURE_LEVEL_CRITICAL | 2 | Critical memory pressure level. At this level, the **Web** kernel attempts to release all possible memory caches.| 17202 17203## PdfConfiguration<sup>14+</sup> 17204 17205Specifies the input parameters of **createPdf()**. 17206 17207> **NOTE** 17208> 17209> The number of pixels is calculated as follows: Number of pixels = 96 x Number of inches. 17210 17211**System capability**: SystemCapability.Web.Webview.Core 17212 17213| Name | Type | Mandatory| Description | 17214| --------------------- | ------- | ---- | ------------------------------------------------------------ | 17215| width | number | Yes | Page width, in inches.<br>Recommended value: 8.27 inches of A4 paper width. | 17216| height | number | Yes | Page height, in inches.<br>Recommended value: 11.69 inches of A4 paper height. | 17217| scale | number | No | Scale multiple. The value range is [0.0, 2.0]. If the value is less than 0.0, set it to **0.0**. If the value is greater than 2.0, set it to **2.0**. Default value: **1.0**| 17218| marginTop | number | Yes | Top margin. The value range is [0.0, half of the page height). If the value is not within the value range, set it to **0.0**. Unit: inch.| 17219| marginBottom | number | Yes | Bottom margin. The value range is [0.0, half of the page height). If the value is not within the value range, set it to **0.0**. Unit: inch.| 17220| marginRight | number | Yes | Right margin. The value range is [0.0, half of the page width). If the value is not within the value range, set it to **0.0**. Unit: inch.| 17221| marginLeft | number | Yes | Left margin. The value range is [0.0, half of the page width). If the value is not within the value range, set it to **0.0**. Unit: inch.| 17222| shouldPrintBackground | boolean | No | Whether to print the background color. The default value is **false**. | 17223 17224## PdfData<sup>14+</sup> 17225 17226Represents the output data stream class of **createPdf()**. 17227 17228> **NOTE** 17229> 17230> When a PDF file is generated on a web page, a data stream is returned, which is encapsulated by the **PdfData** class. 17231 17232### pdfArrayBuffer<sup>14+</sup> 17233 17234pdfArrayBuffer(): Uint8Array 17235 17236Obtains the data stream generated by a web page. For details, see [createPdf](#createpdf14). 17237 17238**System capability**: SystemCapability.Web.Webview.Core 17239 17240**Return value** 17241 17242| Type | Description | 17243| ---------- | -------- | 17244| Uint8Array | Data stream.| 17245 17246## ScrollOffset<sup>13+</sup> 17247 17248Represents the current scrolling offset of a web page. 17249 17250**System capability**: SystemCapability.Web.Webview.Core 17251 17252| Name| Type | Readable| Writable| Description | 17253| ---- | ------ | ---- | ---- | ------------------------------------------------------------ | 17254| x | number | Yes | Yes | Horizontal scrolling offset of a web page. The value is the difference between the x-coordinate of the left boundary of the web page and that of the left boundary of the **Web** component. The unit is vp.<br>When the web page is scrolled rightwards, the value is negative.<br>When the web page is not scrolled or scrolled leftwards, the value is **0** or positive.| 17255| y | number | Yes | Yes | Vertical scrolling offset of a web page. The value is the difference between the y-coordinate of the upper boundary of the web page and that of the upper boundary of the **Web** component. The unit is vp.<br>When the web page is scrolled downwards, the value is negative.<br>When the web page is not scrolled or scrolled upwards, the value is **0** or positive.| 17256