1# @ohos.web.webview (Webview) 2 3The **Webview** module provides APIs for web control. It can work with the [Web](ts-basic-components-web.md) component, which is used to display web pages. 4 5> **NOTE** 6> 7> - The initial APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. 8> 9> - You can preview how this component looks on a real device, but not in DevEco Studio Previewer. 10 11## Required Permissions 12 13**ohos.permission.INTERNET**, required for accessing online web pages. For details about how to apply for a permission, see [Declaring Permissions](../../security/AccessToken/declare-permissions.md). 14 15## Modules to Import 16 17```ts 18import { webview } from '@kit.ArkWeb'; 19``` 20 21## once 22 23once(type: string, callback: Callback\<void\>): void 24 25Registers a one-time callback for web events of the specified type. 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**System capability**: SystemCapability.Web.Webview.Core 1212 1213**Return value** 1214 1215| Type | Description | 1216| ------- | -------------------------------- | 1217| boolean | Returns **true** if going to the previous page can be performed on the current page; returns **false** otherwise.| 1218 1219**Error codes** 1220 1221For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1222 1223| ID| Error Message | 1224| -------- | ------------------------------------------------------------ | 1225| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1226 1227**Example** 1228 1229```ts 1230// xxx.ets 1231import { webview } from '@kit.ArkWeb'; 1232import { BusinessError } from '@kit.BasicServicesKit'; 1233 1234@Entry 1235@Component 1236struct WebComponent { 1237 controller: webview.WebviewController = new webview.WebviewController(); 1238 1239 build() { 1240 Column() { 1241 Button('accessBackward') 1242 .onClick(() => { 1243 try { 1244 let result = this.controller.accessBackward(); 1245 console.log('result:' + result); 1246 } catch (error) { 1247 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1248 } 1249 }) 1250 Web({ src: 'www.example.com', controller: this.controller }) 1251 } 1252 } 1253} 1254``` 1255 1256### backward 1257 1258backward(): void 1259 1260Moves to the previous page based on the history stack. This API is generally used together with **accessBackward**. 1261 1262**System capability**: SystemCapability.Web.Webview.Core 1263 1264**Error codes** 1265 1266For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1267 1268| ID| Error Message | 1269| -------- | ------------------------------------------------------------ | 1270| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1271 1272**Example** 1273 1274```ts 1275// xxx.ets 1276import { webview } from '@kit.ArkWeb'; 1277import { BusinessError } from '@kit.BasicServicesKit'; 1278 1279@Entry 1280@Component 1281struct WebComponent { 1282 controller: webview.WebviewController = new webview.WebviewController(); 1283 1284 build() { 1285 Column() { 1286 Button('backward') 1287 .onClick(() => { 1288 try { 1289 this.controller.backward(); 1290 } catch (error) { 1291 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1292 } 1293 }) 1294 Web({ src: 'www.example.com', controller: this.controller }) 1295 } 1296 } 1297} 1298``` 1299 1300### onActive 1301 1302onActive(): void 1303 1304Called when the **Web** component enters the active state. 1305<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). 1306 1307**System capability**: SystemCapability.Web.Webview.Core 1308 1309**Error codes** 1310 1311For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1312 1313| ID| Error Message | 1314| -------- | ------------------------------------------------------------ | 1315| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1316 1317**Example** 1318 1319```ts 1320// xxx.ets 1321import { webview } from '@kit.ArkWeb'; 1322import { BusinessError } from '@kit.BasicServicesKit'; 1323 1324@Entry 1325@Component 1326struct WebComponent { 1327 controller: webview.WebviewController = new webview.WebviewController(); 1328 1329 build() { 1330 Column() { 1331 Button('onActive') 1332 .onClick(() => { 1333 try { 1334 this.controller.onActive(); 1335 } catch (error) { 1336 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1337 } 1338 }) 1339 Web({ src: 'www.example.com', controller: this.controller }) 1340 } 1341 } 1342} 1343``` 1344 1345### onInactive 1346 1347onInactive(): void 1348 1349Called when the **Web** component enters the inactive state. You can implement the behavior to perform after the application loses focus. 1350 1351When 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). 1352 1353**System capability**: SystemCapability.Web.Webview.Core 1354 1355**Error codes** 1356 1357For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1358 1359| ID| Error Message | 1360| -------- | ------------------------------------------------------------ | 1361| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1362 1363**Example** 1364 1365```ts 1366// xxx.ets 1367import { webview } from '@kit.ArkWeb'; 1368import { BusinessError } from '@kit.BasicServicesKit'; 1369 1370@Entry 1371@Component 1372struct WebComponent { 1373 controller: webview.WebviewController = new webview.WebviewController(); 1374 1375 build() { 1376 Column() { 1377 Button('onInactive') 1378 .onClick(() => { 1379 try { 1380 this.controller.onInactive(); 1381 } catch (error) { 1382 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1383 } 1384 }) 1385 Web({ src: 'www.example.com', controller: this.controller }) 1386 } 1387 } 1388} 1389``` 1390 1391### refresh 1392refresh(): void 1393 1394Called when the **Web** component refreshes the web page. 1395 1396**System capability**: SystemCapability.Web.Webview.Core 1397 1398**Error codes** 1399 1400For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1401 1402| ID| Error Message | 1403| -------- | ------------------------------------------------------------ | 1404| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1405 1406**Example** 1407 1408```ts 1409// xxx.ets 1410import { webview } from '@kit.ArkWeb'; 1411import { BusinessError } from '@kit.BasicServicesKit'; 1412 1413@Entry 1414@Component 1415struct WebComponent { 1416 controller: webview.WebviewController = new webview.WebviewController(); 1417 1418 build() { 1419 Column() { 1420 Button('refresh') 1421 .onClick(() => { 1422 try { 1423 this.controller.refresh(); 1424 } catch (error) { 1425 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1426 } 1427 }) 1428 Web({ src: 'www.example.com', controller: this.controller }) 1429 } 1430 } 1431} 1432``` 1433 1434### accessStep 1435 1436accessStep(step: number): boolean 1437 1438Checks whether a specific number of steps forward or backward can be performed on the current page. 1439 1440**System capability**: SystemCapability.Web.Webview.Core 1441 1442**Parameters** 1443 1444| Name| Type| Mandatory| Description | 1445| ------ | -------- | ---- | ------------------------------------------ | 1446| step | number | Yes | Number of the steps to take. A positive number means to move forward, and a negative number means to move backward.| 1447 1448**Return value** 1449 1450| Type | Description | 1451| ------- | ------------------ | 1452| boolean | Whether moving forward or backward is performed on the current page.| 1453 1454**Error codes** 1455 1456For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1457 1458| ID| Error Message | 1459| -------- | ------------------------------------------------------------ | 1460| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1461| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1462 1463**Example** 1464 1465```ts 1466// xxx.ets 1467import { webview } from '@kit.ArkWeb'; 1468import { BusinessError } from '@kit.BasicServicesKit'; 1469 1470@Entry 1471@Component 1472struct WebComponent { 1473 controller: webview.WebviewController = new webview.WebviewController(); 1474 @State steps: number = 2; 1475 1476 build() { 1477 Column() { 1478 Button('accessStep') 1479 .onClick(() => { 1480 try { 1481 let result = this.controller.accessStep(this.steps); 1482 console.log('result:' + result); 1483 } catch (error) { 1484 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1485 } 1486 }) 1487 Web({ src: 'www.example.com', controller: this.controller }) 1488 } 1489 } 1490} 1491``` 1492 1493### clearHistory 1494 1495clearHistory(): void 1496 1497Clears the browsing history. You are not advised to call **clearHistory()** in **onErrorReceive()** and **onPageBegin()**. Otherwise, abnormal exit occurs. 1498 1499**System capability**: SystemCapability.Web.Webview.Core 1500 1501**Error codes** 1502 1503For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1504 1505| ID| Error Message | 1506| -------- | ------------------------------------------------------------ | 1507| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1508 1509**Example** 1510 1511```ts 1512// xxx.ets 1513import { webview } from '@kit.ArkWeb'; 1514import { BusinessError } from '@kit.BasicServicesKit'; 1515 1516@Entry 1517@Component 1518struct WebComponent { 1519 controller: webview.WebviewController = new webview.WebviewController(); 1520 1521 build() { 1522 Column() { 1523 Button('clearHistory') 1524 .onClick(() => { 1525 try { 1526 this.controller.clearHistory(); 1527 } catch (error) { 1528 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1529 } 1530 }) 1531 Web({ src: 'www.example.com', controller: this.controller }) 1532 } 1533 } 1534} 1535``` 1536 1537### getHitTest 1538 1539getHitTest(): WebHitTestType 1540 1541Obtains the element type of the area being clicked. 1542 1543**System capability**: SystemCapability.Web.Webview.Core 1544 1545**Return value** 1546 1547| Type | Description | 1548| ------------------------------------------------------------ | ---------------------- | 1549| [WebHitTestType](#webhittesttype)| Element type of the area being clicked.| 1550 1551**Error codes** 1552 1553For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1554 1555| ID| Error Message | 1556| -------- | ------------------------------------------------------------ | 1557| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1558 1559**Example** 1560 1561```ts 1562// xxx.ets 1563import { webview } from '@kit.ArkWeb'; 1564import { BusinessError } from '@kit.BasicServicesKit'; 1565 1566@Entry 1567@Component 1568struct WebComponent { 1569 controller: webview.WebviewController = new webview.WebviewController(); 1570 1571 build() { 1572 Column() { 1573 Button('getHitTest') 1574 .onClick(() => { 1575 try { 1576 let hitTestType = this.controller.getHitTest(); 1577 console.log("hitTestType: " + hitTestType); 1578 } catch (error) { 1579 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1580 } 1581 }) 1582 Web({ src: 'www.example.com', controller: this.controller }) 1583 } 1584 } 1585} 1586``` 1587 1588### registerJavaScriptProxy 1589 1590registerJavaScriptProxy(object: object, name: string, methodList: Array\<string>, asyncMethodList?: Array\<string>, permission?: string): void 1591 1592Registers a proxy for interaction between the application and web pages loaded by the **Web** component. 1593<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. 1594 1595> **NOTE** 1596> 1597> - The **registerJavaScriptProxy** API must be used together with the **deleteJavaScriptRegister** API to prevent memory leak. 1598> - 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. 1599> - After **registerJavaScriptProxy** is called, the application exposes the registered JavaScript object to all page frames. 1600> - If a **registerJavaScriptProxy** is both registered in the synchronous and asynchronous lists, it is called asynchronously by default. 1601> - You should register **registerJavaScriptProxy** either in synchronous list or in asynchronous list. Otherwise, this API fails to be registered. 1602 1603**System capability**: SystemCapability.Web.Webview.Core 1604 1605**Parameters** 1606 1607| Name | Type | Mandatory| Description | 1608| ---------- | -------------- | ---- | ------------------------------------------------------------ | 1609| 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).| 1610| 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.| 1611| methodList | Array\<string> | Yes | Synchronous methods of the JavaScript object to be registered at the application side. | 1612| 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. | 1613| 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).| 1614 1615**Error codes** 1616 1617For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1618 1619| ID| Error Message | 1620| -------- | ------------------------------------------------------------ | 1621| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1622| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1623 1624**Example** 1625 1626```ts 1627// xxx.ets 1628import { webview } from '@kit.ArkWeb'; 1629import { BusinessError } from '@kit.BasicServicesKit'; 1630 1631class TestObj { 1632 constructor() { 1633 } 1634 1635 test(testStr: string): string { 1636 console.log('Web Component str' + testStr); 1637 return testStr; 1638 } 1639 1640 toString(): void { 1641 console.log('Web Component toString'); 1642 } 1643 1644 testNumber(testNum: number): number { 1645 console.log('Web Component number' + testNum); 1646 return testNum; 1647 } 1648 1649 asyncTestBool(testBol: boolean): void { 1650 console.log('Web Component boolean' + testBol); 1651 } 1652} 1653 1654class WebObj { 1655 constructor() { 1656 } 1657 1658 webTest(): string { 1659 console.log('Web test'); 1660 return "Web test"; 1661 } 1662 1663 webString(): void { 1664 console.log('Web test toString'); 1665 } 1666} 1667 1668class AsyncObj { 1669 constructor() { 1670 } 1671 1672 asyncTest(): void { 1673 console.log('Async test'); 1674 } 1675 1676 asyncString(testStr: string): void { 1677 console.log('Web async string' + testStr); 1678 } 1679} 1680 1681@Entry 1682@Component 1683struct Index { 1684 controller: webview.WebviewController = new webview.WebviewController(); 1685 @State testObjtest: TestObj = new TestObj(); 1686 @State webTestObj: WebObj = new WebObj(); 1687 @State asyncTestObj: AsyncObj = new AsyncObj(); 1688 1689 build() { 1690 Column() { 1691 Button('refresh') 1692 .onClick(() => { 1693 try { 1694 this.controller.refresh(); 1695 } catch (error) { 1696 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1697 } 1698 }) 1699 Button('Register JavaScript To Window') 1700 .onClick(() => { 1701 try { 1702 // Register both synchronous and asynchronous functions. 1703 this.controller.registerJavaScriptProxy(this.testObjtest, "objName", ["test", "toString", "testNumber"], ["asyncTestBool"]); 1704 // Register only the synchronous function. 1705 this.controller.registerJavaScriptProxy(this.webTestObj, "objTestName", ["webTest", "webString"]); 1706 // Register only the asynchronous function. 1707 this.controller.registerJavaScriptProxy(this.asyncTestObj, "objAsyncName", [], ["asyncTest", "asyncString"]); 1708 } catch (error) { 1709 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1710 } 1711 }) 1712 Button('deleteJavaScriptRegister') 1713 .onClick(() => { 1714 try { 1715 this.controller.deleteJavaScriptRegister("objName"); 1716 this.controller.deleteJavaScriptRegister("objTestName"); 1717 this.controller.deleteJavaScriptRegister("objAsyncName"); 1718 } catch (error) { 1719 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1720 } 1721 }) 1722 Web({ src: $rawfile('index.html'), controller: this.controller }) 1723 .javaScriptAccess(true) 1724 } 1725 } 1726} 1727``` 1728 1729HTML file to be loaded: 1730```html 1731<!-- index.html --> 1732<!DOCTYPE html> 1733<html> 1734 <meta charset="utf-8"> 1735 <body> 1736 <button type="button" onclick="htmlTest()">Click Me!</button> 1737 <p id="demo"></p> 1738 <p id="webDemo"></p> 1739 <p id="asyncDemo"></p> 1740 </body> 1741 <script type="text/javascript"> 1742 function htmlTest() { 1743 // This function call expects to return "ArkUI Web Component" 1744 let str=objName.test("webtest data"); 1745 objName.testNumber(1); 1746 objName.asyncTestBool(true); 1747 document.getElementById("demo").innerHTML=str; 1748 console.log('objName.test result:'+ str) 1749 1750 // This function call expects to return "Web test" 1751 let webStr = objTestName.webTest(); 1752 document.getElementById("webDemo").innerHTML=webStr; 1753 console.log('objTestName.webTest result:'+ webStr) 1754 1755 objAsyncName.asyncTest(); 1756 objAsyncName.asyncString("async test data"); 1757 } 1758</script> 1759</html> 1760``` 1761For more examples, see [Invoking Application Functions on the Frontend Page](../../web/web-in-page-app-function-invoking.md). 1762 1763### runJavaScript 1764 1765runJavaScript(script: string, callback : AsyncCallback\<string>): void 1766 1767Executes 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**. 1768 1769> **NOTE** 1770> 1771> The offscreen component does not trigger **runJavaScript()**. 1772 1773**System capability**: SystemCapability.Web.Webview.Core 1774 1775**Parameters** 1776 1777| Name | Type | Mandatory| Description | 1778| -------- | -------------------- | ---- | ---------------------------- | 1779| script | string | Yes | JavaScript script. | 1780| 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.| 1781 1782**Error codes** 1783 1784For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1785 1786| ID| Error Message | 1787| -------- | ------------------------------------------------------------ | 1788| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1789| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1790 1791**Example** 1792 1793```ts 1794import { webview } from '@kit.ArkWeb'; 1795import { BusinessError } from '@kit.BasicServicesKit'; 1796 1797@Entry 1798@Component 1799struct WebComponent { 1800 controller: webview.WebviewController = new webview.WebviewController(); 1801 @State webResult: string = ''; 1802 1803 build() { 1804 Column() { 1805 Text(this.webResult).fontSize(20) 1806 Web({ src: $rawfile('index.html'), controller: this.controller }) 1807 .javaScriptAccess(true) 1808 .onPageEnd(e => { 1809 try { 1810 this.controller.runJavaScript( 1811 'test()', 1812 (error, result) => { 1813 if (error) { 1814 console.error(`run JavaScript error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1815 return; 1816 } 1817 if (result) { 1818 this.webResult = result; 1819 console.info(`The test() return value is: ${result}`); 1820 } 1821 }); 1822 if (e) { 1823 console.info('url: ', e.url); 1824 } 1825 } catch (error) { 1826 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1827 } 1828 }) 1829 } 1830 } 1831} 1832``` 1833 1834HTML file to be loaded: 1835```html 1836<!-- index.html --> 1837<!DOCTYPE html> 1838<html> 1839 <meta charset="utf-8"> 1840 <body> 1841 Hello world! 1842 </body> 1843 <script type="text/javascript"> 1844 function test() { 1845 console.log('Ark WebComponent') 1846 return "This value is from index.html" 1847 } 1848 </script> 1849</html> 1850``` 1851 1852### runJavaScript 1853 1854runJavaScript(script: string): Promise\<string> 1855 1856Executes 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**. 1857 1858**System capability**: SystemCapability.Web.Webview.Core 1859 1860**Parameters** 1861 1862| Name| Type| Mandatory| Description | 1863| ------ | -------- | ---- | ---------------- | 1864| script | string | Yes | JavaScript script.| 1865 1866**Return value** 1867 1868| Type | Description | 1869| --------------- | --------------------------------------------------- | 1870| Promise\<string> | Promise used to return the result if the operation is successful and null otherwise.| 1871 1872**Error codes** 1873 1874For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1875 1876| ID| Error Message | 1877| -------- | ------------------------------------------------------------ | 1878| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1879| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1880 1881**Example** 1882 1883```ts 1884// xxx.ets 1885import { webview } from '@kit.ArkWeb'; 1886import { BusinessError } from '@kit.BasicServicesKit'; 1887 1888@Entry 1889@Component 1890struct WebComponent { 1891 controller: webview.WebviewController = new webview.WebviewController(); 1892 1893 build() { 1894 Column() { 1895 Web({ src: $rawfile('index.html'), controller: this.controller }) 1896 .javaScriptAccess(true) 1897 .onPageEnd(e => { 1898 try { 1899 this.controller.runJavaScript('test()') 1900 .then((result) => { 1901 console.log('result: ' + result); 1902 }) 1903 .catch((error: BusinessError) => { 1904 console.error("error: " + error); 1905 }) 1906 if (e) { 1907 console.info('url: ', e.url); 1908 } 1909 } catch (error) { 1910 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1911 } 1912 }) 1913 } 1914 } 1915} 1916``` 1917 1918HTML file to be loaded: 1919```html 1920<!-- index.html --> 1921<!DOCTYPE html> 1922<html> 1923 <meta charset="utf-8"> 1924 <body> 1925 Hello world! 1926 </body> 1927 <script type="text/javascript"> 1928 function test() { 1929 console.log('Ark WebComponent') 1930 return "This value is from index.html" 1931 } 1932 </script> 1933</html> 1934``` 1935 1936### runJavaScriptExt<sup>10+</sup> 1937 1938runJavaScriptExt(script: string | ArrayBuffer, callback : AsyncCallback\<JsMessageExt>): void 1939 1940Executes 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**. 1941 1942**System capability**: SystemCapability.Web.Webview.Core 1943 1944**Parameters** 1945 1946| Name | Type | Mandatory| Description | 1947| -------- | -------------------- | ---- | ---------------------------- | 1948| script | string \| ArrayBuffer<sup>12+</sup> | Yes | JavaScript script.| 1949| callback | AsyncCallback\<[JsMessageExt](#jsmessageext10)\> | Yes | Callback used to return the result.| 1950 1951**Error codes** 1952 1953For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1954 1955| ID| Error Message | 1956| -------- | ------------------------------------------------------------ | 1957| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1958| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1959 1960**Example** 1961 1962```ts 1963import { webview } from '@kit.ArkWeb'; 1964import { BusinessError } from '@kit.BasicServicesKit'; 1965 1966@Entry 1967@Component 1968struct WebComponent { 1969 controller: webview.WebviewController = new webview.WebviewController(); 1970 @State msg1: string = ''; 1971 @State msg2: string = ''; 1972 1973 build() { 1974 Column() { 1975 Text(this.msg1).fontSize(20) 1976 Text(this.msg2).fontSize(20) 1977 Web({ src: $rawfile('index.html'), controller: this.controller }) 1978 .javaScriptAccess(true) 1979 .onPageEnd(e => { 1980 try { 1981 this.controller.runJavaScriptExt( 1982 'test()', 1983 (error, result) => { 1984 if (error) { 1985 console.error(`run JavaScript error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`) 1986 return; 1987 } 1988 if (result) { 1989 try { 1990 let type = result.getType(); 1991 switch (type) { 1992 case webview.JsMessageType.STRING: { 1993 this.msg1 = "result type:" + typeof (result.getString()); 1994 this.msg2 = "result getString:" + ((result.getString())); 1995 break; 1996 } 1997 case webview.JsMessageType.NUMBER: { 1998 this.msg1 = "result type:" + typeof (result.getNumber()); 1999 this.msg2 = "result getNumber:" + ((result.getNumber())); 2000 break; 2001 } 2002 case webview.JsMessageType.BOOLEAN: { 2003 this.msg1 = "result type:" + typeof (result.getBoolean()); 2004 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 2005 break; 2006 } 2007 case webview.JsMessageType.ARRAY_BUFFER: { 2008 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 2009 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 2010 break; 2011 } 2012 case webview.JsMessageType.ARRAY: { 2013 this.msg1 = "result type:" + typeof (result.getArray()); 2014 this.msg2 = "result getArray:" + result.getArray(); 2015 break; 2016 } 2017 default: { 2018 this.msg1 = "default break, type:" + type; 2019 break; 2020 } 2021 } 2022 } 2023 catch (resError) { 2024 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2025 } 2026 } 2027 }); 2028 if (e) { 2029 console.info('url: ', e.url); 2030 } 2031 } catch (error) { 2032 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2033 } 2034 }) 2035 } 2036 } 2037} 2038``` 2039 2040```ts 2041// Use the ArrayBuffer input parameter to obtain the JavaScript script data from the file. 2042import { webview } from '@kit.ArkWeb'; 2043import { BusinessError } from '@kit.BasicServicesKit'; 2044import { fileIo } from '@kit.CoreFileKit'; 2045import { common } from '@kit.AbilityKit'; 2046 2047@Entry 2048@Component 2049struct WebComponent { 2050 controller: webview.WebviewController = new webview.WebviewController(); 2051 @State msg1: string = '' 2052 @State msg2: string = '' 2053 2054 build() { 2055 Column() { 2056 Text(this.msg1).fontSize(20) 2057 Text(this.msg2).fontSize(20) 2058 Button('runJavaScriptExt') 2059 .onClick(() => { 2060 try { 2061 let context = getContext(this) as common.UIAbilityContext; 2062 let filePath = context.filesDir + 'test.txt'; 2063 // Create a file and open it. 2064 let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); 2065 // Write data to the file. 2066 fileIo.writeSync(file.fd, "test()"); 2067 // Read data from the file. 2068 let arrayBuffer: ArrayBuffer = new ArrayBuffer(6); 2069 fileIo.readSync(file.fd, arrayBuffer, { offset: 0, length: arrayBuffer.byteLength }); 2070 // Close the file. 2071 fileIo.closeSync(file); 2072 this.controller.runJavaScriptExt( 2073 arrayBuffer, 2074 (error, result) => { 2075 if (error) { 2076 console.error(`run JavaScript error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`) 2077 return; 2078 } 2079 if (result) { 2080 try { 2081 let type = result.getType(); 2082 switch (type) { 2083 case webview.JsMessageType.STRING: { 2084 this.msg1 = "result type:" + typeof (result.getString()); 2085 this.msg2 = "result getString:" + ((result.getString())); 2086 break; 2087 } 2088 case webview.JsMessageType.NUMBER: { 2089 this.msg1 = "result type:" + typeof (result.getNumber()); 2090 this.msg2 = "result getNumber:" + ((result.getNumber())); 2091 break; 2092 } 2093 case webview.JsMessageType.BOOLEAN: { 2094 this.msg1 = "result type:" + typeof (result.getBoolean()); 2095 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 2096 break; 2097 } 2098 case webview.JsMessageType.ARRAY_BUFFER: { 2099 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 2100 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 2101 break; 2102 } 2103 case webview.JsMessageType.ARRAY: { 2104 this.msg1 = "result type:" + typeof (result.getArray()); 2105 this.msg2 = "result getArray:" + result.getArray(); 2106 break; 2107 } 2108 default: { 2109 this.msg1 = "default break, type:" + type; 2110 break; 2111 } 2112 } 2113 } 2114 catch (resError) { 2115 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2116 } 2117 } 2118 }); 2119 } catch (error) { 2120 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2121 } 2122 }) 2123 Web({ src: $rawfile('index.html'), controller: this.controller }) 2124 .javaScriptAccess(true) 2125 } 2126 } 2127} 2128``` 2129 2130HTML file to be loaded: 2131```html 2132<!-- index.html --> 2133<!DOCTYPE html> 2134<html lang="en-gb"> 2135<body> 2136<h1>run JavaScript Ext demo</h1> 2137</body> 2138<script type="text/javascript"> 2139function test() { 2140 return "hello, world"; 2141} 2142</script> 2143</html> 2144``` 2145 2146### runJavaScriptExt<sup>10+</sup> 2147 2148runJavaScriptExt(script: string | ArrayBuffer): Promise\<JsMessageExt> 2149 2150Executes 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**. 2151 2152**System capability**: SystemCapability.Web.Webview.Core 2153 2154**Parameters** 2155 2156| Name| Type| Mandatory| Description | 2157| ------ | -------- | ---- | ---------------- | 2158| script | string \| ArrayBuffer<sup>12+</sup> | Yes | JavaScript script.| 2159 2160**Return value** 2161 2162| Type | Description | 2163| --------------- | --------------------------------------------------- | 2164| Promise\<[JsMessageExt](#jsmessageext10)> | Promise used to return the script execution result.| 2165 2166**Error codes** 2167 2168For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2169 2170| ID| Error Message | 2171| -------- | ------------------------------------------------------------ | 2172| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2173| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2174 2175**Example** 2176 2177```ts 2178// xxx.ets 2179import { webview } from '@kit.ArkWeb'; 2180import { BusinessError } from '@kit.BasicServicesKit'; 2181 2182@Entry 2183@Component 2184struct WebComponent { 2185 controller: webview.WebviewController = new webview.WebviewController(); 2186 @State webResult: string = ''; 2187 @State msg1: string = ''; 2188 @State msg2: string = ''; 2189 2190 build() { 2191 Column() { 2192 Text(this.webResult).fontSize(20) 2193 Text(this.msg1).fontSize(20) 2194 Text(this.msg2).fontSize(20) 2195 Web({ src: $rawfile('index.html'), controller: this.controller }) 2196 .javaScriptAccess(true) 2197 .onPageEnd(() => { 2198 this.controller.runJavaScriptExt('test()') 2199 .then((result) => { 2200 try { 2201 let type = result.getType(); 2202 switch (type) { 2203 case webview.JsMessageType.STRING: { 2204 this.msg1 = "result type:" + typeof (result.getString()); 2205 this.msg2 = "result getString:" + ((result.getString())); 2206 break; 2207 } 2208 case webview.JsMessageType.NUMBER: { 2209 this.msg1 = "result type:" + typeof (result.getNumber()); 2210 this.msg2 = "result getNumber:" + ((result.getNumber())); 2211 break; 2212 } 2213 case webview.JsMessageType.BOOLEAN: { 2214 this.msg1 = "result type:" + typeof (result.getBoolean()); 2215 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 2216 break; 2217 } 2218 case webview.JsMessageType.ARRAY_BUFFER: { 2219 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 2220 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 2221 break; 2222 } 2223 case webview.JsMessageType.ARRAY: { 2224 this.msg1 = "result type:" + typeof (result.getArray()); 2225 this.msg2 = "result getArray:" + result.getArray(); 2226 break; 2227 } 2228 default: { 2229 this.msg1 = "default break, type:" + type; 2230 break; 2231 } 2232 } 2233 } 2234 catch (resError) { 2235 console.error(`ErrorCode: ${(resError as BusinessError).code}, Message: ${(resError as BusinessError).message}`); 2236 } 2237 }).catch((error: BusinessError) => { 2238 console.error("error: " + error); 2239 }) 2240 }) 2241 } 2242 } 2243} 2244``` 2245 2246```ts 2247// Use the ArrayBuffer input parameter to obtain the JavaScript script data from the file. 2248import { webview } from '@kit.ArkWeb'; 2249import { BusinessError } from '@kit.BasicServicesKit'; 2250import { fileIo } from '@kit.CoreFileKit'; 2251import { common } from '@kit.AbilityKit'; 2252 2253@Entry 2254@Component 2255struct WebComponent { 2256 controller: webview.WebviewController = new webview.WebviewController(); 2257 @State msg1: string = ''; 2258 @State msg2: string = ''; 2259 2260 build() { 2261 Column() { 2262 Text(this.msg1).fontSize(20) 2263 Text(this.msg2).fontSize(20) 2264 Button('runJavaScriptExt') 2265 .onClick(() => { 2266 try { 2267 let context = getContext(this) as common.UIAbilityContext; 2268 let filePath = context.filesDir + 'test.txt'; 2269 // Create a file and open it. 2270 let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); 2271 // Write data to the file. 2272 fileIo.writeSync(file.fd, "test()"); 2273 // Read data from the file. 2274 let arrayBuffer: ArrayBuffer = new ArrayBuffer(6); 2275 fileIo.readSync(file.fd, arrayBuffer, { offset: 0, length: arrayBuffer.byteLength }); 2276 // Close the file. 2277 fileIo.closeSync(file); 2278 this.controller.runJavaScriptExt(arrayBuffer) 2279 .then((result) => { 2280 try { 2281 let type = result.getType(); 2282 switch (type) { 2283 case webview.JsMessageType.STRING: { 2284 this.msg1 = "result type:" + typeof (result.getString()); 2285 this.msg2 = "result getString:" + ((result.getString())); 2286 break; 2287 } 2288 case webview.JsMessageType.NUMBER: { 2289 this.msg1 = "result type:" + typeof (result.getNumber()); 2290 this.msg2 = "result getNumber:" + ((result.getNumber())); 2291 break; 2292 } 2293 case webview.JsMessageType.BOOLEAN: { 2294 this.msg1 = "result type:" + typeof (result.getBoolean()); 2295 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 2296 break; 2297 } 2298 case webview.JsMessageType.ARRAY_BUFFER: { 2299 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 2300 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 2301 break; 2302 } 2303 case webview.JsMessageType.ARRAY: { 2304 this.msg1 = "result type:" + typeof (result.getArray()); 2305 this.msg2 = "result getArray:" + result.getArray(); 2306 break; 2307 } 2308 default: { 2309 this.msg1 = "default break, type:" + type; 2310 break; 2311 } 2312 } 2313 } 2314 catch (resError) { 2315 console.error(`ErrorCode: ${(resError as BusinessError).code}, Message: ${(resError as BusinessError).message}`); 2316 } 2317 }) 2318 .catch((error: BusinessError) => { 2319 console.error("error: " + error); 2320 }) 2321 } catch (error) { 2322 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2323 } 2324 }) 2325 Web({ src: $rawfile('index.html'), controller: this.controller }) 2326 .javaScriptAccess(true) 2327 } 2328 } 2329} 2330``` 2331 2332HTML file to be loaded: 2333```html 2334<!-- index.html --> 2335<!DOCTYPE html> 2336<html lang="en-gb"> 2337<body> 2338<h1>run JavaScript Ext demo</h1> 2339</body> 2340<script type="text/javascript"> 2341function test() { 2342 return "hello, world"; 2343} 2344</script> 2345</html> 2346``` 2347 2348### deleteJavaScriptRegister 2349 2350deleteJavaScriptRegister(name: string): void 2351 2352Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. After the deletion, the [refresh](#refresh) API must be called. 2353 2354**System capability**: SystemCapability.Web.Webview.Core 2355 2356**Parameters** 2357 2358| Name| Type| Mandatory| Description | 2359| ------ | -------- | ---- | ---- | 2360| 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.| 2361 2362**Error codes** 2363 2364For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2365 2366| ID| Error Message | 2367| -------- | ------------------------------------------------------------ | 2368| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2369| 17100008 | Failed to delete JavaScriptProxy because it does not exist. | 2370| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2371 2372**Example** 2373 2374```ts 2375// xxx.ets 2376import { webview } from '@kit.ArkWeb'; 2377import { BusinessError } from '@kit.BasicServicesKit'; 2378 2379class TestObj { 2380 constructor() { 2381 } 2382 2383 test(): string { 2384 return "ArkUI Web Component"; 2385 } 2386 2387 toString(): void { 2388 console.log('Web Component toString'); 2389 } 2390} 2391 2392@Entry 2393@Component 2394struct WebComponent { 2395 controller: webview.WebviewController = new webview.WebviewController(); 2396 @State testObjtest: TestObj = new TestObj(); 2397 @State name: string = 'objName'; 2398 build() { 2399 Column() { 2400 Button('refresh') 2401 .onClick(() => { 2402 try { 2403 this.controller.refresh(); 2404 } catch (error) { 2405 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2406 } 2407 }) 2408 Button('Register JavaScript To Window') 2409 .onClick(() => { 2410 try { 2411 this.controller.registerJavaScriptProxy(this.testObjtest, this.name, ["test", "toString"]); 2412 } catch (error) { 2413 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2414 } 2415 }) 2416 Button('deleteJavaScriptRegister') 2417 .onClick(() => { 2418 try { 2419 this.controller.deleteJavaScriptRegister(this.name); 2420 } catch (error) { 2421 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2422 } 2423 }) 2424 Web({ src: $rawfile('index.html'), controller: this.controller }) 2425 .javaScriptAccess(true) 2426 } 2427 } 2428} 2429``` 2430 2431HTML file to be loaded: 2432```html 2433<!-- index.html --> 2434<!DOCTYPE html> 2435<html> 2436 <meta charset="utf-8"> 2437 <body> 2438 <button type="button" onclick="htmlTest()">Click Me!</button> 2439 <p id="demo"></p> 2440 </body> 2441 <script type="text/javascript"> 2442 function htmlTest() { 2443 let str=objName.test(); 2444 document.getElementById("demo").innerHTML=str; 2445 console.log('objName.test result:'+ str) 2446 } 2447</script> 2448</html> 2449``` 2450 2451### zoom 2452 2453zoom(factor: number): void 2454 2455Zooms in or out of this web page. This API is effective only when [zoomAccess](ts-basic-components-web.md#zoomaccess) is **true**. 2456 2457**System capability**: SystemCapability.Web.Webview.Core 2458 2459**Parameters** 2460 2461| Name| Type| Mandatory| Description| 2462| ------ | -------- | ---- | ------------------------------------------------------------ | 2463| 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.| 2464 2465**Error codes** 2466 2467For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2468 2469| ID| Error Message | 2470| -------- | ------------------------------------------------------------ | 2471| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2472| 17100004 | Function not enabled. | 2473| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2474 2475**Example** 2476 2477```ts 2478// xxx.ets 2479import { webview } from '@kit.ArkWeb'; 2480import { BusinessError } from '@kit.BasicServicesKit'; 2481 2482@Entry 2483@Component 2484struct WebComponent { 2485 controller: webview.WebviewController = new webview.WebviewController(); 2486 @State factor: number = 1; 2487 2488 build() { 2489 Column() { 2490 Button('zoom') 2491 .onClick(() => { 2492 try { 2493 this.controller.zoom(this.factor); 2494 } catch (error) { 2495 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2496 } 2497 }) 2498 Web({ src: 'www.example.com', controller: this.controller }) 2499 .zoomAccess(true) 2500 } 2501 } 2502} 2503``` 2504 2505### searchAllAsync 2506 2507searchAllAsync(searchString: string): void 2508 2509Searches 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). 2510 2511**System capability**: SystemCapability.Web.Webview.Core 2512 2513**Parameters** 2514 2515| Name | Type| Mandatory| Description | 2516| ------------ | -------- | ---- | -------------- | 2517| searchString | string | Yes | Search keyword.| 2518 2519**Error codes** 2520 2521For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2522 2523| ID| Error Message | 2524| -------- | ------------------------------------------------------------ | 2525| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2526| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2527 2528**Example** 2529 2530```ts 2531// xxx.ets 2532import { webview } from '@kit.ArkWeb'; 2533import { BusinessError } from '@kit.BasicServicesKit'; 2534 2535@Entry 2536@Component 2537struct WebComponent { 2538 controller: webview.WebviewController = new webview.WebviewController(); 2539 @State searchString: string = "Hello World"; 2540 2541 build() { 2542 Column() { 2543 Button('searchString') 2544 .onClick(() => { 2545 try { 2546 this.controller.searchAllAsync(this.searchString); 2547 } catch (error) { 2548 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2549 } 2550 }) 2551 Web({ src: $rawfile('index.html'), controller: this.controller }) 2552 .onSearchResultReceive(ret => { 2553 if (ret) { 2554 console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal + 2555 "[total]" + ret.numberOfMatches + "[isDone]" + ret.isDoneCounting); 2556 } 2557 }) 2558 } 2559 } 2560} 2561``` 2562 2563HTML file to be loaded: 2564```html 2565<!-- index.html --> 2566<!DOCTYPE html> 2567<html> 2568 <body> 2569 <p>Hello World Highlight Hello World</p> 2570 </body> 2571</html> 2572``` 2573 2574### clearMatches 2575 2576clearMatches(): void 2577 2578Clears the matches found through [searchAllAsync](#searchallasync). 2579 2580**System capability**: SystemCapability.Web.Webview.Core 2581 2582**Error codes** 2583 2584For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2585 2586| ID| Error Message | 2587| -------- | ------------------------------------------------------------ | 2588| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2589 2590**Example** 2591 2592```ts 2593// xxx.ets 2594import { webview } from '@kit.ArkWeb'; 2595import { BusinessError } from '@kit.BasicServicesKit'; 2596 2597@Entry 2598@Component 2599struct WebComponent { 2600 controller: webview.WebviewController = new webview.WebviewController(); 2601 2602 build() { 2603 Column() { 2604 Button('clearMatches') 2605 .onClick(() => { 2606 try { 2607 this.controller.clearMatches(); 2608 } catch (error) { 2609 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2610 } 2611 }) 2612 Web({ src: $rawfile('index.html'), controller: this.controller }) 2613 } 2614 } 2615} 2616``` 2617 2618For details about the HTML file loaded, see the HMTL file loaded using [searchAllAsync](#searchallasync). 2619 2620### searchNext 2621 2622searchNext(forward: boolean): void 2623 2624Searches for and highlights the next match. 2625 2626**System capability**: SystemCapability.Web.Webview.Core 2627 2628**Parameters** 2629 2630| Name | Type| Mandatory| Description | 2631| ------- | -------- | ---- | ---------------------- | 2632| forward | boolean | Yes | Whether to search forward.| 2633 2634**Error codes** 2635 2636For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2637 2638| ID| Error Message | 2639| -------- | ------------------------------------------------------------ | 2640| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2641| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2642 2643**Example** 2644 2645```ts 2646// xxx.ets 2647import { webview } from '@kit.ArkWeb'; 2648import { BusinessError } from '@kit.BasicServicesKit'; 2649 2650@Entry 2651@Component 2652struct WebComponent { 2653 controller: webview.WebviewController = new webview.WebviewController(); 2654 2655 build() { 2656 Column() { 2657 Button('searchNext') 2658 .onClick(() => { 2659 try { 2660 this.controller.searchNext(true); 2661 } catch (error) { 2662 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2663 } 2664 }) 2665 Web({ src: $rawfile('index.html'), controller: this.controller }) 2666 } 2667 } 2668} 2669``` 2670 2671For details about the HTML file loaded, see the HMTL file loaded using [searchAllAsync](#searchallasync). 2672 2673### clearSslCache 2674 2675clearSslCache(): void 2676 2677Clears the user operation corresponding to the SSL certificate error event recorded by the **Web** component. 2678 2679**System capability**: SystemCapability.Web.Webview.Core 2680 2681**Error codes** 2682 2683For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2684 2685| ID| Error Message | 2686| -------- | ------------------------------------------------------------ | 2687| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2688 2689**Example** 2690 2691```ts 2692// xxx.ets 2693import { webview } from '@kit.ArkWeb'; 2694import { BusinessError } from '@kit.BasicServicesKit'; 2695 2696@Entry 2697@Component 2698struct WebComponent { 2699 controller: webview.WebviewController = new webview.WebviewController(); 2700 2701 build() { 2702 Column() { 2703 Button('clearSslCache') 2704 .onClick(() => { 2705 try { 2706 this.controller.clearSslCache(); 2707 } catch (error) { 2708 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2709 } 2710 }) 2711 Web({ src: 'www.example.com', controller: this.controller }) 2712 } 2713 } 2714} 2715``` 2716 2717### clearClientAuthenticationCache 2718 2719clearClientAuthenticationCache(): void 2720 2721Clears the user operation corresponding to the client certificate request event recorded by the **Web** component. 2722 2723**System capability**: SystemCapability.Web.Webview.Core 2724 2725**Error codes** 2726 2727For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2728 2729| ID| Error Message | 2730| -------- | ------------------------------------------------------------ | 2731| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2732 2733**Example** 2734 2735```ts 2736// xxx.ets 2737import { webview } from '@kit.ArkWeb'; 2738import { BusinessError } from '@kit.BasicServicesKit'; 2739 2740@Entry 2741@Component 2742struct WebComponent { 2743 controller: webview.WebviewController = new webview.WebviewController(); 2744 2745 build() { 2746 Column() { 2747 Button('clearClientAuthenticationCache') 2748 .onClick(() => { 2749 try { 2750 this.controller.clearClientAuthenticationCache(); 2751 } catch (error) { 2752 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2753 } 2754 }) 2755 Web({ src: 'www.example.com', controller: this.controller }) 2756 } 2757 } 2758} 2759``` 2760 2761### createWebMessagePorts 2762 2763createWebMessagePorts(isExtentionType?: boolean): Array\<WebMessagePort> 2764 2765Creates web message ports. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 2766 2767**System capability**: SystemCapability.Web.Webview.Core 2768 2769**Parameters** 2770 2771| Name| Type | Mandatory| Description | 2772| ------ | ---------------------- | ---- | :------------------------------| 2773| 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.| 2774 2775**Return value** 2776 2777| Type | Description | 2778| ---------------------- | ----------------- | 2779| Array\<[WebMessagePort](#webmessageport)> | List of web message ports.| 2780 2781**Error codes** 2782 2783For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2784 2785| ID| Error Message | 2786| -------- | ------------------------------------------------------------ | 2787| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2788| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2789 2790**Example** 2791 2792```ts 2793// xxx.ets 2794import { webview } from '@kit.ArkWeb'; 2795import { BusinessError } from '@kit.BasicServicesKit'; 2796 2797@Entry 2798@Component 2799struct WebComponent { 2800 controller: webview.WebviewController = new webview.WebviewController(); 2801 ports: webview.WebMessagePort[] = []; 2802 2803 build() { 2804 Column() { 2805 Button('createWebMessagePorts') 2806 .onClick(() => { 2807 try { 2808 this.ports = this.controller.createWebMessagePorts(); 2809 console.log("createWebMessagePorts size:" + this.ports.length); 2810 } catch (error) { 2811 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2812 } 2813 }) 2814 Web({ src: 'www.example.com', controller: this.controller }) 2815 } 2816 } 2817} 2818``` 2819 2820### postMessage 2821 2822postMessage(name: string, ports: Array\<WebMessagePort>, uri: string): void 2823 2824Sends a web message to an HTML window. 2825 2826**System capability**: SystemCapability.Web.Webview.Core 2827 2828**Parameters** 2829 2830| Name| Type | Mandatory| Description | 2831| ------ | ---------------------- | ---- | :------------------------------- | 2832| name | string | Yes | Name of the message to send. | 2833| ports | Array\<[WebMessagePort](#webmessageport)> | Yes | Message ports for sending the message. | 2834| uri | string | Yes | URI for receiving the message. | 2835 2836**Error codes** 2837 2838For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2839 2840| ID| Error Message | 2841| -------- | ------------------------------------------------------------ | 2842| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2843| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2844 2845**Example** 2846 2847```ts 2848// xxx.ets 2849import { webview } from '@kit.ArkWeb'; 2850import { BusinessError } from '@kit.BasicServicesKit'; 2851 2852@Entry 2853@Component 2854struct WebComponent { 2855 controller: webview.WebviewController = new webview.WebviewController(); 2856 ports: webview.WebMessagePort[] = []; 2857 @State sendFromEts: string = 'Send this message from ets to HTML'; 2858 @State receivedFromHtml: string = 'Display received message send from HTML'; 2859 2860 build() { 2861 Column() { 2862 // Display the received HTML content. 2863 Text(this.receivedFromHtml) 2864 // Send the content in the text box to an HTML window. 2865 TextInput({ placeholder: 'Send this message from ets to HTML' }) 2866 .onChange((value: string) => { 2867 this.sendFromEts = value; 2868 }) 2869 2870 Button('postMessage') 2871 .onClick(() => { 2872 try { 2873 // 1. Create two message ports. 2874 this.ports = this.controller.createWebMessagePorts(); 2875 // 2. Register a callback on a message port (for example, port 1) on the application side. 2876 this.ports[1].onMessageEvent((result: webview.WebMessage) => { 2877 let msg = 'Got msg from HTML:'; 2878 if (typeof (result) == "string") { 2879 console.log("received string message from html5, string is:" + result); 2880 msg = msg + result; 2881 } else if (typeof (result) == "object") { 2882 if (result instanceof ArrayBuffer) { 2883 console.log("received arraybuffer from html5, length is:" + result.byteLength); 2884 msg = msg + "length is " + result.byteLength; 2885 } else { 2886 console.log("not support"); 2887 } 2888 } else { 2889 console.log("not support"); 2890 } 2891 this.receivedFromHtml = msg; 2892 }) 2893 // 3. Send another message port (for example, port 0) to the HTML side, which can then save the port for future use. 2894 this.controller.postMessage('__init_port__', [this.ports[0]], '*'); 2895 } catch (error) { 2896 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2897 } 2898 }) 2899 2900 // 4. Use the port on the application side to send messages to the port that has been sent to the HTML side. 2901 Button('SendDataToHTML') 2902 .onClick(() => { 2903 try { 2904 if (this.ports && this.ports[1]) { 2905 this.ports[1].postMessageEvent(this.sendFromEts); 2906 } else { 2907 console.error(`ports is null, Please initialize first`); 2908 } 2909 } catch (error) { 2910 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2911 } 2912 }) 2913 Web({ src: $rawfile('index.html'), controller: this.controller }) 2914 } 2915 } 2916} 2917``` 2918 2919HTML file to be loaded: 2920```html 2921<!--index.html--> 2922<!DOCTYPE html> 2923<html> 2924<head> 2925 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 2926 <title>WebView Message Port Demo</title> 2927</head> 2928 2929 <body> 2930 <h1>WebView Message Port Demo</h1> 2931 <div> 2932 <input type="button" value="SendToEts" onclick="PostMsgToEts(msgFromJS.value);"/><br/> 2933 <input id="msgFromJS" type="text" value="send this message from HTML to ets"/><br/> 2934 </div> 2935 <p class="output">display received message send from ets</p> 2936 </body> 2937 <script src="xxx.js"></script> 2938</html> 2939``` 2940 2941```js 2942//xxx.js 2943var h5Port; 2944var output = document.querySelector('.output'); 2945window.addEventListener('message', function (event) { 2946 if (event.data == '__init_port__') { 2947 if (event.ports[0] != null) { 2948 h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side. 2949 h5Port.onmessage = function (event) { 2950 // 2. Receive the message sent from the eTS side. 2951 var msg = 'Got message from ets:'; 2952 var result = event.data; 2953 if (typeof(result) == "string") { 2954 console.log("received string message from html5, string is:" + result); 2955 msg = msg + result; 2956 } else if (typeof(result) == "object") { 2957 if (result instanceof ArrayBuffer) { 2958 console.log("received arraybuffer from html5, length is:" + result.byteLength); 2959 msg = msg + "length is " + result.byteLength; 2960 } else { 2961 console.log("not support"); 2962 } 2963 } else { 2964 console.log("not support"); 2965 } 2966 output.innerHTML = msg; 2967 } 2968 } 2969 } 2970}) 2971 2972// 3. Use h5Port to send messages to the eTS side. 2973function PostMsgToEts(data) { 2974 if (h5Port) { 2975 h5Port.postMessage(data); 2976 } else { 2977 console.error("h5Port is null, Please initialize first"); 2978 } 2979} 2980``` 2981 2982### requestFocus 2983 2984requestFocus(): void 2985 2986Requests focus for this web page. 2987 2988**System capability**: SystemCapability.Web.Webview.Core 2989 2990**Error codes** 2991 2992For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2993 2994| ID| Error Message | 2995| -------- | ------------------------------------------------------------ | 2996| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2997 2998**Example** 2999 3000```ts 3001// xxx.ets 3002import { webview } from '@kit.ArkWeb'; 3003import { BusinessError } from '@kit.BasicServicesKit'; 3004 3005@Entry 3006@Component 3007struct WebComponent { 3008 controller: webview.WebviewController = new webview.WebviewController(); 3009 3010 build() { 3011 Column() { 3012 Button('requestFocus') 3013 .onClick(() => { 3014 try { 3015 this.controller.requestFocus(); 3016 } catch (error) { 3017 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3018 } 3019 }); 3020 Web({ src: 'www.example.com', controller: this.controller }) 3021 } 3022 } 3023} 3024``` 3025 3026### zoomIn 3027 3028zoomIn(): void 3029 3030Zooms in on this web page by 20%. 3031 3032**System capability**: SystemCapability.Web.Webview.Core 3033 3034**Error codes** 3035 3036For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3037 3038| ID| Error Message | 3039| -------- | ------------------------------------------------------------ | 3040| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3041| 17100004 | Function not enabled. | 3042 3043**Example** 3044 3045```ts 3046// xxx.ets 3047import { webview } from '@kit.ArkWeb'; 3048import { BusinessError } from '@kit.BasicServicesKit'; 3049 3050@Entry 3051@Component 3052struct WebComponent { 3053 controller: webview.WebviewController = new webview.WebviewController(); 3054 3055 build() { 3056 Column() { 3057 Button('zoomIn') 3058 .onClick(() => { 3059 try { 3060 this.controller.zoomIn(); 3061 } catch (error) { 3062 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3063 } 3064 }) 3065 Web({ src: 'www.example.com', controller: this.controller }) 3066 } 3067 } 3068} 3069``` 3070 3071### zoomOut 3072 3073zoomOut(): void 3074 3075Zooms out of this web page by 20%. 3076 3077**System capability**: SystemCapability.Web.Webview.Core 3078 3079**Error codes** 3080 3081For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3082 3083| ID| Error Message | 3084| -------- | ------------------------------------------------------------ | 3085| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3086| 17100004 | Function not enabled. | 3087 3088**Example** 3089 3090```ts 3091// xxx.ets 3092import { webview } from '@kit.ArkWeb'; 3093import { BusinessError } from '@kit.BasicServicesKit'; 3094 3095@Entry 3096@Component 3097struct WebComponent { 3098 controller: webview.WebviewController = new webview.WebviewController(); 3099 3100 build() { 3101 Column() { 3102 Button('zoomOut') 3103 .onClick(() => { 3104 try { 3105 this.controller.zoomOut(); 3106 } catch (error) { 3107 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3108 } 3109 }) 3110 Web({ src: 'www.example.com', controller: this.controller }) 3111 } 3112 } 3113} 3114``` 3115 3116### getHitTestValue 3117 3118getHitTestValue(): HitTestValue 3119 3120Obtains the element information of the area being clicked. 3121 3122**System capability**: SystemCapability.Web.Webview.Core 3123 3124**Return value** 3125 3126| Type | Description | 3127| ------------ | -------------------- | 3128| [HitTestValue](#hittestvalue) | Element information of the area being clicked.| 3129 3130**Error codes** 3131 3132For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3133 3134| ID| Error Message | 3135| -------- | ------------------------------------------------------------ | 3136| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3137 3138**Example** 3139 3140```ts 3141// xxx.ets 3142import { webview } from '@kit.ArkWeb'; 3143import { BusinessError } from '@kit.BasicServicesKit'; 3144 3145@Entry 3146@Component 3147struct WebComponent { 3148 controller: webview.WebviewController = new webview.WebviewController(); 3149 3150 build() { 3151 Column() { 3152 Button('getHitTestValue') 3153 .onClick(() => { 3154 try { 3155 let hitValue = this.controller.getHitTestValue(); 3156 console.log("hitType: " + hitValue.type); 3157 console.log("extra: " + hitValue.extra); 3158 } catch (error) { 3159 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3160 } 3161 }) 3162 Web({ src: 'www.example.com', controller: this.controller }) 3163 } 3164 } 3165} 3166``` 3167 3168### getWebId 3169 3170getWebId(): number 3171 3172Obtains the index value of this **Web** component, which can be used for **Web** component management. 3173 3174**System capability**: SystemCapability.Web.Webview.Core 3175 3176**Return value** 3177 3178| Type | Description | 3179| ------ | --------------------- | 3180| number | Index value of the current **Web** component.| 3181 3182**Error codes** 3183 3184For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3185 3186| ID| Error Message | 3187| -------- | ------------------------------------------------------------ | 3188| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3189 3190**Example** 3191 3192```ts 3193// xxx.ets 3194import { webview } from '@kit.ArkWeb'; 3195import { BusinessError } from '@kit.BasicServicesKit'; 3196 3197@Entry 3198@Component 3199struct WebComponent { 3200 controller: webview.WebviewController = new webview.WebviewController(); 3201 3202 build() { 3203 Column() { 3204 Button('getWebId') 3205 .onClick(() => { 3206 try { 3207 let id = this.controller.getWebId(); 3208 console.log("id: " + id); 3209 } catch (error) { 3210 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3211 } 3212 }) 3213 Web({ src: 'www.example.com', controller: this.controller }) 3214 } 3215 } 3216} 3217``` 3218 3219### getUserAgent 3220 3221getUserAgent(): string 3222 3223Obtains the default user agent of this web page. 3224 3225For details about the default **UserAgent**, see [Default User Agent String](../../web/web-default-userAgent.md). 3226 3227**System capability**: SystemCapability.Web.Webview.Core 3228 3229**Return value** 3230 3231| Type | Description | 3232| ------ | -------------- | 3233| string | Default user agent.| 3234 3235**Error codes** 3236 3237For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3238 3239| ID| Error Message | 3240| -------- | ------------------------------------------------------------ | 3241| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3242 3243**Example** 3244 3245```ts 3246// xxx.ets 3247import { webview } from '@kit.ArkWeb'; 3248import { BusinessError } from '@kit.BasicServicesKit'; 3249 3250@Entry 3251@Component 3252struct WebComponent { 3253 controller: webview.WebviewController = new webview.WebviewController(); 3254 3255 build() { 3256 Column() { 3257 Button('getUserAgent') 3258 .onClick(() => { 3259 try { 3260 let userAgent = this.controller.getUserAgent(); 3261 console.log("userAgent: " + userAgent); 3262 } catch (error) { 3263 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3264 } 3265 }) 3266 Web({ src: 'www.example.com', controller: this.controller }) 3267 } 3268 } 3269} 3270``` 3271 3272You can define a custom user agent based on the default user agent. 3273```ts 3274// xxx.ets 3275import { webview } from '@kit.ArkWeb'; 3276import { BusinessError } from '@kit.BasicServicesKit'; 3277 3278@Entry 3279@Component 3280struct WebComponent { 3281 controller: webview.WebviewController = new webview.WebviewController(); 3282 @State ua: string = ""; 3283 3284 aboutToAppear(): void { 3285 webview.once('webInited', () => { 3286 try { 3287 // Define a custom user agent on the application side. 3288 this.ua = this.controller.getUserAgent() + 'xxx'; 3289 this.controller.setCustomUserAgent(this.ua); 3290 } catch (error) { 3291 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3292 } 3293 }) 3294 } 3295 3296 build() { 3297 Column() { 3298 Web({ src: 'www.example.com', controller: this.controller }) 3299 } 3300 } 3301} 3302``` 3303 3304### getTitle 3305 3306getTitle(): string 3307 3308Obtains the title of the current web page. 3309 3310**System capability**: SystemCapability.Web.Webview.Core 3311 3312**Return value** 3313 3314| Type | Description | 3315| ------ | -------------------- | 3316| string | Title of the current web page.| 3317 3318**Error codes** 3319 3320For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3321 3322| ID| Error Message | 3323| -------- | ------------------------------------------------------------ | 3324| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3325 3326**Example** 3327 3328```ts 3329// xxx.ets 3330import { webview } from '@kit.ArkWeb'; 3331import { BusinessError } from '@kit.BasicServicesKit'; 3332 3333@Entry 3334@Component 3335struct WebComponent { 3336 controller: webview.WebviewController = new webview.WebviewController(); 3337 3338 build() { 3339 Column() { 3340 Button('getTitle') 3341 .onClick(() => { 3342 try { 3343 let title = this.controller.getTitle(); 3344 console.log("title: " + title); 3345 } catch (error) { 3346 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3347 } 3348 }) 3349 Web({ src: 'www.example.com', controller: this.controller }) 3350 } 3351 } 3352} 3353``` 3354 3355### getPageHeight 3356 3357getPageHeight(): number 3358 3359Obtains the height of this web page. 3360 3361**System capability**: SystemCapability.Web.Webview.Core 3362 3363**Return value** 3364 3365| Type | Description | 3366| ------ | -------------------- | 3367| number | Height of the current web page. Unit: vp| 3368 3369**Error codes** 3370 3371For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3372 3373| ID| Error Message | 3374| -------- | ------------------------------------------------------------ | 3375| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3376 3377**Example** 3378 3379```ts 3380// xxx.ets 3381import { webview } from '@kit.ArkWeb'; 3382import { BusinessError } from '@kit.BasicServicesKit'; 3383 3384@Entry 3385@Component 3386struct WebComponent { 3387 controller: webview.WebviewController = new webview.WebviewController(); 3388 3389 build() { 3390 Column() { 3391 Button('getPageHeight') 3392 .onClick(() => { 3393 try { 3394 let pageHeight = this.controller.getPageHeight(); 3395 console.log("pageHeight : " + pageHeight); 3396 } catch (error) { 3397 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3398 } 3399 }) 3400 Web({ src: 'www.example.com', controller: this.controller }) 3401 } 3402 } 3403} 3404``` 3405 3406### storeWebArchive 3407 3408storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback\<string>): void 3409 3410Stores this web page. This API uses an asynchronous callback to return the result. 3411 3412**System capability**: SystemCapability.Web.Webview.Core 3413 3414**Parameters** 3415 3416| Name | Type | Mandatory| Description | 3417| -------- | --------------------- | ---- | ------------------------------------------------------------ | 3418| baseName | string | Yes | Save path of the web page. The value cannot be null. | 3419| 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.| 3420| callback | AsyncCallback\<string> | Yes | Callback used to return the save path if the operation is successful and null otherwise. | 3421 3422**Error codes** 3423 3424For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3425 3426| ID| Error Message | 3427| -------- | ------------------------------------------------------------ | 3428| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3429| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3430| 17100003 | Invalid resource path or file type. | 3431 3432**Example** 3433 3434```ts 3435// xxx.ets 3436import { webview } from '@kit.ArkWeb'; 3437import { BusinessError } from '@kit.BasicServicesKit'; 3438 3439@Entry 3440@Component 3441struct WebComponent { 3442 controller: webview.WebviewController = new webview.WebviewController(); 3443 3444 build() { 3445 Column() { 3446 Button('storeWebArchive') 3447 .onClick(() => { 3448 try { 3449 this.controller.storeWebArchive("/data/storage/el2/base/", true, (error, filename) => { 3450 if (error) { 3451 console.error(`save web archive error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3452 return; 3453 } 3454 if (filename != null) { 3455 console.info(`save web archive success: ${filename}`); 3456 } 3457 }); 3458 } catch (error) { 3459 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3460 } 3461 }) 3462 Web({ src: 'www.example.com', controller: this.controller }) 3463 } 3464 } 3465} 3466``` 3467 3468### storeWebArchive 3469 3470storeWebArchive(baseName: string, autoName: boolean): Promise\<string> 3471 3472Stores this web page. This API uses a promise to return the result. 3473 3474**System capability**: SystemCapability.Web.Webview.Core 3475 3476**Parameters** 3477 3478| Name | Type| Mandatory| Description | 3479| -------- | -------- | ---- | ------------------------------------------------------------ | 3480| baseName | string | Yes | Save path of the web page. The value cannot be null. | 3481| 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.| 3482 3483**Return value** 3484 3485| Type | Description | 3486| --------------- | ----------------------------------------------------- | 3487| Promise\<string> | Promise used to return the save path if the operation is successful and null otherwise.| 3488 3489**Error codes** 3490 3491For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3492 3493| ID| Error Message | 3494| -------- | ------------------------------------------------------------ | 3495| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3496| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3497| 17100003 | Invalid resource path or file type. | 3498 3499**Example** 3500 3501```ts 3502// xxx.ets 3503import { webview } from '@kit.ArkWeb'; 3504import { BusinessError } from '@kit.BasicServicesKit'; 3505 3506@Entry 3507@Component 3508struct WebComponent { 3509 controller: webview.WebviewController = new webview.WebviewController(); 3510 3511 build() { 3512 Column() { 3513 Button('storeWebArchive') 3514 .onClick(() => { 3515 try { 3516 this.controller.storeWebArchive("/data/storage/el2/base/", true) 3517 .then(filename => { 3518 if (filename != null) { 3519 console.info(`save web archive success: ${filename}`) 3520 } 3521 }) 3522 .catch((error: BusinessError) => { 3523 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 3524 }) 3525 } catch (error) { 3526 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3527 } 3528 }) 3529 Web({ src: 'www.example.com', controller: this.controller }) 3530 } 3531 } 3532} 3533``` 3534 3535### getUrl 3536 3537getUrl(): string 3538 3539Obtains the URL of this page. 3540 3541**System capability**: SystemCapability.Web.Webview.Core 3542 3543**Return value** 3544 3545| Type | Description | 3546| ------ | ------------------- | 3547| string | URL of the current page.| 3548 3549**Error codes** 3550 3551For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3552 3553| ID| Error Message | 3554| -------- | ------------------------------------------------------------ | 3555| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3556 3557**Example** 3558 3559```ts 3560// xxx.ets 3561import { webview } from '@kit.ArkWeb'; 3562import { BusinessError } from '@kit.BasicServicesKit'; 3563 3564@Entry 3565@Component 3566struct WebComponent { 3567 controller: webview.WebviewController = new webview.WebviewController(); 3568 3569 build() { 3570 Column() { 3571 Button('getUrl') 3572 .onClick(() => { 3573 try { 3574 let url = this.controller.getUrl(); 3575 console.log("url: " + url); 3576 } catch (error) { 3577 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3578 } 3579 }) 3580 Web({ src: 'www.example.com', controller: this.controller }) 3581 } 3582 } 3583} 3584``` 3585 3586### stop 3587 3588stop(): void 3589 3590Stops page loading. 3591 3592**System capability**: SystemCapability.Web.Webview.Core 3593 3594**Error codes** 3595 3596For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3597 3598| ID| Error Message | 3599| -------- | ------------------------------------------------------------ | 3600| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3601 3602**Example** 3603 3604```ts 3605// xxx.ets 3606import { webview } from '@kit.ArkWeb'; 3607import { BusinessError } from '@kit.BasicServicesKit'; 3608 3609@Entry 3610@Component 3611struct WebComponent { 3612 controller: webview.WebviewController = new webview.WebviewController(); 3613 3614 build() { 3615 Column() { 3616 Button('stop') 3617 .onClick(() => { 3618 try { 3619 this.controller.stop(); 3620 } catch (error) { 3621 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3622 } 3623 }); 3624 Web({ src: 'www.example.com', controller: this.controller }) 3625 } 3626 } 3627} 3628``` 3629 3630### backOrForward 3631 3632backOrForward(step: number): void 3633 3634Performs 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. 3635 3636Because the previously loaded web pages are used for the operation, no page reloading is involved. 3637 3638**System capability**: SystemCapability.Web.Webview.Core 3639 3640**Parameters** 3641 3642| Name| Type| Mandatory| Description | 3643| ------ | -------- | ---- | ---------------------- | 3644| step | number | Yes | Number of the steps to take.| 3645 3646**Error codes** 3647 3648For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3649 3650| ID| Error Message | 3651| -------- | ------------------------------------------------------------ | 3652| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3653| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3654 3655**Example** 3656 3657```ts 3658// xxx.ets 3659import { webview } from '@kit.ArkWeb'; 3660import { BusinessError } from '@kit.BasicServicesKit'; 3661 3662@Entry 3663@Component 3664struct WebComponent { 3665 controller: webview.WebviewController = new webview.WebviewController(); 3666 @State step: number = -2; 3667 3668 build() { 3669 Column() { 3670 Button('backOrForward') 3671 .onClick(() => { 3672 try { 3673 this.controller.backOrForward(this.step); 3674 } catch (error) { 3675 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3676 } 3677 }) 3678 Web({ src: 'www.example.com', controller: this.controller }) 3679 } 3680 } 3681} 3682``` 3683 3684### scrollTo 3685 3686scrollTo(x:number, y:number, duration?:number): void 3687 3688Scrolls the page to the specified absolute position within a specified period. 3689 3690**System capability**: SystemCapability.Web.Webview.Core 3691 3692**Parameters** 3693 3694| Name| Type| Mandatory| Description | 3695| ------ | -------- | ---- | ---------------------- | 3696| x | number | Yes | X coordinate of the absolute position. If the value is a negative number, the value 0 is used. Unit: vp| 3697| y | number | Yes | Y coordinate of the absolute position. If the value is a negative number, the value 0 is used. Unit: vp| 3698| 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.| 3699 3700**Error codes** 3701 3702For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3703 3704| ID| Error Message | 3705| -------- | ------------------------------------------------------------ | 3706| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3707| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3708 3709**Example** 3710 3711```ts 3712// xxx.ets 3713import { webview } from '@kit.ArkWeb'; 3714import { BusinessError } from '@kit.BasicServicesKit'; 3715 3716@Entry 3717@Component 3718struct WebComponent { 3719 controller: webview.WebviewController = new webview.WebviewController(); 3720 3721 build() { 3722 Column() { 3723 Button('scrollTo') 3724 .onClick(() => { 3725 try { 3726 this.controller.scrollTo(50, 50, 500); 3727 } catch (error) { 3728 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3729 } 3730 }) 3731 Button('stopScroll') 3732 .onClick(() => { 3733 try { 3734 this.controller.scrollBy(0, 0, 1); // If you want to stop the animation generated by the current scroll, you can generate another 1ms animation to interrupt the animation. 3735 } catch (error) { 3736 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3737 } 3738 }) 3739 Web({ src: $rawfile('index.html'), controller: this.controller }) 3740 } 3741 } 3742} 3743``` 3744 3745HTML file to be loaded: 3746```html 3747<!--index.html--> 3748<!DOCTYPE html> 3749<html> 3750<head> 3751 <title>Demo</title> 3752 <style> 3753 body { 3754 width:2000px; 3755 height:2000px; 3756 padding-right:170px; 3757 padding-left:170px; 3758 border:5px solid blueviolet 3759 } 3760 </style> 3761</head> 3762<body> 3763Scroll Test 3764</body> 3765</html> 3766``` 3767 3768### scrollBy 3769 3770scrollBy(deltaX:number, deltaY:number,duration?:number): void 3771 3772Scrolls the page by the specified amount within a specified period. 3773 3774**System capability**: SystemCapability.Web.Webview.Core 3775 3776**Parameters** 3777 3778| Name| Type| Mandatory| Description | 3779| ------ | -------- | ---- | ---------------------- | 3780| deltaX | number | Yes | Amount to scroll by along the x-axis. The positive direction is rightward. Unit: vp| 3781| deltaY | number | Yes | Amount to scroll by along the y-axis. The positive direction is downward. Unit: vp| 3782| 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.| 3783 3784**Error codes** 3785 3786For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3787 3788| ID| Error Message | 3789| -------- | ------------------------------------------------------------ | 3790| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3791| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3792 3793> **NOTE** 3794> 3795> Calling **scrollBy** does not trigger the nested scrolling of the parent component. 3796 3797**Example** 3798 3799```ts 3800// xxx.ets 3801import { webview } from '@kit.ArkWeb'; 3802import { BusinessError } from '@kit.BasicServicesKit'; 3803 3804@Entry 3805@Component 3806struct WebComponent { 3807 controller: webview.WebviewController = new webview.WebviewController(); 3808 3809 build() { 3810 Column() { 3811 Button('scrollBy') 3812 .onClick(() => { 3813 try { 3814 this.controller.scrollBy(50, 50, 500); 3815 } catch (error) { 3816 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3817 } 3818 }) 3819 Button('stopScroll') 3820 .onClick(() => { 3821 try { 3822 this.controller.scrollBy(0, 0, 1); // If you want to stop the animation generated by the current scroll, you can generate another 1ms animation to interrupt the animation. 3823 } catch (error) { 3824 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3825 } 3826 }) 3827 Web({ src: $rawfile('index.html'), controller: this.controller }) 3828 } 3829 } 3830} 3831``` 3832 3833HTML file to be loaded: 3834```html 3835<!--index.html--> 3836<!DOCTYPE html> 3837<html> 3838<head> 3839 <title>Demo</title> 3840 <style> 3841 body { 3842 width:2000px; 3843 height:2000px; 3844 padding-right:170px; 3845 padding-left:170px; 3846 border:5px solid blueviolet 3847 } 3848 </style> 3849</head> 3850<body> 3851Scroll Test 3852</body> 3853</html> 3854``` 3855### scrollByWithResult<sup>12+</sup> 3856 3857scrollByWithResult(deltaX: number, deltaY: number): boolean 3858 3859Scrolls the page by the specified amount and returns value to indicate whether the scrolling is successful. 3860 3861**System capability**: SystemCapability.Web.Webview.Core 3862 3863**Parameters** 3864 3865| Name| Type| Mandatory| Description | 3866| ------ | -------- | ---- | ---------------------- | 3867| deltaX | number | Yes | Amount to scroll by along the x-axis. The positive direction is rightward.| 3868| deltaY | number | Yes | Amount to scroll by along the y-axis. The positive direction is downward.| 3869 3870**Return value** 3871 3872| Type | Description | 3873| ------- | --------------------------------------- | 3874| boolean | Whether the current web page can be scrolled. The default value is **false**.| 3875 3876**Error codes** 3877 3878For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3879 3880| ID| Error Message | 3881| -------- | ------------------------------------------------------------ | 3882| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3883| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3884 3885> **NOTE** 3886> 3887> - If the web page is being touched, **false** is returned. Otherwise, **true** is returned. 3888> - If the rendering area at the same layer of the web page is being touched, **true** is returned. 3889> - Calling **scrollByWithResult** does not trigger the nested scrolling of the parent component. 3890> - This API does not support the high frame rate of scrolling performance. 3891 3892**Example** 3893 3894```ts 3895// xxx.ets 3896import { webview } from '@kit.ArkWeb'; 3897import { BusinessError } from '@kit.BasicServicesKit'; 3898 3899@Entry 3900@Component 3901struct WebComponent { 3902 controller: webview.WebviewController = new webview.WebviewController(); 3903 3904 build() { 3905 Column() { 3906 Button('scrollByWithResult') 3907 .onClick(() => { 3908 try { 3909 let result = this.controller.scrollByWithResult(50, 50); 3910 console.log("original result: " + result); 3911 } catch (error) { 3912 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3913 } 3914 }) 3915 Web({ src: $rawfile('index.html'), controller: this.controller }) 3916 } 3917 } 3918} 3919``` 3920 3921HTML file to be loaded: 3922```html 3923<!--index.html--> 3924<!DOCTYPE html> 3925<html> 3926<head> 3927 <title>Demo</title> 3928 <style> 3929 body { 3930 width:2000px; 3931 height:2000px; 3932 padding-right:170px; 3933 padding-left:170px; 3934 border:5px solid blueviolet 3935 } 3936 </style> 3937</head> 3938<body> 3939Scroll Test 3940</body> 3941</html> 3942``` 3943### slideScroll 3944 3945slideScroll(vx:number, vy:number): void 3946 3947Simulates a slide-to-scroll action on the page at the specified velocity. 3948 3949**System capability**: SystemCapability.Web.Webview.Core 3950 3951**Parameters** 3952 3953| Name| Type| Mandatory| Description | 3954| ------ | -------- | ---- | ---------------------- | 3955| vx | number | Yes | Horizontal velocity component of the slide-to-scroll action, where the positive direction is rightward. Unit: vp/ms.| 3956| vy | number | Yes | Vertical velocity component of the slide-to-scroll action, where the positive direction is downward. Unit: vp/ms.| 3957 3958**Error codes** 3959 3960For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3961 3962| ID| Error Message | 3963| -------- | ------------------------------------------------------------ | 3964| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3965| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3966 3967**Example** 3968 3969```ts 3970// xxx.ets 3971import { webview } from '@kit.ArkWeb'; 3972import { BusinessError } from '@kit.BasicServicesKit'; 3973 3974@Entry 3975@Component 3976struct WebComponent { 3977 controller: webview.WebviewController = new webview.WebviewController(); 3978 3979 build() { 3980 Column() { 3981 Button('slideScroll') 3982 .onClick(() => { 3983 try { 3984 this.controller.slideScroll(500, 500); 3985 } catch (error) { 3986 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3987 } 3988 }) 3989 Web({ src: $rawfile('index.html'), controller: this.controller }) 3990 } 3991 } 3992} 3993``` 3994 3995HTML file to be loaded: 3996```html 3997<!--index.html--> 3998<!DOCTYPE html> 3999<html> 4000<head> 4001 <title>Demo</title> 4002 <style> 4003 body { 4004 width:3000px; 4005 height:3000px; 4006 padding-right:170px; 4007 padding-left:170px; 4008 border:5px solid blueviolet 4009 } 4010 </style> 4011</head> 4012<body> 4013Scroll Test 4014</body> 4015</html> 4016``` 4017 4018### getOriginalUrl 4019 4020getOriginalUrl(): string 4021 4022Obtains the original URL of this page. 4023Risk warning: If you want to obtain the URL for JavaScriptProxy communication API authentication, use [getLastJavascriptProxyCallingFrameUrl<sup>12+</sup>](#getlastjavascriptproxycallingframeurl12). 4024 4025**System capability**: SystemCapability.Web.Webview.Core 4026 4027**Return value** 4028 4029| Type | Description | 4030| ------ | ----------------------- | 4031| string | Original URL of the current page.| 4032 4033**Error codes** 4034 4035For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4036 4037| ID| Error Message | 4038| -------- | ------------------------------------------------------------ | 4039| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4040 4041**Example** 4042 4043```ts 4044// xxx.ets 4045import { webview } from '@kit.ArkWeb'; 4046import { BusinessError } from '@kit.BasicServicesKit'; 4047 4048@Entry 4049@Component 4050struct WebComponent { 4051 controller: webview.WebviewController = new webview.WebviewController(); 4052 4053 build() { 4054 Column() { 4055 Button('getOrgUrl') 4056 .onClick(() => { 4057 try { 4058 let url = this.controller.getOriginalUrl(); 4059 console.log("original url: " + url); 4060 } catch (error) { 4061 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4062 } 4063 }) 4064 Web({ src: 'www.example.com', controller: this.controller }) 4065 } 4066 } 4067} 4068``` 4069 4070### getFavicon 4071 4072getFavicon(): image.PixelMap 4073 4074Obtains the favicon of this page. 4075 4076**System capability**: SystemCapability.Web.Webview.Core 4077 4078**Return value** 4079 4080| Type | Description | 4081| -------------------------------------- | ------------------------------- | 4082| [PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | **PixelMap** object of the favicon of the page.| 4083 4084**Error codes** 4085 4086For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4087 4088| ID| Error Message | 4089| -------- | ------------------------------------------------------------ | 4090| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4091 4092**Example** 4093 4094```ts 4095// xxx.ets 4096import { webview } from '@kit.ArkWeb'; 4097import { BusinessError } from '@kit.BasicServicesKit'; 4098import { image } from '@kit.ImageKit'; 4099 4100@Entry 4101@Component 4102struct WebComponent { 4103 controller: webview.WebviewController = new webview.WebviewController(); 4104 @State pixelmap: image.PixelMap | undefined = undefined; 4105 4106 build() { 4107 Column() { 4108 Button('getFavicon') 4109 .onClick(() => { 4110 try { 4111 this.pixelmap = this.controller.getFavicon(); 4112 } catch (error) { 4113 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4114 } 4115 }) 4116 Web({ src: 'www.example.com', controller: this.controller }) 4117 } 4118 } 4119} 4120``` 4121 4122### setNetworkAvailable 4123 4124setNetworkAvailable(enable: boolean): void 4125 4126Sets the **window.navigator.onLine** attribute in JavaScript. 4127 4128**System capability**: SystemCapability.Web.Webview.Core 4129 4130**Parameters** 4131 4132| Name| Type | Mandatory| Description | 4133| ------ | ------- | ---- | --------------------------------- | 4134| enable | boolean | Yes | Whether to enable **window.navigator.onLine**.| 4135 4136**Error codes** 4137 4138For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4139 4140| ID| Error Message | 4141| -------- | ------------------------------------------------------------ | 4142| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4143| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4144 4145**Example** 4146 4147```ts 4148// xxx.ets 4149import { webview } from '@kit.ArkWeb'; 4150import { BusinessError } from '@kit.BasicServicesKit'; 4151 4152@Entry 4153@Component 4154struct WebComponent { 4155 controller: webview.WebviewController = new webview.WebviewController(); 4156 4157 build() { 4158 Column() { 4159 Button('setNetworkAvailable') 4160 .onClick(() => { 4161 try { 4162 this.controller.setNetworkAvailable(true); 4163 } catch (error) { 4164 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4165 } 4166 }) 4167 Web({ src: $rawfile('index.html'), controller: this.controller }) 4168 } 4169 } 4170} 4171``` 4172 4173HTML file to be loaded: 4174```html 4175<!-- index.html --> 4176<!DOCTYPE html> 4177<html> 4178<body> 4179<h1>online attribute </h1> 4180<p id="demo"></p> 4181<button onclick="func()">click</button> 4182<script> 4183 let online = navigator.onLine; 4184 document.getElementById ("demo").innerHTML = "Browser online:" + online; 4185 4186 function func(){ 4187 var online = navigator.onLine; 4188 document.getElementById ("demo").innerHTML = "Browser online:" + online; 4189 } 4190</script> 4191</body> 4192</html> 4193``` 4194 4195### hasImage 4196 4197hasImage(callback: AsyncCallback\<boolean>): void 4198 4199Checks whether this page contains images. This API uses an asynchronous callback to return the result. 4200 4201**System capability**: SystemCapability.Web.Webview.Core 4202 4203**Parameters** 4204 4205| Name | Type | Mandatory| Description | 4206| -------- | ----------------------- | ---- | -------------------------- | 4207| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result.| 4208 4209**Error codes** 4210 4211For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4212 4213| ID| Error Message | 4214| -------- | ------------------------------------------------------------ | 4215| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4216| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4217 4218**Example** 4219 4220```ts 4221// xxx.ets 4222import { webview } from '@kit.ArkWeb'; 4223import { BusinessError } from '@kit.BasicServicesKit'; 4224 4225@Entry 4226@Component 4227struct WebComponent { 4228 controller: webview.WebviewController = new webview.WebviewController(); 4229 4230 build() { 4231 Column() { 4232 Button('hasImageCb') 4233 .onClick(() => { 4234 try { 4235 this.controller.hasImage((error, data) => { 4236 if (error) { 4237 console.error(`hasImage error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4238 return; 4239 } 4240 console.info("hasImage: " + data); 4241 }); 4242 } catch (error) { 4243 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4244 } 4245 }) 4246 Web({ src: 'www.example.com', controller: this.controller }) 4247 } 4248 } 4249} 4250``` 4251 4252### hasImage 4253 4254hasImage(): Promise\<boolean> 4255 4256Checks whether this page contains images. This API uses a promise to return the result. 4257 4258**System capability**: SystemCapability.Web.Webview.Core 4259 4260**Return value** 4261 4262| Type | Description | 4263| ----------------- | --------------------------------------- | 4264| Promise\<boolean> | Promise used to return the result.| 4265 4266**Error codes** 4267 4268For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4269 4270| ID| Error Message | 4271| -------- | ------------------------------------------------------------ | 4272| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4273| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 4274 4275**Example** 4276 4277```ts 4278// xxx.ets 4279import { webview } from '@kit.ArkWeb'; 4280import { BusinessError } from '@kit.BasicServicesKit'; 4281 4282@Entry 4283@Component 4284struct WebComponent { 4285 controller: webview.WebviewController = new webview.WebviewController(); 4286 4287 build() { 4288 Column() { 4289 Button('hasImagePm') 4290 .onClick(() => { 4291 try { 4292 this.controller.hasImage().then((data) => { 4293 console.info('hasImage: ' + data); 4294 }).catch((error: BusinessError) => { 4295 console.error("error: " + error); 4296 }) 4297 } catch (error) { 4298 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4299 } 4300 }) 4301 Web({ src: 'www.example.com', controller: this.controller }) 4302 } 4303 } 4304} 4305``` 4306 4307### removeCache 4308 4309removeCache(clearRom: boolean): void 4310 4311Clears the cache in the application. This API will clear the cache for all webviews in the same application. 4312 4313> **NOTE** 4314> 4315> You can view the Webview cache in the **data/storage/el2/base/cache/web/Cache** directory. 4316 4317**System capability**: SystemCapability.Web.Webview.Core 4318 4319**Parameters** 4320 4321| Name | Type | Mandatory| Description | 4322| -------- | ------- | ---- | -------------------------------------------------------- | 4323| 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.| 4324 4325**Error codes** 4326 4327For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4328 4329| ID| Error Message | 4330| -------- | ------------------------------------------------------------ | 4331| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4332| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4333 4334**Example** 4335 4336```ts 4337// xxx.ets 4338import { webview } from '@kit.ArkWeb'; 4339import { BusinessError } from '@kit.BasicServicesKit'; 4340 4341@Entry 4342@Component 4343struct WebComponent { 4344 controller: webview.WebviewController = new webview.WebviewController(); 4345 4346 build() { 4347 Column() { 4348 Button('removeCache') 4349 .onClick(() => { 4350 try { 4351 this.controller.removeCache(false); 4352 } catch (error) { 4353 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4354 } 4355 }) 4356 Web({ src: 'www.example.com', controller: this.controller }) 4357 } 4358 } 4359} 4360``` 4361 4362### pageUp 4363 4364pageUp(top: boolean): void 4365 4366Scrolls the page up by half the viewport or jumps to the top of the page. 4367 4368**System capability**: SystemCapability.Web.Webview.Core 4369 4370**Parameters** 4371 4372| Name| Type | Mandatory| Description | 4373| ------ | ------- | ---- | ------------------------------------------------------------ | 4374| 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.| 4375 4376**Error codes** 4377 4378For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4379 4380| ID| Error Message | 4381| -------- | ------------------------------------------------------------ | 4382| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4383| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4384 4385**Example** 4386 4387```ts 4388// xxx.ets 4389import { webview } from '@kit.ArkWeb'; 4390import { BusinessError } from '@kit.BasicServicesKit'; 4391 4392@Entry 4393@Component 4394struct WebComponent { 4395 controller: webview.WebviewController = new webview.WebviewController(); 4396 4397 build() { 4398 Column() { 4399 Button('pageUp') 4400 .onClick(() => { 4401 try { 4402 this.controller.pageUp(false); 4403 } catch (error) { 4404 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4405 } 4406 }) 4407 Web({ src: 'www.example.com', controller: this.controller }) 4408 } 4409 } 4410} 4411``` 4412 4413### pageDown 4414 4415pageDown(bottom: boolean): void 4416 4417Scrolls the page down by half the viewport or jumps to the bottom of the page. 4418 4419**System capability**: SystemCapability.Web.Webview.Core 4420 4421**Parameters** 4422 4423| Name| Type | Mandatory| Description | 4424| ------ | ------- | ---- | ------------------------------------------------------------ | 4425| 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.| 4426 4427**Error codes** 4428 4429For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4430 4431| ID| Error Message | 4432| -------- | ------------------------------------------------------------ | 4433| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4434| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4435 4436**Example** 4437 4438```ts 4439// xxx.ets 4440import { webview } from '@kit.ArkWeb'; 4441import { BusinessError } from '@kit.BasicServicesKit'; 4442 4443@Entry 4444@Component 4445struct WebComponent { 4446 controller: webview.WebviewController = new webview.WebviewController(); 4447 4448 build() { 4449 Column() { 4450 Button('pageDown') 4451 .onClick(() => { 4452 try { 4453 this.controller.pageDown(false); 4454 } catch (error) { 4455 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4456 } 4457 }) 4458 Web({ src: 'www.example.com', controller: this.controller }) 4459 } 4460 } 4461} 4462``` 4463 4464### getBackForwardEntries 4465 4466getBackForwardEntries(): BackForwardList 4467 4468Obtains the historical information list of the current webview. 4469 4470**System capability**: SystemCapability.Web.Webview.Core 4471 4472**Return value** 4473 4474| Type | Description | 4475| ----------------------------------- | --------------------------- | 4476| [BackForwardList](#backforwardlist) | The historical information list of the current webview.| 4477 4478**Error codes** 4479 4480For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4481 4482| ID| Error Message | 4483| -------- | ------------------------------------------------------------ | 4484| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4485 4486**Example** 4487 4488```ts 4489// xxx.ets 4490import { webview } from '@kit.ArkWeb'; 4491import { BusinessError } from '@kit.BasicServicesKit'; 4492 4493@Entry 4494@Component 4495struct WebComponent { 4496 controller: webview.WebviewController = new webview.WebviewController(); 4497 4498 build() { 4499 Column() { 4500 Button('getBackForwardEntries') 4501 .onClick(() => { 4502 try { 4503 let list = this.controller.getBackForwardEntries() 4504 } catch (error) { 4505 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4506 } 4507 }) 4508 Web({ src: 'www.example.com', controller: this.controller }) 4509 } 4510 } 4511} 4512``` 4513 4514### serializeWebState 4515 4516serializeWebState(): Uint8Array 4517 4518Serializes the page status history of the current Webview. 4519 4520**System capability**: SystemCapability.Web.Webview.Core 4521 4522**Return value** 4523 4524| Type | Description | 4525| ---------- | --------------------------------------------- | 4526| Uint8Array | Serialized data of the page status history of the current WebView.| 4527 4528**Error codes** 4529 4530For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4531 4532| ID| Error Message | 4533| -------- | ------------------------------------------------------------ | 4534| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4535 4536**Example** 4537 45381. 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). 4539```ts 4540// xxx.ets 4541import { webview } from '@kit.ArkWeb'; 4542import { BusinessError } from '@kit.BasicServicesKit'; 4543import { fileIo } from '@kit.CoreFileKit'; 4544 4545@Entry 4546@Component 4547struct WebComponent { 4548 controller: webview.WebviewController = new webview.WebviewController(); 4549 4550 build() { 4551 Column() { 4552 Button('serializeWebState') 4553 .onClick(() => { 4554 try { 4555 let state = this.controller.serializeWebState(); 4556 let path:string | undefined = AppStorage.get("cacheDir"); 4557 if (path) { 4558 path += '/WebState'; 4559 // Synchronously open a file. 4560 let file = fileIo.openSync(path, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); 4561 fileIo.writeSync(file.fd, state.buffer); 4562 fileIo.closeSync(file.fd); 4563 } 4564 } catch (error) { 4565 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4566 } 4567 }) 4568 Web({ src: 'www.example.com', controller: this.controller }) 4569 } 4570 } 4571} 4572``` 4573 45742. Modify the **EntryAbility.ets** file. 4575Obtain the path of the application cache file. 4576```ts 4577// xxx.ets 4578import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 4579 4580export default class EntryAbility extends UIAbility { 4581 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 4582 // Data synchronization between the UIAbility component and the page can be implemented by binding cacheDir to the AppStorage object. 4583 AppStorage.setOrCreate("cacheDir", this.context.cacheDir); 4584 } 4585} 4586``` 4587 4588### restoreWebState 4589 4590restoreWebState(state: Uint8Array): void 4591 4592Restores the page status history from the serialized data of the current WebView. 4593 4594If 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. 4595 4596**System capability**: SystemCapability.Web.Webview.Core 4597 4598**Parameters** 4599 4600| Name| Type | Mandatory| Description | 4601| ------ | ---------- | ---- | ---------------------------- | 4602| state | Uint8Array | Yes | Serialized data of the page status history.| 4603 4604**Error codes** 4605 4606For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4607 4608| ID| Error Message | 4609| -------- | ------------------------------------------------------------ | 4610| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4611| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 4612 4613**Example** 4614 46151. 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). 4616```ts 4617// xxx.ets 4618import { webview } from '@kit.ArkWeb'; 4619import { BusinessError } from '@kit.BasicServicesKit'; 4620import { fileIo } from '@kit.CoreFileKit'; 4621 4622@Entry 4623@Component 4624struct WebComponent { 4625 controller: webview.WebviewController = new webview.WebviewController(); 4626 4627 build() { 4628 Column() { 4629 Button('RestoreWebState') 4630 .onClick(() => { 4631 try { 4632 let path: string | undefined = AppStorage.get("cacheDir"); 4633 if (path) { 4634 path += '/WebState'; 4635 // Synchronously open a file. 4636 let file = fileIo.openSync(path, fileIo.OpenMode.READ_WRITE); 4637 let stat = fileIo.statSync(path); 4638 let size = stat.size; 4639 let buf = new ArrayBuffer(size); 4640 fileIo.read(file.fd, buf, (err, readLen) => { 4641 if (err) { 4642 console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); 4643 } else { 4644 console.info("read file data succeed"); 4645 this.controller.restoreWebState(new Uint8Array(buf.slice(0, readLen))); 4646 fileIo.closeSync(file); 4647 } 4648 }); 4649 } 4650 } catch (error) { 4651 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4652 } 4653 }) 4654 Web({ src: 'www.example.com', controller: this.controller }) 4655 } 4656 } 4657} 4658``` 4659 46602. Modify the **EntryAbility.ets** file. 4661Obtain the path of the application cache file. 4662```ts 4663// xxx.ets 4664import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 4665 4666export default class EntryAbility extends UIAbility { 4667 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 4668 // Data synchronization between the UIAbility component and the page can be implemented by binding cacheDir to the AppStorage object. 4669 AppStorage.setOrCreate("cacheDir", this.context.cacheDir); 4670 } 4671} 4672``` 4673 4674### customizeSchemes 4675 4676static customizeSchemes(schemes: Array\<WebCustomScheme\>): void 4677 4678Grants 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. 4679 4680**System capability**: SystemCapability.Web.Webview.Core 4681 4682**Parameters** 4683 4684| Name | Type | Mandatory| Description | 4685| -------- | ------- | ---- | -------------------------------------- | 4686| schemes | Array\<[WebCustomScheme](#webcustomscheme)\> | Yes | Array of up to 10 custom schemes.| 4687 4688**Error codes** 4689 4690For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4691 4692| ID| Error Message | 4693| -------- | ------------------------------------------------------------ | 4694| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4695| 17100020 | Failed to register custom schemes. | 4696 4697**Example** 4698 4699```ts 4700// xxx.ets 4701import { webview } from '@kit.ArkWeb'; 4702import { BusinessError } from '@kit.BasicServicesKit'; 4703 4704@Entry 4705@Component 4706struct WebComponent { 4707 controller: webview.WebviewController = new webview.WebviewController(); 4708 responseWeb: WebResourceResponse = new WebResourceResponse(); 4709 scheme1: webview.WebCustomScheme = { schemeName: "name1", isSupportCORS: true, isSupportFetch: true }; 4710 scheme2: webview.WebCustomScheme = { schemeName: "name2", isSupportCORS: true, isSupportFetch: true }; 4711 scheme3: webview.WebCustomScheme = { schemeName: "name3", isSupportCORS: true, isSupportFetch: true }; 4712 4713 aboutToAppear(): void { 4714 try { 4715 webview.WebviewController.customizeSchemes([this.scheme1, this.scheme2, this.scheme3]); 4716 } catch (error) { 4717 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4718 } 4719 } 4720 4721 build() { 4722 Column() { 4723 Web({ src: 'www.example.com', controller: this.controller }) 4724 .onInterceptRequest((event) => { 4725 if (event) { 4726 console.log('url:' + event.request.getRequestUrl()); 4727 } 4728 return this.responseWeb; 4729 }) 4730 } 4731 } 4732} 4733``` 4734 4735### getCertificate<sup>10+</sup> 4736 4737getCertificate(): Promise<Array<cert.X509Cert>> 4738 4739Obtains 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. 4740 4741**System capability**: SystemCapability.Web.Webview.Core 4742 4743**Return value** 4744 4745| Type | Description | 4746| ---------- | --------------------------------------------- | 4747| Promise<Array<cert.X509Cert>> | Promise used to obtain the X.509 certificate array of the current HTTPS website.| 4748 4749**Error codes** 4750 4751For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4752 4753| ID| Error Message | 4754| -------- | ------------------------------------------------------------ | 4755| 17100001 | Init error. The WebviewController must be associated with a web component. | 4756 4757**Example** 4758 4759```ts 4760// xxx.ets 4761import { webview } from '@kit.ArkWeb'; 4762import { BusinessError } from '@kit.BasicServicesKit'; 4763import { cert } from '@kit.DeviceCertificateKit'; 4764 4765function Uint8ArrayToString(dataArray: Uint8Array) { 4766 let dataString = ''; 4767 for (let i = 0; i < dataArray.length; i++) { 4768 dataString += String.fromCharCode(dataArray[i]); 4769 } 4770 return dataString; 4771} 4772 4773function ParseX509CertInfo(x509CertArray: Array<cert.X509Cert>) { 4774 let res: string = 'getCertificate success: len = ' + x509CertArray.length; 4775 for (let i = 0; i < x509CertArray.length; i++) { 4776 res += ', index = ' + i + ', issuer name = ' 4777 + Uint8ArrayToString(x509CertArray[i].getIssuerName().data) + ', subject name = ' 4778 + Uint8ArrayToString(x509CertArray[i].getSubjectName().data) + ', valid start = ' 4779 + x509CertArray[i].getNotBeforeTime() 4780 + ', valid end = ' + x509CertArray[i].getNotAfterTime(); 4781 } 4782 return res; 4783} 4784 4785@Entry 4786@Component 4787struct Index { 4788 // outputStr displays debug information on the UI. 4789 @State outputStr: string = ''; 4790 webviewCtl: webview.WebviewController = new webview.WebviewController(); 4791 4792 build() { 4793 Row() { 4794 Column() { 4795 List({ space: 20, initialIndex: 0 }) { 4796 ListItem() { 4797 Button() { 4798 Text('load bad ssl') 4799 .fontSize(10) 4800 .fontWeight(FontWeight.Bold) 4801 } 4802 .type(ButtonType.Capsule) 4803 .onClick(() => { 4804 // Load an expired certificate website and view the obtained certificate information. 4805 this.webviewCtl.loadUrl('https://expired.badssl.com'); 4806 }) 4807 .height(50) 4808 } 4809 4810 ListItem() { 4811 Button() { 4812 Text('load example') 4813 .fontSize(10) 4814 .fontWeight(FontWeight.Bold) 4815 } 4816 .type(ButtonType.Capsule) 4817 .onClick(() => { 4818 // Load an HTTPS website and view the certificate information of the website. 4819 this.webviewCtl.loadUrl('https://www.example.com'); 4820 }) 4821 .height(50) 4822 } 4823 4824 ListItem() { 4825 Button() { 4826 Text('getCertificate Promise') 4827 .fontSize(10) 4828 .fontWeight(FontWeight.Bold) 4829 } 4830 .type(ButtonType.Capsule) 4831 .onClick(() => { 4832 try { 4833 this.webviewCtl.getCertificate().then((x509CertArray: Array<cert.X509Cert>) => { 4834 this.outputStr = ParseX509CertInfo(x509CertArray); 4835 }) 4836 } catch (error) { 4837 this.outputStr = 'getCertificate failed: ' + (error as BusinessError).code + ", errMsg: " + (error as BusinessError).message; 4838 } 4839 }) 4840 .height(50) 4841 } 4842 4843 ListItem() { 4844 Button() { 4845 Text('getCertificate AsyncCallback') 4846 .fontSize(10) 4847 .fontWeight(FontWeight.Bold) 4848 } 4849 .type(ButtonType.Capsule) 4850 .onClick(() => { 4851 try { 4852 this.webviewCtl.getCertificate((error: BusinessError, x509CertArray: Array<cert.X509Cert>) => { 4853 if (error) { 4854 this.outputStr = 'getCertificate failed: ' + error.code + ", errMsg: " + error.message; 4855 } else { 4856 this.outputStr = ParseX509CertInfo(x509CertArray); 4857 } 4858 }) 4859 } catch (error) { 4860 this.outputStr = 'getCertificate failed: ' + (error as BusinessError).code + ", errMsg: " + (error as BusinessError).message; 4861 } 4862 }) 4863 .height(50) 4864 } 4865 } 4866 .listDirection(Axis.Horizontal) 4867 .height('10%') 4868 4869 Text(this.outputStr) 4870 .width('100%') 4871 .fontSize(10) 4872 4873 Web({ src: 'https://www.example.com', controller: this.webviewCtl }) 4874 .fileAccess(true) 4875 .javaScriptAccess(true) 4876 .domStorageAccess(true) 4877 .onlineImageAccess(true) 4878 .onPageEnd((e) => { 4879 if (e) { 4880 this.outputStr = 'onPageEnd : url = ' + e.url; 4881 } 4882 }) 4883 .onSslErrorEventReceive((e) => { 4884 // Ignore SSL certificate errors to test websites whose certificates have expired, for example, https://expired.badssl.com. 4885 e.handler.handleConfirm(); 4886 }) 4887 .width('100%') 4888 .height('70%') 4889 } 4890 .height('100%') 4891 } 4892 } 4893} 4894``` 4895 4896### getCertificate<sup>10+</sup> 4897 4898getCertificate(callback: AsyncCallback<Array<cert.X509Cert>>): void 4899 4900Obtains 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. 4901 4902**System capability**: SystemCapability.Web.Webview.Core 4903 4904**Parameters** 4905 4906| Name | Type | Mandatory| Description | 4907| -------- | ---------------------------- | ---- | ---------------------------------------- | 4908| callback | AsyncCallback<Array<cert.X509Cert>> | Yes | Callback used to obtain the X.509 certificate array of the current website.| 4909 4910**Error codes** 4911 4912For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4913 4914| ID| Error Message | 4915| -------- | ------------------------------------------------------------ | 4916| 17100001 | Init error. The WebviewController must be associated with a web component. | 4917| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 4918 4919**Example** 4920 4921```ts 4922// xxx.ets 4923import { webview } from '@kit.ArkWeb'; 4924import { BusinessError } from '@kit.BasicServicesKit'; 4925import { cert } from '@kit.DeviceCertificateKit'; 4926 4927function Uint8ArrayToString(dataArray: Uint8Array) { 4928 let dataString = ''; 4929 for (let i = 0; i < dataArray.length; i++) { 4930 dataString += String.fromCharCode(dataArray[i]); 4931 } 4932 return dataString; 4933} 4934 4935function ParseX509CertInfo(x509CertArray: Array<cert.X509Cert>) { 4936 let res: string = 'getCertificate success: len = ' + x509CertArray.length; 4937 for (let i = 0; i < x509CertArray.length; i++) { 4938 res += ', index = ' + i + ', issuer name = ' 4939 + Uint8ArrayToString(x509CertArray[i].getIssuerName().data) + ', subject name = ' 4940 + Uint8ArrayToString(x509CertArray[i].getSubjectName().data) + ', valid start = ' 4941 + x509CertArray[i].getNotBeforeTime() 4942 + ', valid end = ' + x509CertArray[i].getNotAfterTime(); 4943 } 4944 return res; 4945} 4946 4947@Entry 4948@Component 4949struct Index { 4950 // outputStr displays debug information on the UI. 4951 @State outputStr: string = ''; 4952 webviewCtl: webview.WebviewController = new webview.WebviewController(); 4953 4954 build() { 4955 Row() { 4956 Column() { 4957 List({ space: 20, initialIndex: 0 }) { 4958 ListItem() { 4959 Button() { 4960 Text('load bad ssl') 4961 .fontSize(10) 4962 .fontWeight(FontWeight.Bold) 4963 } 4964 .type(ButtonType.Capsule) 4965 .onClick(() => { 4966 // Load an expired certificate website and view the obtained certificate information. 4967 this.webviewCtl.loadUrl('https://expired.badssl.com'); 4968 }) 4969 .height(50) 4970 } 4971 4972 ListItem() { 4973 Button() { 4974 Text('load example') 4975 .fontSize(10) 4976 .fontWeight(FontWeight.Bold) 4977 } 4978 .type(ButtonType.Capsule) 4979 .onClick(() => { 4980 // Load an HTTPS website and view the certificate information of the website. 4981 this.webviewCtl.loadUrl('https://www.example.com'); 4982 }) 4983 .height(50) 4984 } 4985 4986 ListItem() { 4987 Button() { 4988 Text('getCertificate Promise') 4989 .fontSize(10) 4990 .fontWeight(FontWeight.Bold) 4991 } 4992 .type(ButtonType.Capsule) 4993 .onClick(() => { 4994 try { 4995 this.webviewCtl.getCertificate().then((x509CertArray: Array<cert.X509Cert>) => { 4996 this.outputStr = ParseX509CertInfo(x509CertArray); 4997 }) 4998 } catch (error) { 4999 this.outputStr = 'getCertificate failed: ' + (error as BusinessError).code + ", errMsg: " + (error as BusinessError).message; 5000 } 5001 }) 5002 .height(50) 5003 } 5004 5005 ListItem() { 5006 Button() { 5007 Text('getCertificate AsyncCallback') 5008 .fontSize(10) 5009 .fontWeight(FontWeight.Bold) 5010 } 5011 .type(ButtonType.Capsule) 5012 .onClick(() => { 5013 try { 5014 this.webviewCtl.getCertificate((error: BusinessError, x509CertArray: Array<cert.X509Cert>) => { 5015 if (error) { 5016 this.outputStr = 'getCertificate failed: ' + error.code + ", errMsg: " + error.message; 5017 } else { 5018 this.outputStr = ParseX509CertInfo(x509CertArray); 5019 } 5020 }) 5021 } catch (error) { 5022 this.outputStr = 'getCertificate failed: ' + (error as BusinessError).code + ", errMsg: " + (error as BusinessError).message; 5023 } 5024 }) 5025 .height(50) 5026 } 5027 } 5028 .listDirection(Axis.Horizontal) 5029 .height('10%') 5030 5031 Text(this.outputStr) 5032 .width('100%') 5033 .fontSize(10) 5034 5035 Web({ src: 'https://www.example.com', controller: this.webviewCtl }) 5036 .fileAccess(true) 5037 .javaScriptAccess(true) 5038 .domStorageAccess(true) 5039 .onlineImageAccess(true) 5040 .onPageEnd((e) => { 5041 if (e) { 5042 this.outputStr = 'onPageEnd : url = ' + e.url; 5043 } 5044 }) 5045 .onSslErrorEventReceive((e) => { 5046 // Ignore SSL certificate errors to test websites whose certificates have expired, for example, https://expired.badssl.com. 5047 e.handler.handleConfirm(); 5048 }) 5049 .width('100%') 5050 .height('70%') 5051 } 5052 .height('100%') 5053 } 5054 } 5055} 5056``` 5057 5058### setAudioMuted<sup>10+</sup> 5059 5060setAudioMuted(mute: boolean): void 5061 5062Mutes this web page. 5063 5064**System capability**: SystemCapability.Web.Webview.Core 5065 5066**Parameters** 5067 5068| Name | Type | Mandatory| Description | 5069| -------- | ------- | ---- | -------------------------------------- | 5070| mute | boolean | Yes | Whether to mute the web page. The value **true** means to mute the web page, and **false** means the opposite.| 5071 5072**Error codes** 5073 5074For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5075 5076| ID| Error Message | 5077| -------- | ------------------------------------------------------------ | 5078| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5079| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5080 5081**Example** 5082 5083```ts 5084// xxx.ets 5085import { webview } from '@kit.ArkWeb'; 5086 5087@Entry 5088@Component 5089struct WebComponent { 5090 controller: webview.WebviewController = new webview.WebviewController(); 5091 @State muted: boolean = false; 5092 5093 build() { 5094 Column() { 5095 Button("Toggle Mute") 5096 .onClick(event => { 5097 if (event) { 5098 this.muted = !this.muted; 5099 this.controller.setAudioMuted(this.muted); 5100 } 5101 }) 5102 Web({ src: 'www.example.com', controller: this.controller }) 5103 } 5104 } 5105} 5106``` 5107 5108### prefetchPage<sup>10+</sup> 5109 5110prefetchPage(url: string, additionalHeaders?: Array\<WebHeader>): void 5111 5112Prefetches 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. 5113 5114> **NOTE** 5115> 5116> The downloaded page resources are cached for about 5 minutes. After this period, the **Web** component automatically releases the resources. 5117 5118**System capability**: SystemCapability.Web.Webview.Core 5119 5120**Parameters** 5121 5122| Name | Type | Mandatory | Description | 5123| ------------------| --------------------------------| ---- | ------------- | 5124| url | string | Yes | URL to be preloaded.| 5125| additionalHeaders | Array\<[WebHeader](#webheader)> | No | Additional HTTP headers of the URL.| 5126 5127**Error codes** 5128 5129For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5130 5131| ID | Error Message | 5132| -------- | ------------------------------------------------------------ | 5133| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5134| 17100002 | Invalid url. | 5135 5136**Example** 5137 5138```ts 5139// xxx.ets 5140import { webview } from '@kit.ArkWeb'; 5141import { BusinessError } from '@kit.BasicServicesKit'; 5142 5143@Entry 5144@Component 5145struct WebComponent { 5146 controller: webview.WebviewController = new webview.WebviewController(); 5147 5148 build() { 5149 Column() { 5150 Button('prefetchPopularPage') 5151 .onClick(() => { 5152 try { 5153 // Replace 'https://www.example.com' with a real URL for the API to work. 5154 this.controller.prefetchPage('https://www.example.com'); 5155 } catch (error) { 5156 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5157 } 5158 }) 5159 // Replace ''www.example1.com' with a real URL for the API to work. 5160 Web({ src: 'www.example1.com', controller: this.controller }) 5161 } 5162 } 5163} 5164``` 5165 5166### prefetchResource<sup>12+</sup> 5167 5168static prefetchResource(request: RequestInfo, additionalHeaders?: Array\<WebHeader>, cacheKey?: string, cacheValidTime?: number): void 5169 5170Prefetches 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. 5171 5172**System capability**: SystemCapability.Web.Webview.Core 5173 5174**Parameters** 5175 5176| Name | Type | Mandatory | Description | 5177| ------------------| ------------------------------- | ---- | ------------------------------------------------------------------ | 5178| request | [RequestInfo](#requestinfo12) | Yes | Information about the prefetched request. | 5179| additionalHeaders | Array\<[WebHeader](#webheader)> | No | Additional HTTP request header of the prefetched request. | 5180| 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.| 5181| cacheValidTime | number | No | Validity period for caching prefetched resources. Value range: (0, 2147483647] Unit: second. Default value: **300s** | 5182 5183**Error codes** 5184 5185For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5186 5187| ID | Error Message | 5188| -------- | ------------------------------------------------------------ | 5189| 401 | Invalid input parameter.Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | 5190| 17100002 | Invalid url. | 5191 5192**Example** 5193 5194```ts 5195// xxx.ets 5196import { webview } from '@kit.ArkWeb'; 5197import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 5198 5199export default class EntryAbility extends UIAbility { 5200 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 5201 console.log("EntryAbility onCreate"); 5202 webview.WebviewController.initializeWebEngine(); 5203 // Replace "https://www.example1.com/post?e=f&g=h" with the actual website address to visit. 5204 webview.WebviewController.prefetchResource( 5205 { 5206 url: "https://www.example1.com/post?e=f&g=h", 5207 method: "POST", 5208 formData: "a=x&b=y", 5209 }, 5210 [{ 5211 headerKey: "c", 5212 headerValue: "z", 5213 },], 5214 "KeyX", 500); 5215 AppStorage.setOrCreate("abilityWant", want); 5216 console.log("EntryAbility onCreate done"); 5217 } 5218} 5219``` 5220 5221### clearPrefetchedResource<sup>12+</sup> 5222 5223static clearPrefetchedResource(cacheKeyList: Array\<string>): void 5224 5225Clears 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). 5226 5227**System capability**: SystemCapability.Web.Webview.Core 5228 5229**Parameters** 5230 5231| Name | Type | Mandatory | Description | 5232| ------------------| ----------- | ---- | ------------------------------------------------------------------------- | 5233| 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.| 5234 5235**Example** 5236 5237```ts 5238// xxx.ets 5239import { webview } from '@kit.ArkWeb'; 5240 5241@Entry 5242@Component 5243struct WebComponent { 5244 controller: webview.WebviewController = new webview.WebviewController(); 5245 5246 build() { 5247 Column() { 5248 Web({ src: "https://www.example.com/", controller: this.controller }) 5249 .onAppear(() => { 5250 // Replace "https://www.example1.com/post?e=f&g=h" with the actual website address to visit. 5251 webview.WebviewController.prefetchResource( 5252 { 5253 url: "https://www.example1.com/post?e=f&g=h", 5254 method: "POST", 5255 formData: "a=x&b=y", 5256 }, 5257 [{ 5258 headerKey: "c", 5259 headerValue: "z", 5260 },], 5261 "KeyX", 500); 5262 }) 5263 .onPageEnd(() => { 5264 // Clear the prefetch cache that is no longer used. 5265 webview.WebviewController.clearPrefetchedResource(["KeyX",]); 5266 }) 5267 } 5268 } 5269} 5270``` 5271 5272### prepareForPageLoad<sup>10+</sup> 5273 5274static prepareForPageLoad(url: string, preconnectable: boolean, numSockets: number): void 5275 5276Preconnects 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. 5277 5278**System capability**: SystemCapability.Web.Webview.Core 5279 5280**Parameters** 5281 5282| Name | Type | Mandatory | Description | 5283| ---------------| ------- | ---- | ------------- | 5284| url | string | Yes | URL to be preconnected.| 5285| 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.| 5286| numSockets | number | Yes | Number of sockets to be preconnected. The value must be greater than 0. A maximum of six socket connections are allowed.| 5287 5288**Error codes** 5289 5290For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5291 5292| ID | Error Message | 5293| -------- | ------------------------------------------------------------ | 5294| 17100002 | Invalid url. | 5295| 171000013| The number of preconnect sockets is invalid. | 5296 5297**Example** 5298 5299```ts 5300// xxx.ets 5301import { webview } from '@kit.ArkWeb'; 5302import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 5303 5304export default class EntryAbility extends UIAbility { 5305 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 5306 console.log("EntryAbility onCreate"); 5307 webview.WebviewController.initializeWebEngine(); 5308 // Replace 'https://www.example.com' with a real URL for the API to work. 5309 webview.WebviewController.prepareForPageLoad("https://www.example.com", true, 2); 5310 AppStorage.setOrCreate("abilityWant", want); 5311 console.log("EntryAbility onCreate done"); 5312 } 5313} 5314``` 5315 5316### setCustomUserAgent<sup>10+</sup> 5317 5318setCustomUserAgent(userAgent: string): void 5319 5320Sets a custom user agent, which will overwrite the default user agent. 5321 5322When a URL is set for the **Web** component **src**, you are advised to set UserAgent in the onControllerAttached callback event. For details, see the example. You are not advised to set **UserAgent** in the **onLoadIntercept** callback event. Otherwise, the setting may fail occasionally. 5323 5324When **src** of the **Web** component is set to an empty string, you are advised to call the **setCustomUserAgent** method to set **UserAgent** and then use **loadUrl** to load a specific page. 5325 5326For details about the default **UserAgent**, see [Default User Agent String](../../web/web-default-userAgent.md). 5327 5328> **NOTE** 5329> 5330>If a URL is set for the **Web** component **src**, and **UserAgent** is not set in the **onControllerAttached** callback event, calling **setCustomUserAgent** again may result in the loaded page being inconsistent with the actual user agent. 5331 5332**System capability**: SystemCapability.Web.Webview.Core 5333 5334**Parameters** 5335 5336| Name | Type | Mandatory | Description | 5337| ---------------| ------- | ---- | ------------- | 5338| 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.| 5339 5340**Error codes** 5341 5342For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5343 5344| ID | Error Message | 5345| -------- | ------------------------------------------------------------ | 5346| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5347| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5348 5349**Example** 5350 5351```ts 5352// xxx.ets 5353import { webview } from '@kit.ArkWeb'; 5354import { BusinessError } from '@kit.BasicServicesKit'; 5355 5356@Entry 5357@Component 5358struct WebComponent { 5359 controller: webview.WebviewController = new webview.WebviewController(); 5360 @State customUserAgent: string = ' DemoApp'; 5361 5362 build() { 5363 Column() { 5364 Web({ src: 'www.example.com', controller: this.controller }) 5365 .onControllerAttached(() => { 5366 console.log("onControllerAttached"); 5367 try { 5368 let userAgent = this.controller.getUserAgent() + this.customUserAgent; 5369 this.controller.setCustomUserAgent(userAgent); 5370 } catch (error) { 5371 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5372 } 5373 }) 5374 } 5375 } 5376} 5377``` 5378 5379### setDownloadDelegate<sup>11+</sup> 5380 5381setDownloadDelegate(delegate: WebDownloadDelegate): void 5382 5383Sets a **WebDownloadDelegate** object to receive downloads and download progress triggered from a page. 5384 5385**System capability**: SystemCapability.Web.Webview.Core 5386 5387**Parameters** 5388 5389| Name | Type | Mandatory | Description | 5390| ---------------| ------- | ---- | ------------- | 5391| delegate | [WebDownloadDelegate](#webdownloaddelegate11) | Yes | Delegate used to receive the download progress.| 5392 5393**Error codes** 5394 5395For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5396 5397| ID | Error Message | 5398| -------- | ------------------------------------------------------------ | 5399| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5400 5401**Example** 5402 5403```ts 5404// xxx.ets 5405import { webview } from '@kit.ArkWeb'; 5406import { BusinessError } from '@kit.BasicServicesKit'; 5407 5408@Entry 5409@Component 5410struct WebComponent { 5411 controller: webview.WebviewController = new webview.WebviewController(); 5412 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 5413 5414 build() { 5415 Column() { 5416 Button('setDownloadDelegate') 5417 .onClick(() => { 5418 try { 5419 this.controller.setDownloadDelegate(this.delegate); 5420 } catch (error) { 5421 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5422 } 5423 }) 5424 Web({ src: 'www.example.com', controller: this.controller }) 5425 } 5426 } 5427} 5428``` 5429 5430### startDownload<sup>11+</sup> 5431 5432startDownload(url: string): void 5433 5434Downloads a file, such as an image, from the specified URL. 5435 5436**System capability**: SystemCapability.Web.Webview.Core 5437 5438**Parameters** 5439 5440| Name | Type | Mandatory | Description | 5441| ---------------| ------- | ---- | ------------- | 5442| url | string | Yes | Download URL.| 5443 5444**Error codes** 5445 5446For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5447 5448| ID | Error Message | 5449| -------- | ------------------------------------------------------------ | 5450| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5451| 17100002 | Invalid url. | 5452 5453**Example** 5454 5455```ts 5456// xxx.ets 5457import { webview } from '@kit.ArkWeb'; 5458import { BusinessError } from '@kit.BasicServicesKit'; 5459 5460@Entry 5461@Component 5462struct WebComponent { 5463 controller: webview.WebviewController = new webview.WebviewController(); 5464 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 5465 5466 build() { 5467 Column() { 5468 Button('setDownloadDelegate') 5469 .onClick(() => { 5470 try { 5471 this.controller.setDownloadDelegate(this.delegate); 5472 } catch (error) { 5473 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5474 } 5475 }) 5476 Button('startDownload') 5477 .onClick(() => { 5478 try { 5479 this.controller.startDownload('https://www.example.com'); 5480 } catch (error) { 5481 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5482 } 5483 }) 5484 Web({ src: 'www.example.com', controller: this.controller }) 5485 } 5486 } 5487} 5488``` 5489 5490### getCustomUserAgent<sup>10+</sup> 5491 5492getCustomUserAgent(): string 5493 5494Obtains a custom user agent. 5495 5496For details about the default **UserAgent**, see [Default User Agent String](../../web/web-default-userAgent.md). 5497 5498**System capability**: SystemCapability.Web.Webview.Core 5499 5500**Return value** 5501 5502| Type | Description | 5503| ------ | ------------------------- | 5504| string | Information about the custom user agent.| 5505 5506**Error codes** 5507 5508For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5509 5510| ID | Error Message | 5511| -------- | ------------------------------------------------------------ | 5512| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5513 5514**Example** 5515 5516```ts 5517// xxx.ets 5518import { webview } from '@kit.ArkWeb'; 5519import { BusinessError } from '@kit.BasicServicesKit'; 5520 5521@Entry 5522@Component 5523struct WebComponent { 5524 controller: webview.WebviewController = new webview.WebviewController(); 5525 @State userAgent: string = ''; 5526 5527 build() { 5528 Column() { 5529 Button('getCustomUserAgent') 5530 .onClick(() => { 5531 try { 5532 this.userAgent = this.controller.getCustomUserAgent(); 5533 console.log("userAgent: " + this.userAgent); 5534 } catch (error) { 5535 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5536 } 5537 }) 5538 Web({ src: 'www.example.com', controller: this.controller }) 5539 } 5540 } 5541} 5542``` 5543 5544### setConnectionTimeout<sup>11+</sup> 5545 5546static setConnectionTimeout(timeout: number): void 5547 5548Sets the network connection timeout. You can use the **onErrorReceive** method in the **Web** component to obtain the timeout error code. 5549 5550**System capability**: SystemCapability.Web.Webview.Core 5551 5552**Parameters** 5553 5554| Name | Type | Mandatory | Description | 5555| ---------------| ------- | ---- | ------------- | 5556| timeout | number | Yes | Socket connection timeout interval, in seconds. The value of socket must be an integer greater than 0.| 5557 5558**Error codes** 5559 5560For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5561 5562| ID| Error Message | 5563| -------- | ------------------------------------------------------------ | 5564| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 5565 5566**Example** 5567 5568```ts 5569// xxx.ets 5570import { webview } from '@kit.ArkWeb'; 5571import { BusinessError } from '@kit.BasicServicesKit'; 5572 5573@Entry 5574@Component 5575struct WebComponent { 5576 controller: webview.WebviewController = new webview.WebviewController(); 5577 5578 build() { 5579 Column() { 5580 Button('setConnectionTimeout') 5581 .onClick(() => { 5582 try { 5583 webview.WebviewController.setConnectionTimeout(5); 5584 console.log("setConnectionTimeout: 5s"); 5585 } catch (error) { 5586 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5587 } 5588 }) 5589 Web({ src: 'www.example.com', controller: this.controller }) 5590 .onErrorReceive((event) => { 5591 if (event) { 5592 console.log('getErrorInfo:' + event.error.getErrorInfo()); 5593 console.log('getErrorCode:' + event.error.getErrorCode()); 5594 } 5595 }) 5596 } 5597 } 5598} 5599``` 5600 5601### warmupServiceWorker<sup>12+</sup> 5602 5603static warmupServiceWorker(url: string): void 5604 5605Warms 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. 5606 5607**System capability**: SystemCapability.Web.Webview.Core 5608 5609**Parameters** 5610 5611| Name | Type | Mandatory | Description | 5612| ---------------| ------- | ---- | ------------- | 5613| url | string | Yes | URL of the ServiceWorker to warm up.| 5614 5615**Error codes** 5616 5617For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5618 5619| ID | Error Message | 5620| -------- | ------------------------------------------------------------ | 5621| 17100002 | Invalid url. | 5622 5623**Example** 5624 5625```ts 5626// xxx.ts 5627import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 5628import { hilog } from '@kit.PerformanceAnalysisKit'; 5629import { window } from '@kit.ArkUI'; 5630import { webview } from '@kit.ArkWeb'; 5631 5632export default class EntryAbility extends UIAbility { 5633 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 5634 console.log("EntryAbility onCreate"); 5635 webview.WebviewController.initializeWebEngine(); 5636 webview.WebviewController.warmupServiceWorker("https://www.example.com"); 5637 AppStorage.setOrCreate("abilityWant", want); 5638 } 5639} 5640``` 5641 5642### enableSafeBrowsing<sup>11+</sup> 5643 5644enableSafeBrowsing(enable: boolean): void 5645 5646<!--RP1-->Enables the safe browsing feature. This feature is forcibly enabled and cannot be disabled for identified untrusted websites. 5647By 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. 5648<!--RP1End--> 5649 5650**System capability**: SystemCapability.Web.Webview.Core 5651 5652**Parameters** 5653 5654| Name | Type | Mandatory | Description | 5655| --------| ------- | ---- | ---------------------------| 5656| enable | boolean | Yes | Whether to enable the safe browsing feature.| 5657 5658**Error codes** 5659 5660For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5661 5662| ID| Error Message | 5663| -------- | ----------------------- | 5664| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5665 5666**Example** 5667 5668```ts 5669// xxx.ets 5670import { webview } from '@kit.ArkWeb'; 5671import { BusinessError } from '@kit.BasicServicesKit'; 5672 5673@Entry 5674@Component 5675struct WebComponent { 5676 controller: webview.WebviewController = new webview.WebviewController(); 5677 5678 build() { 5679 Column() { 5680 Button('enableSafeBrowsing') 5681 .onClick(() => { 5682 try { 5683 this.controller.enableSafeBrowsing(true); 5684 console.log("enableSafeBrowsing: true"); 5685 } catch (error) { 5686 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5687 } 5688 }) 5689 Web({ src: 'www.example.com', controller: this.controller }) 5690 } 5691 } 5692} 5693``` 5694 5695### isSafeBrowsingEnabled<sup>11+</sup> 5696 5697isSafeBrowsingEnabled(): boolean 5698 5699Checks whether the safe browsing feature is enabled for this web page. 5700 5701**System capability**: SystemCapability.Web.Webview.Core 5702 5703**Return value** 5704 5705| Type | Description | 5706| ------- | --------------------------------------- | 5707| boolean | Whether the safe browsing feature is enabled. The default value is **false**.| 5708 5709**Example** 5710 5711```ts 5712// xxx.ets 5713import { webview } from '@kit.ArkWeb'; 5714 5715@Entry 5716@Component 5717struct WebComponent { 5718 controller: webview.WebviewController = new webview.WebviewController(); 5719 5720 build() { 5721 Column() { 5722 Button('isSafeBrowsingEnabled') 5723 .onClick(() => { 5724 let result = this.controller.isSafeBrowsingEnabled(); 5725 console.log("result: " + result); 5726 }) 5727 Web({ src: 'www.example.com', controller: this.controller }) 5728 } 5729 } 5730} 5731``` 5732 5733### enableIntelligentTrackingPrevention<sup>12+</sup> 5734 5735enableIntelligentTrackingPrevention(enable: boolean): void 5736 5737Enables intelligent tracking prevention. By default, this feature is disabled. 5738 5739**System capability**: SystemCapability.Web.Webview.Core 5740 5741**Parameters** 5742 5743| Name | Type | Mandatory | Description | 5744| --------| ------- | ---- | ---------------------------| 5745| enable | boolean | Yes | Whether to enable intelligent tracking prevention.| 5746 5747**Error codes** 5748 5749For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5750 5751| ID| Error Message | 5752| -------- | ----------------------- | 5753| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5754| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5755 5756**Example** 5757 5758```ts 5759// xxx.ets 5760import { webview } from '@kit.ArkWeb'; 5761import { BusinessError } from '@kit.BasicServicesKit'; 5762 5763@Entry 5764@Component 5765struct WebComponent { 5766 controller: webview.WebviewController = new webview.WebviewController(); 5767 5768 build() { 5769 Column() { 5770 Button('enableIntelligentTrackingPrevention') 5771 .onClick(() => { 5772 try { 5773 this.controller.enableIntelligentTrackingPrevention(true); 5774 console.log("enableIntelligentTrackingPrevention: true"); 5775 } catch (error) { 5776 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5777 } 5778 }) 5779 Web({ src: 'www.example.com', controller: this.controller }) 5780 } 5781 } 5782} 5783``` 5784 5785### isIntelligentTrackingPreventionEnabled<sup>12+</sup> 5786 5787isIntelligentTrackingPreventionEnabled(): boolean 5788 5789Obtains whether intelligent tracking prevention is enabled on this web page. 5790 5791**System capability**: SystemCapability.Web.Webview.Core 5792 5793**Return value** 5794 5795| Type | Description | 5796| ------- | --------------------------------------- | 5797| boolean | Whether intelligent tracking prevention is enabled on the current web page. The default value is **false**.| 5798 5799**Error codes** 5800 5801For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5802 5803| ID| Error Message | 5804| -------- | ----------------------- | 5805| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5806 5807**Example** 5808 5809```ts 5810// xxx.ets 5811import { webview } from '@kit.ArkWeb'; 5812import { BusinessError } from '@kit.BasicServicesKit'; 5813 5814@Entry 5815@Component 5816struct WebComponent { 5817 controller: webview.WebviewController = new webview.WebviewController(); 5818 5819 build() { 5820 Column() { 5821 Button('isIntelligentTrackingPreventionEnabled') 5822 .onClick(() => { 5823 try { 5824 let result = this.controller.isIntelligentTrackingPreventionEnabled(); 5825 console.log("result: " + result); 5826 } catch (error) { 5827 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5828 } 5829 }) 5830 Web({ src: 'www.example.com', controller: this.controller }) 5831 } 5832 } 5833} 5834``` 5835 5836### addIntelligentTrackingPreventionBypassingList<sup>12+</sup> 5837 5838static addIntelligentTrackingPreventionBypassingList(hostList: Array\<string>): void 5839 5840Adds a list of domain names that bypass intelligent tracking prevention. 5841 5842**System capability**: SystemCapability.Web.Webview.Core 5843 5844**Parameters** 5845 5846| Name | Type | Mandatory | Description | 5847| ----------- | ------------- | ---- | ------------------------ | 5848| hostList | Array\<string> | Yes | List of domain names that bypass intelligent tracking prevention.| 5849 5850**Error codes** 5851 5852For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5853 5854| ID | Error Message | 5855| -------- | ------------------------ | 5856| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5857 5858**Example** 5859 5860```ts 5861// xxx.ets 5862import { webview } from '@kit.ArkWeb'; 5863import { BusinessError } from '@kit.BasicServicesKit'; 5864 5865@Entry 5866@Component 5867struct WebComponent { 5868 controller: webview.WebviewController = new webview.WebviewController(); 5869 5870 build() { 5871 Column() { 5872 Button('addIntelligentTrackingPreventionBypassingList') 5873 .onClick(() => { 5874 try { 5875 let hostList = ["www.test1.com", "www.test2.com", "www.test3.com"]; 5876 webview.WebviewController.addIntelligentTrackingPreventionBypassingList(hostList); 5877 } catch (error) { 5878 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5879 } 5880 }) 5881 Web({ src: 'www.example.com', controller: this.controller }) 5882 } 5883 } 5884} 5885``` 5886 5887### removeIntelligentTrackingPreventionBypassingList<sup>12+</sup> 5888 5889static removeIntelligentTrackingPreventionBypassingList(hostList: Array\<string>): void 5890 5891Deletes the domain names from the list of domain names added through the **addIntelligentTrackingPreventionBypassingList** API. 5892 5893**System capability**: SystemCapability.Web.Webview.Core 5894 5895**Parameters** 5896 5897| Name | Type | Mandatory | Description | 5898| ----------- | ------------- | ---- | ------------------------ | 5899| hostList | Array\<string> | Yes | List of domain names that bypass intelligent tracking prevention.| 5900 5901**Error codes** 5902 5903For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5904 5905| ID | Error Message | 5906| -------- | ------------------------ | 5907| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5908 5909**Example** 5910 5911```ts 5912// xxx.ets 5913import { webview } from '@kit.ArkWeb'; 5914import { BusinessError } from '@kit.BasicServicesKit'; 5915 5916@Entry 5917@Component 5918struct WebComponent { 5919 controller: webview.WebviewController = new webview.WebviewController(); 5920 5921 build() { 5922 Column() { 5923 Button('removeIntelligentTrackingPreventionBypassingList') 5924 .onClick(() => { 5925 try { 5926 let hostList = ["www.test1.com", "www.test2.com"]; 5927 webview.WebviewController.removeIntelligentTrackingPreventionBypassingList(hostList); 5928 } catch (error) { 5929 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5930 } 5931 }) 5932 Web({ src: 'www.example.com', controller: this.controller }) 5933 } 5934 } 5935} 5936``` 5937 5938### clearIntelligentTrackingPreventionBypassingList<sup>12+</sup> 5939 5940static clearIntelligentTrackingPreventionBypassingList(): void 5941 5942Deletes all domain names from the list of domain names added through the **addIntelligentTrackingPreventionBypassingList** API. 5943 5944**System capability**: SystemCapability.Web.Webview.Core 5945 5946**Example** 5947 5948```ts 5949// xxx.ets 5950import { webview } from '@kit.ArkWeb'; 5951 5952@Entry 5953@Component 5954struct WebComponent { 5955 controller: webview.WebviewController = new webview.WebviewController(); 5956 5957 build() { 5958 Column() { 5959 Button('clearIntelligentTrackingPreventionBypassingList') 5960 .onClick(() => { 5961 webview.WebviewController.clearIntelligentTrackingPreventionBypassingList(); 5962 }) 5963 Web({ src: 'www.example.com', controller: this.controller }) 5964 } 5965 } 5966} 5967``` 5968 5969### getDefaultUserAgent<sup>14+</sup> 5970 5971static getDefaultUserAgent(): string 5972 5973Obtains the default user agent. 5974 5975This API can be called only in the UI thread. 5976 5977**System capability**: SystemCapability.Web.Webview.Core 5978 5979**Example** 5980 5981```ts 5982// xxx.ets 5983import { webview } from '@kit.ArkWeb'; 5984import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 5985 5986export default class EntryAbility extends UIAbility { 5987 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 5988 console.log("EntryAbility onCreate"); 5989 webview.WebviewController.initializeWebEngine(); 5990 let defaultUserAgent = webview.WebviewController.getDefaultUserAgent(); 5991 console.log("defaultUserAgent: " + defaultUserAgent); 5992 } 5993} 5994``` 5995 5996### enableAdsBlock<sup>12+</sup> 5997 5998enableAdsBlock(enable: boolean): void 5999 6000Enables ad blocking. By default, this feature is disabled. 6001 6002**System capability**: SystemCapability.Web.Webview.Core 6003 6004**Parameters** 6005 6006| Name | Type | Mandatory | Description | 6007| --------| ------- | ---- | ---------------------------| 6008| enable | boolean | Yes | Whether to enable ad blocking.| 6009 6010**Error codes** 6011 6012For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6013 6014| ID| Error Message | 6015| -------- | ----------------------- | 6016| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6017| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Parameter string is too long. 3.Parameter verification failed. | 6018 6019**Example** 6020 6021```ts 6022// xxx.ets 6023import { webview } from '@kit.ArkWeb'; 6024import { BusinessError } from '@kit.BasicServicesKit'; 6025 6026@Entry 6027@Component 6028struct WebComponent { 6029 controller: webview.WebviewController = new webview.WebviewController(); 6030 6031 build() { 6032 Column() { 6033 Button('enableAdsBlock') 6034 .onClick(() => { 6035 try { 6036 this.controller.enableAdsBlock(true); 6037 console.log("enableAdsBlock: true") 6038 } catch (error) { 6039 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6040 } 6041 }) 6042 Web({ src: 'www.example.com', controller: this.controller }) 6043 } 6044 } 6045} 6046``` 6047 6048### isAdsBlockEnabled<sup>12+</sup> 6049 6050isAdsBlockEnabled() : boolean 6051 6052Checks whether ad blocking is enabled. By default, this feature is disabled. 6053 6054**System capability**: SystemCapability.Web.Webview.Core 6055 6056**Return value** 6057 6058| Type | Description | 6059| ------------------------------------------------------------ | ---------------------- | 6060| boolean | Returns **true** if ad blocking is enabled; returns **false** otherwise.| 6061 6062**Example** 6063 6064```ts 6065// xxx.ets 6066import { webview } from '@kit.ArkWeb'; 6067import { BusinessError } from '@kit.BasicServicesKit'; 6068 6069@Entry 6070@Component 6071struct WebComponent { 6072 controller: webview.WebviewController = new webview.WebviewController(); 6073 6074 build() { 6075 Column() { 6076 Button('isAdsBlockEnabled') 6077 .onClick(() => { 6078 try { 6079 let isAdsBlockEnabled: boolean = this.controller.isAdsBlockEnabled(); 6080 console.log("isAdsBlockEnabled:", isAdsBlockEnabled); 6081 } catch (error) { 6082 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6083 } 6084 }) 6085 Web({ src: 'www.example.com', controller: this.controller }) 6086 } 6087 } 6088} 6089``` 6090 6091### isAdsBlockEnabledForCurPage<sup>12+</sup> 6092 6093isAdsBlockEnabledForCurPage() : boolean 6094 6095Checks whether ad blocking is enabled on this web page. 6096After 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. 6097 6098**System capability**: SystemCapability.Web.Webview.Core 6099 6100**Return value** 6101 6102| Type | Description | 6103| ------------------------------------------------------------ | ---------------------- | 6104| boolean | Returns **true** if ad blocking is enabled; returns **false** otherwise.| 6105 6106**Example** 6107 6108```ts 6109// xxx.ets 6110import { webview } from '@kit.ArkWeb'; 6111import { BusinessError } from '@kit.BasicServicesKit'; 6112 6113@Entry 6114@Component 6115struct WebComponent { 6116 controller: webview.WebviewController = new webview.WebviewController(); 6117 6118 build() { 6119 Column() { 6120 Button('isAdsBlockEnabledForCurPage') 6121 .onClick(() => { 6122 try { 6123 let isAdsBlockEnabledForCurPage: boolean = this.controller.isAdsBlockEnabledForCurPage(); 6124 console.log("isAdsBlockEnabledForCurPage:", isAdsBlockEnabledForCurPage); 6125 } catch (error) { 6126 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6127 } 6128 }) 6129 Web({ src: 'www.example.com', controller: this.controller }) 6130 } 6131 } 6132} 6133``` 6134 6135### setRenderProcessMode<sup>12+</sup> 6136 6137static setRenderProcessMode(mode: RenderProcessMode): void 6138 6139Sets the ArkWeb render subprocess mode. 6140 6141**System capability**: SystemCapability.Web.Webview.Core 6142 6143**Parameters** 6144 6145| Name | Type | Mandatory | Description | 6146| ----------- | ------------- | ---- | ------------------------ | 6147| 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.| 6148 6149**Error codes** 6150 6151For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6152 6153| ID | Error Message | 6154| -------- | ------------------------ | 6155| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 6156 6157**Example** 6158 6159```ts 6160// xxx.ets 6161import { webview } from '@kit.ArkWeb'; 6162import { BusinessError } from '@kit.BasicServicesKit'; 6163 6164@Entry 6165@Component 6166struct WebComponent { 6167 controller: webview.WebviewController = new webview.WebviewController(); 6168 6169 build() { 6170 Column() { 6171 Button('setRenderProcessMode') 6172 .onClick(() => { 6173 try { 6174 webview.WebviewController.setRenderProcessMode(webview.RenderProcessMode.MULTIPLE); 6175 } catch (error) { 6176 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6177 } 6178 }) 6179 Web({ src: 'www.example.com', controller: this.controller }) 6180 } 6181 } 6182} 6183``` 6184### getRenderProcessMode<sup>12+</sup> 6185 6186static getRenderProcessMode(): RenderProcessMode 6187 6188Obtains the ArkWeb render subprocess mode. 6189 6190**System capability**: SystemCapability.Web.Webview.Core 6191 6192**Return value** 6193 6194| Type | Description | 6195| ----------------------------------------- | ------------------------------------------------------------ | 6196| [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.| 6197 6198 6199**Example** 6200 6201```ts 6202// xxx.ets 6203import { webview } from '@kit.ArkWeb'; 6204 6205@Entry 6206@Component 6207struct WebComponent { 6208 controller: webview.WebviewController = new webview.WebviewController(); 6209 6210 build() { 6211 Column() { 6212 Button('getRenderProcessMode') 6213 .onClick(() => { 6214 let mode = webview.WebviewController.getRenderProcessMode(); 6215 console.log("getRenderProcessMode: " + mode); 6216 }) 6217 Web({ src: 'www.example.com', controller: this.controller }) 6218 } 6219 } 6220} 6221``` 6222 6223### terminateRenderProcess<sup>12+</sup> 6224 6225terminateRenderProcess(): boolean 6226 6227Terminates this render process. 6228 6229Calling 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. 6230 6231**System capability**: SystemCapability.Web.Webview.Core 6232 6233**Return value** 6234 6235| Type | Description | 6236| ------------------------------------------------------------ | ---------------------- | 6237| 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.| 6238 6239**Error codes** 6240 6241For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6242 6243| ID | Error Message | 6244| -------- | ------------------------------------------------------------ | 6245| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6246 6247**Example** 6248 6249```ts 6250// xxx.ets 6251import { webview } from '@kit.ArkWeb'; 6252 6253@Entry 6254@Component 6255struct WebComponent { 6256 controller: webview.WebviewController = new webview.WebviewController(); 6257 6258 build() { 6259 Column() { 6260 Button('terminateRenderProcess') 6261 .onClick(() => { 6262 let result = this.controller.terminateRenderProcess(); 6263 console.log("terminateRenderProcess result: " + result); 6264 }) 6265 Web({ src: 'www.example.com', controller: this.controller }) 6266 } 6267 } 6268} 6269``` 6270 6271### postUrl<sup>11+</sup> 6272 6273postUrl(url: string, postData: ArrayBuffer): void 6274 6275Loads 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. 6276 6277**System capability**: SystemCapability.Web.Webview.Core 6278 6279**Parameters** 6280 6281| Name | Type | Mandatory| Description | 6282| ------- | ---------------- | ---- | :-------------------- | 6283| url | string | Yes | URL to load. | 6284| postData | ArrayBuffer | Yes | Data to transfer using the POST method. The request must be encoded in "application/x-www-form-urlencoded" format.| 6285 6286**Error codes** 6287 6288For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6289 6290| ID| Error Message | 6291| -------- | ------------------------------------------------------------ | 6292| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6293| 17100002 | Invalid url. | 6294| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 6295 6296**Example** 6297 6298```ts 6299// xxx.ets 6300import { webview } from '@kit.ArkWeb'; 6301import { BusinessError } from '@kit.BasicServicesKit'; 6302 6303class TestObj { 6304 constructor() { 6305 } 6306 6307 test(str: string): ArrayBuffer { 6308 let buf = new ArrayBuffer(str.length); 6309 let buff = new Uint8Array(buf); 6310 6311 for (let i = 0; i < str.length; i++) { 6312 buff[i] = str.charCodeAt(i); 6313 } 6314 return buf; 6315 } 6316} 6317 6318@Entry 6319@Component 6320struct WebComponent { 6321 controller: webview.WebviewController = new webview.WebviewController(); 6322 @State testObjtest: TestObj = new TestObj(); 6323 6324 build() { 6325 Column() { 6326 Button('postUrl') 6327 .onClick(() => { 6328 try { 6329 // Convert data to the ArrayBuffer type. 6330 let postData = this.testObjtest.test("Name=test&Password=test"); 6331 this.controller.postUrl('www.example.com', postData); 6332 } catch (error) { 6333 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6334 } 6335 }) 6336 Web({ src: '', controller: this.controller }) 6337 } 6338 } 6339} 6340``` 6341 6342### createWebPrintDocumentAdapter<sup>11+</sup> 6343 6344createWebPrintDocumentAdapter(jobName: string): print.PrintDocumentAdapter 6345 6346Creates a **PrintDocumentAdapter** instance to provide content for printing. 6347 6348**System capability**: SystemCapability.Web.Webview.Core 6349 6350**Parameters** 6351 6352| Name | Type | Mandatory| Description | 6353| ------- | ------ | ---- | :-------------------- | 6354| jobName | string | Yes | Name of the file to print. | 6355 6356**Return value** 6357 6358| Type | Description | 6359| -------------------- | ------------------------- | 6360| print.printDocumentAdapter | **PrintDocumentAdapter** instance created.| 6361 6362**Error codes** 6363 6364For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6365 6366| ID| Error Message | 6367| -------- | -------------------------------------------------------------------------- | 6368| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 6369| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6370 6371**Example** 6372 6373```ts 6374// xxx.ets 6375import { webview } from '@kit.ArkWeb'; 6376import { BusinessError, print } from '@kit.BasicServicesKit'; 6377 6378@Entry 6379@Component 6380struct WebComponent { 6381 controller: webview.WebviewController = new webview.WebviewController(); 6382 6383 build() { 6384 Column() { 6385 Button('createWebPrintDocumentAdapter') 6386 .onClick(() => { 6387 try { 6388 let webPrintDocadapter = this.controller.createWebPrintDocumentAdapter('example.pdf'); 6389 print.print('example_jobid', webPrintDocadapter, null, getContext()); 6390 } catch (error) { 6391 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6392 } 6393 }) 6394 Web({ src: 'www.example.com', controller: this.controller }) 6395 } 6396 } 6397} 6398``` 6399### isIncognitoMode<sup>11+</sup> 6400 6401isIncognitoMode(): boolean 6402 6403Checks whether this Webview is in incognito mode. 6404 6405**System capability**: SystemCapability.Web.Webview.Core 6406 6407**Return value** 6408 6409| Type | Description | 6410| -------------------- | ------------------------- | 6411| boolean | Whether the Webview is in incognito mode.| 6412 6413**Error codes** 6414 6415For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6416 6417| ID| Error Message | 6418| -------- | -------------------------------------------------------------------------- | 6419| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6420 6421**Example** 6422 6423```ts 6424// xxx.ets 6425import { webview } from '@kit.ArkWeb'; 6426import { BusinessError } from '@kit.BasicServicesKit'; 6427 6428@Entry 6429@Component 6430struct WebComponent { 6431 controller: webview.WebviewController = new webview.WebviewController(); 6432 6433 build() { 6434 Column() { 6435 Button('isIncognitoMode') 6436 .onClick(() => { 6437 try { 6438 let result = this.controller.isIncognitoMode(); 6439 console.log('isIncognitoMode' + result); 6440 } catch (error) { 6441 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6442 } 6443 }) 6444 Web({ src: 'www.example.com', controller: this.controller }) 6445 } 6446 } 6447} 6448``` 6449 6450### getSecurityLevel<sup>11+</sup> 6451 6452getSecurityLevel(): SecurityLevel 6453 6454Obtains the security level of this web page. 6455 6456**System capability**: SystemCapability.Web.Webview.Core 6457 6458**Return value** 6459 6460| Type | Description | 6461| ----------------------------------- | --------------------------- | 6462| [SecurityLevel](#securitylevel11) | Security level of the web page. The value can be **NONE**, **SECURE**, **WARNING**, or **DANGEROUS**.| 6463 6464**Error codes** 6465 6466For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6467 6468| ID| Error Message | 6469| -------- | ------------------------------------------------------------ | 6470| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6471 6472**Example** 6473 6474```ts 6475import { webview } from '@kit.ArkWeb'; 6476 6477@Entry 6478@Component 6479struct WebComponent { 6480 controller: webview.WebviewController = new webview.WebviewController(); 6481 6482 build() { 6483 Column() { 6484 Web({ src: 'www.example.com', controller: this.controller }) 6485 .onPageEnd((event) => { 6486 if (event) { 6487 let securityLevel = this.controller.getSecurityLevel(); 6488 console.info('securityLevel: ', securityLevel); 6489 } 6490 }) 6491 } 6492 } 6493} 6494``` 6495 6496### setScrollable<sup>12+</sup> 6497 6498setScrollable(enable: boolean, type?: ScrollType): void 6499 6500Sets whether this web page is scrollable. 6501 6502**System capability**: SystemCapability.Web.Webview.Core 6503 6504**Parameters** 6505 6506| Name| Type| Mandatory| Description | 6507| ------ | -------- | ---- | ---------------------- | 6508| enable | boolean | Yes | Whether the web page is scrollable. The value **true** means the web page is scrollable, and **false** means the opposite.| 6509| 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**.| 6510 6511**Error codes** 6512 6513For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6514 6515| ID| Error Message | 6516| -------- | ------------------------------------------------------------ | 6517| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 6518| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6519 6520**Example** 6521 6522```ts 6523// xxx.ets 6524import { webview } from '@kit.ArkWeb'; 6525import { BusinessError } from '@kit.BasicServicesKit'; 6526 6527@Entry 6528@Component 6529struct WebComponent { 6530 controller: webview.WebviewController = new webview.WebviewController(); 6531 6532 build() { 6533 Column() { 6534 Button('setScrollable') 6535 .onClick(() => { 6536 try { 6537 this.controller.setScrollable(true); 6538 } catch (error) { 6539 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6540 } 6541 }) 6542 Web({ src: 'www.example.com', controller: this.controller }) 6543 } 6544 } 6545} 6546``` 6547 6548### getScrollable<sup>12+</sup> 6549 6550getScrollable(): boolean 6551 6552Obtains whether this web page is scrollable. 6553 6554**System capability**: SystemCapability.Web.Webview.Core 6555 6556**Return value** 6557 6558| Type | Description | 6559| ------ | -------------- | 6560| boolean | Whether the web page is scrollable. The value **true** means the web page is scrollable, and **false** means the opposite.| 6561 6562**Error codes** 6563 6564For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6565 6566| ID| Error Message | 6567| -------- | ------------------------------------------------------------ | 6568| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6569 6570**Example** 6571 6572```ts 6573// xxx.ets 6574import { webview } from '@kit.ArkWeb'; 6575import { BusinessError } from '@kit.BasicServicesKit'; 6576 6577@Entry 6578@Component 6579struct WebComponent { 6580 controller: webview.WebviewController = new webview.WebviewController(); 6581 6582 build() { 6583 Column() { 6584 Button('getScrollable') 6585 .onClick(() => { 6586 try { 6587 let scrollEnabled = this.controller.getScrollable(); 6588 console.log("scrollEnabled: " + scrollEnabled); 6589 } catch (error) { 6590 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6591 } 6592 }) 6593 Web({ src: 'www.example.com', controller: this.controller }) 6594 } 6595 } 6596} 6597``` 6598 6599### setPrintBackground<sup>12+</sup> 6600 6601setPrintBackground(enable: boolean): void 6602 6603Sets whether to print the web page background. 6604 6605**System capability**: SystemCapability.Web.Webview.Core 6606 6607**Parameters** 6608 6609| Name | Type | Mandatory| Description | 6610| -------- | ------- | ---- | -------------------------------------- | 6611| 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.| 6612 6613**Error codes** 6614 6615For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6616 6617| ID| Error Message | 6618| -------- | ------------------------------------------------------------ | 6619| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 6620| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6621 6622**Example** 6623 6624```ts 6625import { webview } from '@kit.ArkWeb'; 6626import { BusinessError } from '@kit.BasicServicesKit'; 6627 6628@Entry 6629@Component 6630struct WebComponent { 6631 controller: webview.WebviewController = new webview.WebviewController(); 6632 6633 build() { 6634 Column() { 6635 Button('setPrintBackground') 6636 .onClick(() => { 6637 try { 6638 this.controller.setPrintBackground(false); 6639 } catch (error) { 6640 console.error(`ErrorCode:${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6641 } 6642 }) 6643 Web({ src: 'www.example.com', controller: this.controller }) 6644 } 6645 } 6646} 6647``` 6648 6649### getPrintBackground<sup>12+</sup> 6650 6651getPrintBackground(): boolean 6652 6653Obtains whether the web page background is printed. 6654 6655**System capability**: SystemCapability.Web.Webview.Core 6656 6657**Return value** 6658 6659| Type | Description | 6660| -------------------- | ------------------------- | 6661| boolean | Whether the web page background is printed.| 6662 6663**Error codes** 6664 6665For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6666 6667| ID| Error Message | 6668| -------- | ------------------------------------------------------------ | 6669| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6670 6671**Example** 6672 6673```ts 6674import { webview } from '@kit.ArkWeb'; 6675import { BusinessError } from '@kit.BasicServicesKit'; 6676 6677@Entry 6678@Component 6679struct WebComponent { 6680 controller: webview.WebviewController = new webview.WebviewController(); 6681 6682 build() { 6683 Column() { 6684 Button('setPrintBackground') 6685 .onClick(() => { 6686 try { 6687 let enable = this.controller.getPrintBackground(); 6688 console.log("getPrintBackground: " + enable); 6689 } catch (error) { 6690 console.error(`ErrorCode:${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6691 } 6692 }) 6693 Web({ src: 'www.example.com', controller: this.controller }) 6694 } 6695 } 6696} 6697``` 6698 6699### getLastJavascriptProxyCallingFrameUrl<sup>12+</sup> 6700 6701getLastJavascriptProxyCallingFrameUrl(): string 6702 6703Obtains 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. 6704 6705**System capability**: SystemCapability.Web.Webview.Core 6706 6707**Error codes** 6708 6709For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6710 6711| ID| Error Message | 6712| -------- | ------------------------------------------------------------ | 6713| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6714 6715**Example** 6716 6717```ts 6718// xxx.ets 6719import { webview } from '@kit.ArkWeb'; 6720import { BusinessError } from '@kit.BasicServicesKit'; 6721 6722class TestObj { 6723 mycontroller: webview.WebviewController; 6724 6725 constructor(controller: webview.WebviewController) { 6726 this.mycontroller = controller; 6727 } 6728 6729 test(testStr: string): string { 6730 console.log('Web Component str' + testStr + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 6731 return testStr; 6732 } 6733 6734 toString(): void { 6735 console.log('Web Component toString ' + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 6736 } 6737 6738 testNumber(testNum: number): number { 6739 console.log('Web Component number' + testNum + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 6740 return testNum; 6741 } 6742 6743 testBool(testBol: boolean): boolean { 6744 console.log('Web Component boolean' + testBol + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 6745 return testBol; 6746 } 6747} 6748 6749class WebObj { 6750 mycontroller: webview.WebviewController; 6751 6752 constructor(controller: webview.WebviewController) { 6753 this.mycontroller = controller; 6754 } 6755 6756 webTest(): string { 6757 console.log('Web test ' + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 6758 return "Web test"; 6759 } 6760 6761 webString(): void { 6762 console.log('Web test toString ' + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 6763 } 6764} 6765 6766@Entry 6767@Component 6768struct Index { 6769 controller: webview.WebviewController = new webview.WebviewController(); 6770 @State testObjtest: TestObj = new TestObj(this.controller); 6771 @State webTestObj: WebObj = new WebObj(this.controller); 6772 6773 build() { 6774 Column() { 6775 Button('refresh') 6776 .onClick(() => { 6777 try { 6778 this.controller.refresh(); 6779 } catch (error) { 6780 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6781 } 6782 }) 6783 Button('Register JavaScript To Window') 6784 .onClick(() => { 6785 try { 6786 this.controller.registerJavaScriptProxy(this.testObjtest, "objName", ["test", "toString", "testNumber", "testBool"]); 6787 this.controller.registerJavaScriptProxy(this.webTestObj, "objTestName", ["webTest", "webString"]); 6788 } catch (error) { 6789 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6790 } 6791 }) 6792 Button('deleteJavaScriptRegister') 6793 .onClick(() => { 6794 try { 6795 this.controller.deleteJavaScriptRegister("objName"); 6796 this.controller.deleteJavaScriptRegister("objTestName"); 6797 } catch (error) { 6798 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6799 } 6800 }) 6801 Web({ src: $rawfile('index.html'), controller: this.controller }) 6802 .javaScriptAccess(true) 6803 } 6804 } 6805} 6806``` 6807 6808HTML file to be loaded: 6809```html 6810<!-- index.html --> 6811<!DOCTYPE html> 6812<html> 6813 <meta charset="utf-8"> 6814 <body> 6815 <button type="button" onclick="htmlTest()">Click Me!</button> 6816 <p id="demo"></p> 6817 <p id="webDemo"></p> 6818 </body> 6819 <script type="text/javascript"> 6820 function htmlTest() { 6821 // This function call expects to return "ArkUI Web Component" 6822 let str=objName.test("webtest data"); 6823 objName.testNumber(1); 6824 objName.testBool(true); 6825 document.getElementById("demo").innerHTML=str; 6826 console.log('objName.test result:'+ str) 6827 6828 // This function call expects to return "Web test" 6829 let webStr = objTestName.webTest(); 6830 document.getElementById("webDemo").innerHTML=webStr; 6831 console.log('objTestName.webTest result:'+ webStr) 6832 } 6833</script> 6834</html> 6835``` 6836 6837### pauseAllTimers<sup>12+</sup> 6838 6839pauseAllTimers(): void 6840 6841Pauses all WebView timers. 6842 6843**System capability**: SystemCapability.Web.Webview.Core 6844 6845**Error codes** 6846 6847For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6848 6849| ID| Error Message | 6850| -------- | ------------------------------------------------------------ | 6851| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6852 6853**Example** 6854 6855```ts 6856import { webview } from '@kit.ArkWeb'; 6857import { BusinessError } from '@kit.BasicServicesKit'; 6858 6859@Entry 6860@Component 6861struct WebComponent { 6862 controller: webview.WebviewController = new webview.WebviewController(); 6863 6864 build() { 6865 Column() { 6866 Row() { 6867 Button('PauseAllTimers') 6868 .onClick(() => { 6869 try { 6870 webview.WebviewController.pauseAllTimers(); 6871 } catch (error) { 6872 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6873 } 6874 }) 6875 } 6876 Web({ src: $rawfile("index.html"), controller: this.controller }) 6877 } 6878 } 6879} 6880``` 6881HTML file to be loaded: 6882 6883```html 6884<!DOCTYPE html> 6885<html> 6886 <body> 6887 <button style="width:300px;height:150px;font-size:50px" onclick="startTimer()">start</button> 6888 <button style="width:300px;height:150px;font-size:50px" onclick="resetTimer()">reset</button> 6889 <input style="width:300px;height:150px;font-size:50px" value="0" id="show_num"> 6890 </body> 6891</html> 6892<script> 6893 var timer = null; 6894 var num = 0; 6895 6896 function startTimer() { 6897 timer = setInterval(function() { 6898 document.getElementById("show_num").value = ++num; 6899 }, 1000); 6900 } 6901</script> 6902``` 6903 6904### resumeAllTimers<sup>12+</sup> 6905 6906resumeAllTimers(): void 6907 6908Resumes all timers that are paused from the **pauseAllTimers()** API. 6909 6910**System capability**: SystemCapability.Web.Webview.Core 6911 6912**Error codes** 6913 6914For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6915 6916| ID| Error Message | 6917| -------- | ------------------------------------------------------------ | 6918| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6919 6920**Example** 6921 6922```ts 6923import { webview } from '@kit.ArkWeb'; 6924import { BusinessError } from '@kit.BasicServicesKit'; 6925 6926@Entry 6927@Component 6928struct WebComponent { 6929 controller: webview.WebviewController = new webview.WebviewController(); 6930 6931 build() { 6932 Column() { 6933 Row() { 6934 Button('ResumeAllTimers') 6935 .onClick(() => { 6936 try { 6937 webview.WebviewController.resumeAllTimers(); 6938 } catch (error) { 6939 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6940 } 6941 }) 6942 Button('PauseAllTimers') 6943 .onClick(() => { 6944 try { 6945 webview.WebviewController.pauseAllTimers(); 6946 } catch (error) { 6947 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6948 } 6949 }) 6950 } 6951 Web({ src: $rawfile("index.html"), controller: this.controller }) 6952 } 6953 } 6954} 6955``` 6956HTML file to be loaded: 6957 6958```html 6959<!DOCTYPE html> 6960<html> 6961 <body> 6962 <button style="width:300px;height:150px;font-size:50px" onclick="startTimer()">start</button> 6963 <button style="width:300px;height:150px;font-size:50px" onclick="resetTimer()">reset</button> 6964 <input style="width:300px;height:150px;font-size:50px" value="0" id="show_num"> 6965 </body> 6966</html> 6967<script> 6968 var timer = null; 6969 var num = 0; 6970 6971 function startTimer() { 6972 timer = setInterval(function() { 6973 document.getElementById("show_num").value = ++num; 6974 }, 1000); 6975 } 6976 6977 function resetTimer() { 6978 clearInterval(timer); 6979 document.getElementById("show_num").value = 0; 6980 num = 0; 6981 } 6982</script> 6983``` 6984 6985### stopAllMedia<sup>12+</sup> 6986 6987stopAllMedia(): void 6988 6989Stops all audio and video on a web page. 6990 6991**System capability**: SystemCapability.Web.Webview.Core 6992 6993**Error codes** 6994 6995For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6996 6997| ID| Error Message | 6998| -------- | ------------------------------------------------------------ | 6999| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7000 7001**Example** 7002 7003```ts 7004// xxx.ets 7005import { webview } from '@kit.ArkWeb'; 7006import { BusinessError } from '@kit.BasicServicesKit'; 7007 7008@Entry 7009@Component 7010struct WebComponent { 7011 controller: webview.WebviewController = new webview.WebviewController(); 7012 7013 build() { 7014 Column() { 7015 Button('stopAllMedia') 7016 .onClick(() => { 7017 try { 7018 this.controller.stopAllMedia(); 7019 } catch (error) { 7020 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7021 } 7022 }) 7023 Web({ src: 'www.example.com', controller: this.controller }) 7024 } 7025 } 7026} 7027``` 7028 7029### pauseAllMedia<sup>12+</sup> 7030 7031pauseAllMedia(): void 7032 7033Pauses all audio and video on a web page. 7034 7035**System capability**: SystemCapability.Web.Webview.Core 7036 7037**Error codes** 7038 7039For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7040 7041| ID| Error Message | 7042| -------- | ------------------------------------------------------------ | 7043| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7044 7045**Example** 7046 7047```ts 7048// xxx.ets 7049import { webview } from '@kit.ArkWeb'; 7050import { BusinessError } from '@kit.BasicServicesKit'; 7051 7052@Entry 7053@Component 7054struct WebComponent { 7055 controller: webview.WebviewController = new webview.WebviewController(); 7056 7057 build() { 7058 Column() { 7059 Button('pauseAllMedia') 7060 .onClick(() => { 7061 try { 7062 this.controller.pauseAllMedia(); 7063 } catch (error) { 7064 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7065 } 7066 }) 7067 Web({ src: 'www.example.com', controller: this.controller }) 7068 } 7069 } 7070} 7071``` 7072 7073### resumeAllMedia<sup>12+</sup> 7074 7075resumeAllMedia(): void 7076 7077Resumes the playback of the audio and video that are paused by the pauseAllMedia interface. 7078 7079**System capability**: SystemCapability.Web.Webview.Core 7080 7081**Error codes** 7082 7083For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7084 7085| ID| Error Message | 7086| -------- | ------------------------------------------------------------ | 7087| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7088 7089**Example** 7090 7091```ts 7092// xxx.ets 7093import { webview } from '@kit.ArkWeb'; 7094import { BusinessError } from '@kit.BasicServicesKit'; 7095 7096@Entry 7097@Component 7098struct WebComponent { 7099 controller: webview.WebviewController = new webview.WebviewController(); 7100 7101 build() { 7102 Column() { 7103 Button('resumeAllMedia') 7104 .onClick(() => { 7105 try { 7106 this.controller.resumeAllMedia(); 7107 } catch (error) { 7108 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7109 } 7110 }) 7111 Web({ src: 'www.example.com', controller: this.controller }) 7112 } 7113 } 7114} 7115``` 7116 7117### closeAllMediaPresentations<sup>12+</sup> 7118 7119closeAllMediaPresentations(): void 7120 7121Closes all full-screen videos on a web page. 7122 7123**System capability**: SystemCapability.Web.Webview.Core 7124 7125**Error codes** 7126 7127For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7128 7129| ID| Error Message | 7130| -------- | ------------------------------------------------------------ | 7131| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7132 7133**Example** 7134 7135```ts 7136// xxx.ets 7137import { webview } from '@kit.ArkWeb'; 7138import { BusinessError } from '@kit.BasicServicesKit'; 7139 7140@Entry 7141@Component 7142struct WebComponent { 7143 controller: webview.WebviewController = new webview.WebviewController(); 7144 7145 build() { 7146 Column() { 7147 Button('closeAllMediaPresentations') 7148 .onClick(() => { 7149 try { 7150 this.controller.closeAllMediaPresentations(); 7151 } catch (error) { 7152 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7153 } 7154 }) 7155 Web({ src: 'www.example.com', controller: this.controller }) 7156 } 7157 } 7158} 7159``` 7160 7161### getMediaPlaybackState<sup>12+</sup> 7162 7163getMediaPlaybackState(): MediaPlaybackState 7164 7165Queries the current audio and video playback control status. 7166 7167**System capability**: SystemCapability.Web.Webview.Core 7168 7169**Return value** 7170 7171| Type | Description | 7172| ------------------------------------------- | --------------------------------------------------------- | 7173| [MediaPlaybackState](#mediaplaybackstate12) | Playback control status of the current web page. The options are **NONE**, **PLAYING**, **PAUSED**, and **STOPPED**.| 7174 7175**Error codes** 7176 7177For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7178 7179| ID| Error Message | 7180| -------- | ------------------------------------------------------------ | 7181| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7182 7183**Example** 7184 7185```ts 7186// xxx.ets 7187import { webview } from '@kit.ArkWeb'; 7188import { BusinessError } from '@kit.BasicServicesKit'; 7189 7190@Entry 7191@Component 7192struct WebComponent { 7193 controller: webview.WebviewController = new webview.WebviewController(); 7194 7195 build() { 7196 Column() { 7197 Button('getMediaPlaybackState') 7198 .onClick(() => { 7199 try { 7200 console.log("MediaPlaybackState : " + this.controller.getMediaPlaybackState()); 7201 } catch (error) { 7202 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7203 } 7204 }) 7205 Web({ src: 'www.example.com', controller: this.controller }) 7206 } 7207 } 7208} 7209``` 7210 7211### setWebSchemeHandler<sup>12+</sup> 7212 7213setWebSchemeHandler(scheme: string, handler: WebSchemeHandler): void 7214 7215Sets the [WebSchemeHandler](#webschemehandler12), [WebSchemeHandler](#webschemehandler12) class for the current Web component to intercept requests of a specified scheme. 7216 7217**System capability**: SystemCapability.Web.Webview.Core 7218 7219**Parameters** 7220 7221| Name| Type | Mandatory| Description | 7222| ------ | ------ | ---- | :------------------------ | 7223| scheme | string | Yes | Protocol to be intercepted.| 7224| handler | [WebSchemeHandler](#webschemehandler12) | Yes | Interceptor that intercepts this protocol.| 7225 7226**Error codes** 7227 7228For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7229 7230| ID| Error Message | 7231| -------- | ------------------------------------------------------------ | 7232| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 7233| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7234 7235**Example** 7236 7237```ts 7238// xxx.ets 7239import { webview } from '@kit.ArkWeb'; 7240import { BusinessError } from '@kit.BasicServicesKit'; 7241 7242@Entry 7243@Component 7244struct WebComponent { 7245 controller: webview.WebviewController = new webview.WebviewController(); 7246 schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); 7247 7248 build() { 7249 Column() { 7250 Button('setWebSchemeHandler') 7251 .onClick(() => { 7252 try { 7253 this.controller.setWebSchemeHandler('http', this.schemeHandler); 7254 } catch (error) { 7255 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7256 } 7257 }) 7258 Web({ src: 'www.example.com', controller: this.controller }) 7259 } 7260 } 7261} 7262``` 7263 7264### clearWebSchemeHandler<sup>12+</sup> 7265 7266clearWebSchemeHandler(): void 7267 7268Clears all WebSchemeHandlers set for the current Web component. 7269 7270**System capability**: SystemCapability.Web.Webview.Core 7271 7272**Error codes** 7273 7274For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7275 7276| ID| Error Message | 7277| -------- | ------------------------------------------------------------ | 7278| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7279 7280**Example** 7281 7282```ts 7283// xxx.ets 7284import { webview } from '@kit.ArkWeb'; 7285import { BusinessError } from '@kit.BasicServicesKit'; 7286 7287@Entry 7288@Component 7289struct WebComponent { 7290 controller: webview.WebviewController = new webview.WebviewController(); 7291 7292 build() { 7293 Column() { 7294 Button('clearWebSchemeHandler') 7295 .onClick(() => { 7296 try { 7297 this.controller.clearWebSchemeHandler(); 7298 } catch (error) { 7299 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7300 } 7301 }) 7302 Web({ src: 'www.example.com', controller: this.controller }) 7303 } 7304 } 7305} 7306``` 7307 7308### setServiceWorkerWebSchemeHandler<sup>12+</sup> 7309 7310setServiceWorkerWebSchemeHandler(scheme: string, handler: WebSchemeHandler): void 7311 7312Sets the WebSchemeHandler used to intercept ServiceWorker for all Web components of the current application. 7313 7314**System capability**: SystemCapability.Web.Webview.Core 7315 7316**Parameters** 7317 7318| Name| Type | Mandatory| Description | 7319| ------ | ------ | ---- | :------------------------ | 7320| scheme | string | Yes | Protocol to be intercepted.| 7321| handler | [WebSchemeHandler](#webschemehandler12) | Yes | Interceptor that intercepts this protocol.| 7322 7323**Error codes** 7324 7325For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7326 7327| ID| Error Message | 7328| -------- | ------------------------------------------------------------ | 7329| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 7330 7331**Example** 7332 7333```ts 7334// xxx.ets 7335import { webview } from '@kit.ArkWeb'; 7336import { BusinessError } from '@kit.BasicServicesKit'; 7337 7338@Entry 7339@Component 7340struct WebComponent { 7341 controller: webview.WebviewController = new webview.WebviewController(); 7342 schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); 7343 7344 build() { 7345 Column() { 7346 Button('setWebSchemeHandler') 7347 .onClick(() => { 7348 try { 7349 webview.WebviewController.setServiceWorkerWebSchemeHandler('http', this.schemeHandler); 7350 } catch (error) { 7351 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7352 } 7353 }) 7354 Web({ src: 'www.example.com', controller: this.controller }) 7355 } 7356 } 7357} 7358``` 7359 7360### clearServiceWorkerWebSchemeHandler<sup>12+</sup> 7361 7362clearServiceWorkerWebSchemeHandler(): void 7363 7364Clears all WebSchemeHandlers that are set in the application and used to intercept ServiceWorker. 7365 7366**System capability**: SystemCapability.Web.Webview.Core 7367 7368**Example** 7369 7370```ts 7371// xxx.ets 7372import { webview } from '@kit.ArkWeb'; 7373 7374@Entry 7375@Component 7376struct WebComponent { 7377 controller: webview.WebviewController = new webview.WebviewController(); 7378 7379 build() { 7380 Column() { 7381 Button('clearServiceWorkerWebSchemeHandler') 7382 .onClick(() => { 7383 webview.WebviewController.clearServiceWorkerWebSchemeHandler(); 7384 }) 7385 Web({ src: 'www.example.com', controller: this.controller }) 7386 } 7387 } 7388} 7389``` 7390 7391### startCamera<sup>12+</sup> 7392 7393startCamera(): void 7394 7395Enables the camera capture of the current web page. 7396 7397**System capability**: SystemCapability.Web.Webview.Core 7398 7399**Error codes** 7400 7401For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7402 7403| ID| Error Message | 7404| -------- | ------------------------------------------------------------ | 7405| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7406 7407**Example** 7408```ts 7409// xxx.ets 7410import { webview } from '@kit.ArkWeb'; 7411import { BusinessError } from '@kit.BasicServicesKit'; 7412import { abilityAccessCtrl, PermissionRequestResult, common } from '@kit.AbilityKit'; 7413 7414let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); 7415try { 7416 let context: Context = getContext(this) as common.UIAbilityContext; 7417 atManager.requestPermissionsFromUser(context, ['ohos.permission.CAMERA'], (err: BusinessError, data: PermissionRequestResult) => { 7418 console.info('data:' + JSON.stringify(data)); 7419 console.info('data permissions:' + data.permissions); 7420 console.info('data authResults:' + data.authResults); 7421 }) 7422} catch (error) { 7423 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7424} 7425 7426@Entry 7427@Component 7428struct WebComponent { 7429 controller: webview.WebviewController = new webview.WebviewController(); 7430 7431 build() { 7432 Column() { 7433 Button("startCamera").onClick(() => { 7434 try { 7435 this.controller.startCamera(); 7436 } catch (error) { 7437 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7438 } 7439 }) 7440 Button("stopCamera").onClick(() => { 7441 try { 7442 this.controller.stopCamera(); 7443 } catch (error) { 7444 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7445 } 7446 }) 7447 Button("closeCamera").onClick(() => { 7448 try { 7449 this.controller.closeCamera(); 7450 } catch (error) { 7451 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7452 } 7453 }) 7454 Web({ src: $rawfile('index.html'), controller: this.controller }) 7455 .onPermissionRequest((event) => { 7456 if (event) { 7457 AlertDialog.show({ 7458 title: 'title', 7459 message: 'text', 7460 primaryButton: { 7461 value: 'deny', 7462 action: () => { 7463 event.request.deny(); 7464 } 7465 }, 7466 secondaryButton: { 7467 value: 'onConfirm', 7468 action: () => { 7469 event.request.grant(event.request.getAccessibleResource()); 7470 } 7471 }, 7472 cancel: () => { 7473 event.request.deny(); 7474 } 7475 }) 7476 } 7477 }) 7478 } 7479 } 7480} 7481 7482``` 7483HTML file to be loaded: 7484 ```html 7485<!-- index.html --> 7486<!DOCTYPE html> 7487<html> 7488 <head> 7489 <meta charset="UTF-8"> 7490 </head> 7491 <body> 7492 <video id="video" width="400px" height="400px" autoplay="autoplay"> 7493 </video> 7494 <input type="button" title="HTML5 Camera" value="Enable Camera" onclick="getMedia()"/> 7495 <script> 7496 function getMedia() { 7497 let constraints = { 7498 video: { 7499 width: 500, 7500 height: 500 7501 }, 7502 audio: true 7503 } 7504 let video = document.getElementById("video"); 7505 let promise = navigator.mediaDevices.getUserMedia(constraints); 7506 promise.then(function(MediaStream) { 7507 video.srcObject = MediaStream; 7508 video.play(); 7509 }) 7510 } 7511 </script> 7512 </body> 7513</html> 7514 ``` 7515 7516### stopCamera<sup>12+</sup> 7517 7518stopCamera(): void 7519 7520Stops the camera capture of the current web page. 7521 7522**System capability**: SystemCapability.Web.Webview.Core 7523 7524**Error codes** 7525 7526For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7527 7528| ID| Error Message | 7529| -------- | ------------------------------------------------------------ | 7530| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7531 7532**Example** 7533 7534For the complete sample code, see [startCamera](#startcamera12). 7535 7536### closeCamera<sup>12+</sup> 7537 7538closeCamera(): void 7539 7540Disables the camera capture of the current web page. 7541 7542**System capability**: SystemCapability.Web.Webview.Core 7543 7544**Error codes** 7545 7546For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7547 7548| ID| Error Message | 7549| -------- | ------------------------------------------------------------ | 7550| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7551 7552**Example** 7553 7554For the complete sample code, see [startCamera](#startcamera12). 7555 7556### precompileJavaScript<sup>12+</sup> 7557 7558precompileJavaScript(url: string, script: string | Uint8Array, cacheOptions: CacheOptions): Promise\<number\> 7559 7560Precompiles JavaScript to generate the bytecode cache or update the existing bytecode cache based on the provided parameters. 7561The API determines whether to update the existing bytecode cache based on the provided file information, E-Tag response header, and Last-Modified response header. 7562 7563**System capability**: SystemCapability.Web.Webview.Core 7564 7565**Parameters** 7566 7567| Name | Type | Mandatory| Description | 7568| ------- | ------ | ---- | :-------------------- | 7569| 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. | 7570| script | string \| Uint8Array | Yes | Text content of the local JavaScript. The content cannot be empty. | 7571| cacheOptions | [CacheOptions](#cacheoptions12) | Yes | Whether to update the bytecode cache. | 7572 7573**Return value** 7574 7575| Type | Description | 7576| ----------------------------------- | --------------------------- | 7577| 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.| 7578 7579**Error codes** 7580 7581For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7582 7583| ID| Error Message | 7584| -------- | ------------------------------------------------------------ | 7585| 401 | Invalid input parameter.Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | 7586| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7587 7588**Example** 7589 7590The 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: 7591 75921. Save **UIContext** to localStorage in **EntryAbility**. 7593 7594 ```ts 7595 // EntryAbility.ets 7596 import { UIAbility } from '@kit.AbilityKit'; 7597 import { window } from '@kit.ArkUI'; 7598 7599 const localStorage: LocalStorage = new LocalStorage('uiContext'); 7600 7601 export default class EntryAbility extends UIAbility { 7602 storage: LocalStorage = localStorage; 7603 7604 onWindowStageCreate(windowStage: window.WindowStage) { 7605 windowStage.loadContent('pages/Index', this.storage, (err, data) => { 7606 if (err.code) { 7607 return; 7608 } 7609 7610 this.storage.setOrCreate<UIContext>("uiContext", windowStage.getMainWindowSync().getUIContext()); 7611 }); 7612 } 7613 } 7614 ``` 7615 76162. Write the basic code required by the dynamic component. 7617 7618 ```ts 7619 // DynamicComponent.ets 7620 import { NodeController, BuilderNode, FrameNode, UIContext } from '@kit.ArkUI'; 7621 7622 export interface BuilderData { 7623 url: string; 7624 controller: WebviewController; 7625 } 7626 7627 const storage = LocalStorage.getShared(); 7628 7629 export class NodeControllerImpl extends NodeController { 7630 private rootNode: BuilderNode<BuilderData[]> | null = null; 7631 private wrappedBuilder: WrappedBuilder<BuilderData[]> | null = null; 7632 7633 constructor(wrappedBuilder: WrappedBuilder<BuilderData[]>) { 7634 super(); 7635 this.wrappedBuilder = wrappedBuilder; 7636 } 7637 7638 makeNode(): FrameNode | null { 7639 if (this.rootNode != null) { 7640 return this.rootNode.getFrameNode(); 7641 } 7642 return null; 7643 } 7644 7645 initWeb(url: string, controller: WebviewController) { 7646 if(this.rootNode != null) { 7647 return; 7648 } 7649 7650 const uiContext: UIContext = storage.get<UIContext>("uiContext") as UIContext; 7651 if (!uiContext) { 7652 return; 7653 } 7654 this.rootNode = new BuilderNode(uiContext); 7655 this.rootNode.build(this.wrappedBuilder, { url: url, controller: controller }); 7656 } 7657 } 7658 7659 export const createNode = (wrappedBuilder: WrappedBuilder<BuilderData[]>, data: BuilderData) => { 7660 const baseNode = new NodeControllerImpl(wrappedBuilder); 7661 baseNode.initWeb(data.url, data.controller); 7662 return baseNode; 7663 } 7664 ``` 7665 76663. 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. 7667 7668 <!--code_no_check--> 7669 ```ts 7670 // PrecompileWebview.ets 7671 import { BuilderData } from "./DynamicComponent"; 7672 import { Config, configs } from "./PrecompileConfig"; 7673 7674 @Builder 7675 function WebBuilder(data: BuilderData) { 7676 Web({ src: data.url, controller: data.controller }) 7677 .onControllerAttached(() => { 7678 precompile(data.controller, configs); 7679 }) 7680 .fileAccess(true) 7681 } 7682 7683 export const precompileWebview = wrapBuilder<BuilderData[]>(WebBuilder); 7684 7685 export const precompile = async (controller: WebviewController, configs: Array<Config>) => { 7686 for (const config of configs) { 7687 let content = await readRawFile(config.localPath); 7688 7689 try { 7690 controller.precompileJavaScript(config.url, content, config.options) 7691 .then(errCode => { 7692 console.error("precompile successfully! " + errCode); 7693 }).catch((errCode: number) => { 7694 console.error("precompile failed. " + errCode); 7695 }); 7696 } catch (err) { 7697 console.error("precompile failed. " + err.code + " " + err.message); 7698 } 7699 } 7700 } 7701 7702 async function readRawFile(path: string) { 7703 try { 7704 return await getContext().resourceManager.getRawFileContent(path);; 7705 } catch (err) { 7706 return new Uint8Array(0); 7707 } 7708 } 7709 ``` 7710 7711JavaScript 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. 7712 77134. Compile the code of the service component. 7714 7715 <!--code_no_check--> 7716 ```ts 7717 // BusinessWebview.ets 7718 import { BuilderData } from "./DynamicComponent"; 7719 7720 @Builder 7721 function WebBuilder(data: BuilderData) { 7722 // The component can be extended based on service requirements. 7723 Web({ src: data.url, controller: data.controller }) 7724 .cacheMode(CacheMode.Default) 7725 } 7726 7727 export const businessWebview = wrapBuilder<BuilderData[]>(WebBuilder); 7728 ``` 7729 77305. Write the resource configuration information. 7731 7732 ```ts 7733 // PrecompileConfig.ets 7734 import { webview } from '@kit.ArkWeb' 7735 7736 export interface Config { 7737 url: string, 7738 localPath: string, // Local resource path 7739 options: webview.CacheOptions 7740 } 7741 7742 export let configs: Array<Config> = [ 7743 { 7744 url: "https://www.example.com/example.js", 7745 localPath: "example.js", 7746 options: { 7747 responseHeaders: [ 7748 { headerKey: "E-Tag", headerValue: "aWO42N9P9dG/5xqYQCxsx+vDOoU="}, 7749 { headerKey: "Last-Modified", headerValue: "Wed, 21 Mar 2024 10:38:41 GMT"} 7750 ] 7751 } 7752 } 7753 ] 7754 ``` 7755 77566. Use the component on the page. 7757 7758 <!--code_no_check--> 7759 ```ts 7760 // Index.ets 7761 import { webview } from '@kit.ArkWeb'; 7762 import { NodeController } from '@kit.ArkUI'; 7763 import { createNode } from "./DynamicComponent" 7764 import { precompileWebview } from "./PrecompileWebview" 7765 import { businessWebview } from "./BusinessWebview" 7766 7767 @Entry 7768 @Component 7769 struct Index { 7770 @State precompileNode: NodeController | undefined = undefined; 7771 precompileController: webview.WebviewController = new webview.WebviewController(); 7772 7773 @State businessNode: NodeController | undefined = undefined; 7774 businessController: webview.WebviewController = new webview.WebviewController(); 7775 7776 aboutToAppear(): void { 7777 // Initialize the Web component used to inject local resources. 7778 this.precompileNode = createNode(precompileWebview, 7779 { url: "https://www.example.com/empty.html", controller: this.precompileController}); 7780 } 7781 7782 build() { 7783 Column() { 7784 // Load the Web component used by the service at a proper time. In this example, the button is clicked. 7785 Button ("Load Page") 7786 .onClick(() => { 7787 this.businessNode = createNode(businessWebview, { 7788 url: "https://www.example.com/business.html", 7789 controller: this.businessController 7790 }); 7791 }) 7792 // The Web component used for the service. 7793 NodeContainer(this.businessNode); 7794 } 7795 } 7796 } 7797 ``` 7798 7799To 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. 7800 7801### onCreateNativeMediaPlayer<sup>12+</sup> 7802 7803onCreateNativeMediaPlayer(callback: CreateNativeMediaPlayerCallback): void 7804 7805Called 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. 7806If the application does not take over media playback on the web page, this callback is not invoked. 7807 7808**System capability**: SystemCapability.Web.Webview.Core 7809 7810**Parameters** 7811 7812| Name| Type| Mandatory| Description| 7813|--------|------|------|------| 7814| callback | [CreateNativeMediaPlayerCallback](#createnativemediaplayercallback12) | Yes| Callback when the application takes over media playback on the web page.| 7815 7816**Example** 7817 7818```ts 7819// xxx.ets 7820import { webview } from '@kit.ArkWeb'; 7821 7822class ActualNativeMediaPlayerListener { 7823 handler: webview.NativeMediaPlayerHandler; 7824 7825 constructor(handler: webview.NativeMediaPlayerHandler) { 7826 this.handler = handler; 7827 } 7828 7829 onPlaying() { 7830 // The native media player starts playback. 7831 this.handler.handleStatusChanged(webview.PlaybackStatus.PLAYING); 7832 } 7833 onPaused() { 7834 // The native media player pauses the playback. 7835 this.handler.handleStatusChanged(webview.PlaybackStatus.PAUSED); 7836 } 7837 onSeeking() { 7838 // The local player starts to jump to the target time point. 7839 this.handler.handleSeeking(); 7840 } 7841 onSeekDone() { 7842 // The native media player seeks to the target time point. 7843 this.handler.handleSeekFinished(); 7844 } 7845 onEnded() { 7846 // The playback on the native media player is ended. 7847 this.handler.handleEnded(); 7848 } 7849 onVolumeChanged() { 7850 // Obtain the volume of the local player. 7851 let volume: number = getVolume(); 7852 this.handler.handleVolumeChanged(volume); 7853 } 7854 onCurrentPlayingTimeUpdate() { 7855 // Update the playback time. 7856 let currentTime: number = getCurrentPlayingTime(); 7857 // Convert the time unit to second. 7858 let currentTimeInSeconds = convertToSeconds(currentTime); 7859 this.handler.handleTimeUpdate(currentTimeInSeconds); 7860 } 7861 onBufferedChanged() { 7862 // The cache is changed. 7863 // Obtain the cache duration of the native media player. 7864 let bufferedEndTime: number = getCurrentBufferedTime(); 7865 // Convert the time unit to second. 7866 let bufferedEndTimeInSeconds = convertToSeconds(bufferedEndTime); 7867 this.handler.handleBufferedEndTimeChanged(bufferedEndTimeInSeconds); 7868 7869 // Check the cache status. 7870 // If the cache status changes, notify the ArkWeb engine of the cache status. 7871 let lastReadyState: webview.ReadyState = getLastReadyState(); 7872 let currentReadyState: webview.ReadyState = getCurrentReadyState(); 7873 if (lastReadyState != currentReadyState) { 7874 this.handler.handleReadyStateChanged(currentReadyState); 7875 } 7876 } 7877 onEnterFullscreen() { 7878 // The native media player enters the full screen mode. 7879 let isFullscreen: boolean = true; 7880 this.handler.handleFullscreenChanged(isFullscreen); 7881 } 7882 onExitFullscreen() { 7883 // The native media player exits the full screen mode. 7884 let isFullscreen: boolean = false; 7885 this.handler.handleFullscreenChanged(isFullscreen); 7886 } 7887 onUpdateVideoSize(width: number, height: number) { 7888 // Notify the ArkWeb kernel when the native media player parses the video width and height. 7889 this.handler.handleVideoSizeChanged(width, height); 7890 } 7891 onDurationChanged(duration: number) { 7892 // Notify the ArkWeb kernel when the native media player parses the video duration. 7893 this.handler.handleDurationChanged(duration); 7894 } 7895 onError(error: webview.MediaError, errorMessage: string) { 7896 // Notify the ArkWeb kernel that an error occurs in the native media player. 7897 this.handler.handleError(error, errorMessage); 7898 } 7899 onNetworkStateChanged(state: webview.NetworkState) { 7900 // Notify the ArkWeb kernel that the network state of the native media player changes. 7901 this.handler.handleNetworkStateChanged(state); 7902 } 7903 onPlaybackRateChanged(playbackRate: number) { 7904 // Notify the ArkWeb kernel that the playback rate of the native media player changes. 7905 this.handler.handlePlaybackRateChanged(playbackRate); 7906 } 7907 onMutedChanged(muted: boolean) { 7908 // Notify the ArkWeb kernel that the native media player is muted. 7909 this.handler.handleMutedChanged(muted); 7910 } 7911 7912 // Listen for other state of the native media player. 7913} 7914 7915class NativeMediaPlayerImpl implements webview.NativeMediaPlayerBridge { 7916 constructor(handler: webview.NativeMediaPlayerHandler, mediaInfo: webview.MediaInfo) { 7917 // 1. Create a listener for the native media player. 7918 let listener: ActualNativeMediaPlayerListener = new ActualNativeMediaPlayerListener(handler); 7919 // 2. Create a native media player. 7920 // 3. Listen for the local player. 7921 // ... 7922 } 7923 7924 updateRect(x: number, y: number, width: number, height: number) { 7925 // The position and size of the <video> tag are changed. 7926 // Make changes based on the information change. 7927 } 7928 7929 play() { 7930 // Start the native media player for playback. 7931 } 7932 7933 pause() { 7934 //Pause the playback on the local player. 7935 } 7936 7937 seek(targetTime: number) { 7938 // The local player jumps to a specified time point. 7939 } 7940 7941 release() { 7942 // Destroy the local player. 7943 } 7944 7945 setVolume(volume: number) { 7946 // The ArkWeb kernel requires to adjust the volume of the local player. 7947 // Set the volume of the local player. 7948 } 7949 7950 setMuted(muted: boolean) { 7951 // Mute or unmute the local player. 7952 } 7953 7954 setPlaybackRate(playbackRate: number) { 7955 // Adjust the playback speed of the local player. 7956 } 7957 7958 enterFullscreen() { 7959 // Set the local player to play in full screen mode. 7960 } 7961 7962 exitFullscreen() { 7963 // Set the local player to exit full screen mode. 7964 } 7965 7966 resumePlayer() { 7967 // Create a player again. 7968 // Resume the status information of the player. 7969 } 7970 7971 suspendPlayer(type: webview.SuspendType) { 7972 // Record the status information of the player. 7973 // Destroy the player. 7974 } 7975} 7976 7977@Entry 7978@Component 7979struct WebComponent { 7980 controller: webview.WebviewController = new webview.WebviewController() 7981 build() { 7982 Column() { 7983 Web({ src: 'www.example.com', controller: this.controller }) 7984 .enableNativeMediaPlayer({enable: true, shouldOverlay: false}) 7985 .onPageBegin((event) => { 7986 this.controller.onCreateNativeMediaPlayer((handler: webview.NativeMediaPlayerHandler, mediaInfo: webview.MediaInfo) => { 7987 if (!shouldHandle(mediaInfo)) { 7988 // The local player does not take over the media. 7989 // The ArkWeb engine will play the media with its own player. 7990 return null; 7991 } 7992 let nativePlayer: webview.NativeMediaPlayerBridge = new NativeMediaPlayerImpl(handler, mediaInfo); 7993 return nativePlayer; 7994 }); 7995 }) 7996 } 7997 } 7998} 7999 8000// stub 8001function getVolume() { 8002 return 1; 8003} 8004function getCurrentPlayingTime() { 8005 return 1; 8006} 8007function getCurrentBufferedTime() { 8008 return 1; 8009} 8010function convertToSeconds(input: number) { 8011 return input; 8012} 8013function getLastReadyState() { 8014 return webview.ReadyState.HAVE_NOTHING; 8015} 8016function getCurrentReadyState() { 8017 return webview.ReadyState.HAVE_NOTHING; 8018} 8019function shouldHandle(mediaInfo: webview.MediaInfo) { 8020 return true; 8021} 8022``` 8023 8024### enableWholeWebPageDrawing<sup>12+</sup> 8025 8026static enableWholeWebPageDrawing(): void 8027 8028Enables the full drawing capability for the web page. This API works only during **Web** component initialization. 8029 8030**System capability**: SystemCapability.Web.Webview.Core 8031 8032**Example** 8033 8034```ts 8035// xxx.ets 8036import { webview } from '@kit.ArkWeb'; 8037import { BusinessError } from '@kit.BasicServicesKit'; 8038 8039@Entry 8040@Component 8041struct WebComponent { 8042 controller: webview.WebviewController = new webview.WebviewController(); 8043 8044 aboutToAppear(): void { 8045 try { 8046 webview.WebviewController.enableWholeWebPageDrawing(); 8047 } catch (error) { 8048 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8049 } 8050 } 8051 8052 build() { 8053 Column() { 8054 Web({ src: 'www.example.com', controller: this.controller }) 8055 } 8056 } 8057} 8058``` 8059 8060### webPageSnapshot<sup>12+</sup> 8061 8062webPageSnapshot(info: SnapshotInfo, callback: AsyncCallback\<SnapshotResult>): void 8063 8064Obtains the full drawing result of the web page. 8065 8066**System capability**: SystemCapability.Web.Webview.Core 8067 8068**Parameters** 8069 8070| Name | Type | Mandatory | Description | 8071| ----------- | ------------- | ---- | ------------------------ | 8072| info | [SnapshotInfo](#snapshotinfo12)| Yes | Information for obtaining the full drawing result.| 8073| callback | [SnapshotResult](#snapshotresult12)| Yes | Callback used to return the result.| 8074 8075**Example** 8076 8077```ts 8078// xxx.ets 8079import { webview } from '@kit.ArkWeb'; 8080import { BusinessError } from '@kit.BasicServicesKit'; 8081 8082@Entry 8083@Component 8084struct WebComponent { 8085 controller: webview.WebviewController = new webview.WebviewController(); 8086 8087 build() { 8088 Column() { 8089 Button('webPageSnapshot') 8090 .onClick(() => { 8091 try { 8092 this.controller.webPageSnapshot({ id: "1234", size: { width: 100, height: 100 } }, (error, result) => { 8093 if (error) { 8094 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8095 return; 8096 } 8097 if (result) { 8098 console.info(`return value is:${result}`); 8099 // You can process the returned result as required. 8100 } 8101 }); 8102 } catch (error) { 8103 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8104 } 8105 }) 8106 Web({ src: 'www.example.com', controller: this.controller }) 8107 } 8108 } 8109} 8110``` 8111 8112### injectOfflineResources<sup>12+</sup> 8113 8114injectOfflineResources(resourceMaps: Array\<[OfflineResourceMap](#offlineresourcemap12)\>): void 8115 8116Injects local offline resources to the memory cache to improve the initial page startup speed. 8117Resources 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. 8118Under 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. 8119The 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. 8120Resources injected in this mode can be loaded only through HTML tags. If the script tag on the business web page uses the **crossorigin** attribute, you must set the Cross-Origin response header to anonymous or use-credentials in the responseHeaders parameter of the interface. 8121After **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. 8122 8123**System capability**: SystemCapability.Web.Webview.Core 8124 8125**Parameters** 8126 8127| Name | Type | Mandatory| Description | 8128| ------- | ------ | ---- | :-------------------- | 8129| 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. | 8130 8131**Error codes** 8132 8133For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8134 8135| ID| Error Message | 8136| -------- | ------------------------------------------------------------ | 8137| 401 | Invalid input parameter.Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | 8138| 17100001 | Init error. The WebviewController must be associated with a Web component. | 8139| 17100002 | Invalid url. | 8140 8141**Example** 8142 8143When 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: 81441. Save **UIContext** to localStorage in **EntryAbility**. 8145 8146 ```ts 8147 // EntryAbility.ets 8148 import { UIAbility } from '@kit.AbilityKit'; 8149 import { window } from '@kit.ArkUI'; 8150 8151 const localStorage: LocalStorage = new LocalStorage('uiContext'); 8152 8153 export default class EntryAbility extends UIAbility { 8154 storage: LocalStorage = localStorage; 8155 8156 onWindowStageCreate(windowStage: window.WindowStage) { 8157 windowStage.loadContent('pages/Index', this.storage, (err, data) => { 8158 if (err.code) { 8159 return; 8160 } 8161 8162 this.storage.setOrCreate<UIContext>("uiContext", windowStage.getMainWindowSync().getUIContext()); 8163 }); 8164 } 8165 } 8166 ``` 8167 81682. Write the basic code required by the dynamic component. 8169 8170 ```ts 8171 // DynamicComponent.ets 8172 import { NodeController, BuilderNode, FrameNode, UIContext } from '@kit.ArkUI'; 8173 8174 export interface BuilderData { 8175 url: string; 8176 controller: WebviewController; 8177 } 8178 8179 const storage = LocalStorage.getShared(); 8180 8181 export class NodeControllerImpl extends NodeController { 8182 private rootNode: BuilderNode<BuilderData[]> | null = null; 8183 private wrappedBuilder: WrappedBuilder<BuilderData[]> | null = null; 8184 8185 constructor(wrappedBuilder: WrappedBuilder<BuilderData[]>) { 8186 super(); 8187 this.wrappedBuilder = wrappedBuilder; 8188 } 8189 8190 makeNode(): FrameNode | null { 8191 if (this.rootNode != null) { 8192 return this.rootNode.getFrameNode(); 8193 } 8194 return null; 8195 } 8196 8197 initWeb(url: string, controller: WebviewController) { 8198 if(this.rootNode != null) { 8199 return; 8200 } 8201 8202 const uiContext: UIContext = storage.get<UIContext>("uiContext") as UIContext; 8203 if (!uiContext) { 8204 return; 8205 } 8206 this.rootNode = new BuilderNode(uiContext); 8207 this.rootNode.build(this.wrappedBuilder, { url: url, controller: controller }); 8208 } 8209 } 8210 8211 export const createNode = (wrappedBuilder: WrappedBuilder<BuilderData[]>, data: BuilderData) => { 8212 const baseNode = new NodeControllerImpl(wrappedBuilder); 8213 baseNode.initWeb(data.url, data.controller); 8214 return baseNode; 8215 } 8216 ``` 8217 82183. 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. 8219 8220 <!--code_no_check--> 8221 ```ts 8222 // InjectWebview.ets 8223 import { webview } from '@kit.ArkWeb'; 8224 import { resourceConfigs } from "./Resource"; 8225 import { BuilderData } from "./DynamicComponent"; 8226 8227 @Builder 8228 function WebBuilder(data: BuilderData) { 8229 Web({ src: data.url, controller: data.controller }) 8230 .onControllerAttached(async () => { 8231 try { 8232 data.controller.injectOfflineResources(await getData ()); 8233 } catch (err) { 8234 console.error("error: " + err.code + " " + err.message); 8235 } 8236 }) 8237 .fileAccess(true) 8238 } 8239 8240 export const injectWebview = wrapBuilder<BuilderData[]>(WebBuilder); 8241 8242 export async function getData() { 8243 const resourceMapArr: Array<webview.OfflineResourceMap> = []; 8244 8245 // Read the configuration and read the file content from the rawfile directory. 8246 for (let config of resourceConfigs) { 8247 let buf: Uint8Array = new Uint8Array(0); 8248 if (config.localPath) { 8249 buf = await readRawFile(config.localPath); 8250 } 8251 8252 resourceMapArr.push({ 8253 urlList: config.urlList, 8254 resource: buf, 8255 responseHeaders: config.responseHeaders, 8256 type: config.type, 8257 }) 8258 } 8259 8260 return resourceMapArr; 8261 } 8262 8263 export async function readRawFile(url: string) { 8264 try { 8265 return await getContext().resourceManager.getRawFileContent(url); 8266 } catch (err) { 8267 return new Uint8Array(0); 8268 } 8269 } 8270 ``` 8271 82724. Compile the code of the service component. 8273 8274 <!--code_no_check--> 8275 ```ts 8276 // BusinessWebview.ets 8277 import { BuilderData } from "./DynamicComponent"; 8278 8279 @Builder 8280 function WebBuilder(data: BuilderData) { 8281 // The component can be extended based on service requirements. 8282 Web({ src: data.url, controller: data.controller }) 8283 .cacheMode(CacheMode.Default) 8284 } 8285 8286 export const businessWebview = wrapBuilder<BuilderData[]>(WebBuilder); 8287 ``` 8288 82895. Write the resource configuration information. 8290 8291 ```ts 8292 // Resource.ets 8293 import { webview } from '@kit.ArkWeb'; 8294 8295 export interface ResourceConfig { 8296 urlList: Array<string>, 8297 type: webview.OfflineResourceType, 8298 responseHeaders: Array<Header>, 8299 localPath: string, // Path for storing local resources in the rawfile directory. 8300 } 8301 8302 export const resourceConfigs: Array<ResourceConfig> = [ 8303 { 8304 localPath: "example.png", 8305 urlList: [ 8306 "https://www.example.com/", 8307 "https://www.example.com/path1/example.png", 8308 "https://www.example.com/path2/example.png", 8309 ], 8310 type: webview.OfflineResourceType.IMAGE, 8311 responseHeaders: [ 8312 { headerKey: "Cache-Control", headerValue: "max-age=1000" }, 8313 { headerKey: "Content-Type", headerValue: "image/png" }, 8314 ] 8315 }, 8316 { 8317 localPath: "example.js", 8318 urlList: [ // Only one URL is provided. This URL is used as both the resource origin and the network request address of the resource. 8319 "https://www.example.com/example.js", 8320 ], 8321 type: webview.OfflineResourceType.CLASSIC_JS, 8322 responseHeaders: [ 8323 // Used in <script crossorigin="anonymous" /> mode to provide additional response headers. 8324 { headerKey: "Cross-Origin", headerValue:"anonymous" } 8325 ] 8326 }, 8327 ]; 8328 ``` 8329 83306. Use the component on the page. 8331 <!--code_no_check--> 8332 ```ts 8333 // Index.ets 8334 import { webview } from '@kit.ArkWeb'; 8335 import { NodeController } from '@kit.ArkUI'; 8336 import { createNode } from "./DynamicComponent" 8337 import { injectWebview } from "./InjectWebview" 8338 import { businessWebview } from "./BusinessWebview" 8339 8340 @Entry 8341 @Component 8342 struct Index { 8343 @State injectNode: NodeController | undefined = undefined; 8344 injectController: webview.WebviewController = new webview.WebviewController(); 8345 8346 @State businessNode: NodeController | undefined = undefined; 8347 businessController: webview.WebviewController = new webview.WebviewController(); 8348 8349 aboutToAppear(): void { 8350 // Initialize the Web component used to inject local resources and provide an empty HTML page as the URL. 8351 this.injectNode = createNode(injectWebview, 8352 { url: "https://www.example.com/empty.html", controller: this.injectController}); 8353 } 8354 8355 build() { 8356 Column() { 8357 // Load the Web component used by the service at a proper time. In this example, the button is clicked. 8358 Button ("Load Page") 8359 .onClick(() => { 8360 this.businessNode = createNode(businessWebview, { 8361 url: "https://www.example.com/business.html", 8362 controller: this.businessController 8363 }); 8364 }) 8365 // The Web component used for the service. 8366 NodeContainer(this.businessNode); 8367 } 8368 } 8369 } 8370 ``` 8371 83727. Example of a loaded HTML web page: 8373 8374 ```HTML 8375 <!DOCTYPE html> 8376 <html lang="en"> 8377 <head></head> 8378 <body> 8379 <img src="https://www.example.com/path1/request.png" /> 8380 <img src="https://www.example.com/path2/request.png" /> 8381 <script src="https://www.example.com/example.js" crossorigin="anonymous"></script> 8382 </body> 8383 </html> 8384 ``` 8385 8386### setHostIP<sup>12+</sup> 8387 8388static setHostIP(hostName: string, address: string, aliveTime: number): void 8389 8390Sets the IP address of the host after domain name resolution. 8391 8392**System capability**: SystemCapability.Web.Webview.Core 8393 8394**Parameters** 8395 8396| Name | Type| Mandatory| Description | 8397| --------- | -------- | ---- | ------------------------------------ | 8398| hostName | string | Yes | Domain name of the host whose DNS records are to be added. | 8399| address | string | Yes | Host domain name resolution address (IPv4 and IPv6).| 8400| aliveTime | number | Yes | Cache validity period, in seconds. | 8401 8402**Error codes** 8403 8404For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8405 8406| ID| Error Message | 8407| -------- | ------------------------ | 8408| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | 8409 8410**Example** 8411 8412For details, see [clearHostIP](#clearhostip12). 8413 8414### clearHostIP<sup>12+</sup> 8415 8416static clearHostIP(hostName: string): void 8417 8418Clears the IP address of a specified host after domain name resolution. 8419 8420**System capability**: SystemCapability.Web.Webview.Core 8421 8422**Parameters** 8423 8424| Name | Type| Mandatory| Description | 8425| -------- | -------- | ---- | ------------------------- | 8426| hostName | string | Yes | Domain name of the host whose DNS records are to be cleared.| 8427 8428**Error codes** 8429 8430For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8431 8432| ID| Error Message | 8433| -------- | ------------------------ | 8434| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | 8435 8436**Example** 8437 8438```ts 8439// xxx.ets 8440import { webview } from '@kit.ArkWeb'; 8441import { BusinessError } from '@kit.BasicServicesKit'; 8442 8443@Entry 8444@Component 8445struct WebComponent { 8446 controller: webview.WebviewController = new webview.WebviewController(); 8447 8448 build() { 8449 Column() { 8450 // The setting takes effect before the URL is loaded. 8451 Button('setHostIP') 8452 .onClick(() => { 8453 try { 8454 webview.WebviewController.setHostIP('www.example.com', '127.0.0.1', 30); 8455 } catch (error) { 8456 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8457 } 8458 }) 8459 Button('clearHostIP') 8460 .onClick(() => { 8461 try { 8462 webview.WebviewController.clearHostIP('www.example.com'); 8463 } catch (error) { 8464 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8465 } 8466 }) 8467 Web({ src: 'www.example.com', controller: this.controller }) 8468 } 8469 } 8470} 8471``` 8472 8473### getSurfaceId<sup>12+</sup> 8474 8475getSurfaceId(): string 8476 8477Obtains 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. 8478 8479**System capability**: SystemCapability.Web.Webview.Core 8480 8481**Return value** 8482 8483| Type | Description | 8484| ------ | ------------------- | 8485| string | ID of the surface held by ArkWeb.| 8486 8487**Example** 8488 8489```ts 8490// xxx.ets 8491import { webview } from '@kit.ArkWeb'; 8492import { image } from '@kit.ImageKit'; 8493import { BusinessError } from '@kit.BasicServicesKit'; 8494 8495@Entry 8496@Component 8497struct Example{ 8498 controller: webview.WebviewController = new webview.WebviewController(); 8499 8500 @State imagePixelMap: image.PixelMap | undefined = undefined; 8501 8502 build(){ 8503 Column(){ 8504 Button ("Screenshot") 8505 .onClick(()=>{ 8506 try { 8507 let surfaceId = this.controller.getSurfaceId(); 8508 console.log("surfaceId: " + surfaceId); 8509 if(surfaceId.length != 0) { 8510 let region:image.Region = { x: 0, y: 0, size: { height: 800, width: 1000}} 8511 this.imagePixelMap = image.createPixelMapFromSurfaceSync(surfaceId, region) 8512 } 8513 } catch (error) { 8514 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8515 } 8516 }) 8517 Image(this.imagePixelMap) 8518 .height(100) 8519 Web({src: 'www.example.com', controller: this.controller}) 8520 } 8521 } 8522} 8523``` 8524 8525### setUrlTrustList<sup>12+</sup> 8526 8527setUrlTrustList(urlTrustList: string): void 8528 8529Sets 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. 8530 8531**System capability**: SystemCapability.Web.Webview.Core 8532 8533**Parameters** 8534 8535| Name | Type | Mandatory| Description | 8536| ------- | ------ | ---- | :-------------------- | 8537| 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>} | 8538 8539**Parameters in JSON format**: 8540| Name | Type| Mandatory| Description | 8541| -------- | -------- | ---- | ------------------------- | 8542| scheme | string | No| Optional parameter. The supported protocols are HTTP and HTTPS.| 8543| 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.| 8544| port | number | No| Optional parameter.| 8545| 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.| 8546 8547**Error codes** 8548 8549For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8550 8551| ID| Error Message | 8552| -------- | ------------------------------------------------------------ | 8553| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified.2. Parameter string is too long.3. Parameter verification failed. | 8554| 17100001 | Init error. The WebviewController must be associated with a Web component. | 8555 8556**Example** 8557 ```ts 8558 // xxx.ets 8559 import { webview } from '@kit.ArkWeb'; 8560 import { BusinessError } from '@kit.BasicServicesKit'; 8561 8562 @Entry 8563 @Component 8564 struct WebComponent { 8565 controller: webview.WebviewController = new webview.WebviewController(); 8566 urltrustList: string = "{\"UrlPermissionList\":[{\"scheme\":\"http\", \"host\":\"trust.example.com\", \"port\":80, \"path\":\"test\"}]}" 8567 8568 build() { 8569 Column() { 8570 Button('Setting the trustlist') 8571 .onClick(() => { 8572 try { 8573 // Set a trustlist to allow access only to trust web pages. 8574 this.controller.setUrlTrustList(this.urltrustList); 8575 } catch (error) { 8576 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8577 } 8578 }) 8579 Button('Cancel the trustlist.') 8580 .onClick(() => { 8581 try { 8582 // Input an empty string to setUrlTrustList() to disable the trustlist, and all URLs can be accessed. 8583 this.controller.setUrlTrustList(""); 8584 } catch (error) { 8585 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8586 } 8587 }) 8588 Button('Access the trust web') 8589 .onClick(() => { 8590 try { 8591 // The trustlist is enabled and trust web pages can be accessed. 8592 this.controller.loadUrl('http://trust.example.com/test'); 8593 } catch (error) { 8594 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8595 } 8596 }) 8597 Button('Access the untrust web') 8598 .onClick(() => { 8599 try { 8600 // The trustlist is enabled that untrust web pages cannot be accessed and an error page is displayed. 8601 this.controller.loadUrl('http://untrust.example.com/test'); 8602 } catch (error) { 8603 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8604 } 8605 }) 8606 Web({ src: 'http://untrust.example.com/test', controller: this.controller }).onControllerAttached(() => { 8607 try { 8608 // 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. 8609 this.controller.setUrlTrustList(this.urltrustList); 8610 } catch (error) { 8611 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8612 } 8613 }) 8614 } 8615 } 8616 } 8617 ``` 8618 8619### setPathAllowingUniversalAccess<sup>12+</sup> 8620 8621setPathAllowingUniversalAccess(pathList: Array\<string\>): void 8622 8623Sets 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: 8624 86251. 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: 8626 8627* /data/storage/el2/base/files/example 8628* /data/storage/el2/base/haps/entry/files/example 8629 86302. 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: 8631 8632* /data/storage/el1/bundle/entry/resource/resfile 8633* /data/storage/el1/bundle/entry/resource/resfile/example 8634 8635If 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). 8636 8637**System capability**: SystemCapability.Web.Webview.Core 8638 8639**Parameters** 8640 8641| Name | Type| Mandatory| Description | 8642| -------- | -------- | ---- | ------------------------- | 8643| pathList | Array\<string\> | Yes | The path list.| 8644 8645**Error codes** 8646 8647For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8648 8649| ID| Error Message | 8650| -------- | ------------------------ | 8651| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Parameter string is too long. 3.Parameter verification failed. | 8652| 17100001 | Init error. The WebviewController must be associated with a Web component. | 8653 8654**Example** 8655 8656```ts 8657// xxx.ets 8658import { webview } from '@kit.ArkWeb'; 8659import { BusinessError } from '@kit.BasicServicesKit'; 8660 8661@Entry 8662@Component 8663struct WebComponent { 8664 controller: WebviewController = new webview.WebviewController(); 8665 8666 build() { 8667 Row() { 8668 Web({ src: "", controller: this.controller }) 8669 .onControllerAttached(() => { 8670 try { 8671 // Set the list of paths that can be accessed across domains. 8672 this.controller.setPathAllowingUniversalAccess([ 8673 getContext().resourceDir, 8674 getContext().filesDir + "/example" 8675 ]) 8676 this.controller.loadUrl("file://" + getContext().resourceDir + "/index.html") 8677 } catch (error) { 8678 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8679 } 8680 }) 8681 .javaScriptAccess(true) 8682 .fileAccess(true) 8683 .domStorageAccess(true) 8684 } 8685 } 8686} 8687 8688``` 8689 8690Load the HTML file in the application resource directory **resource/resfile/index.html**. 8691```html 8692<!-- index.html --> 8693<!DOCTYPE html> 8694<html lang="en"> 8695 8696<head> 8697 <meta charset="utf-8"> 8698 <title>Demo</title> 8699 <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, viewport-fit=cover"> 8700 <script> 8701 function getFile() { 8702 var file = "file:///data/storage/el1/bundle/entry/resources/resfile/js/script.js"; 8703 var xmlHttpReq = new XMLHttpRequest(); 8704 xmlHttpReq.onreadystatechange = function(){ 8705 console.log("readyState:" + xmlHttpReq.readyState); 8706 console.log("status:" + xmlHttpReq.status); 8707 if(xmlHttpReq.readyState == 4){ 8708 if (xmlHttpReq.status == 200) { 8709 // If the path list is set on the eTS, resources can be obtained. 8710 const element = document.getElementById('text'); 8711 element.textContent = "load " + file + " success"; 8712 } else { 8713 // If the path list is not set on the eTS, a CORS error is triggered. 8714 const element = document.getElementById('text'); 8715 element.textContent = "load " + file + " failed"; 8716 } 8717 } 8718 } 8719 xmlHttpReq.open("GET", file); 8720 xmlHttpReq.send(null); 8721 } 8722 8723 </script> 8724</head> 8725 8726<body> 8727<div class="page"> 8728 <button id="example" onclick="getFile()">stealFile</button> 8729</div> 8730<div id="text"></div> 8731</body> 8732 8733</html> 8734``` 8735 8736In 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**. 8737<!--code_no_check--> 8738```javascript 8739const body = document.body; 8740const element = document.createElement('div'); 8741element.textContent = 'success'; 8742body.appendChild(element); 8743``` 8744 8745### enableBackForwardCache<sup>12+</sup> 8746 8747static enableBackForwardCache(features: BackForwardCacheSupportedFeatures): void 8748 8749Enables the back-forward cache of a **Web** component. You can specify whether to add a specific page to the back-forward cache. 8750 8751This API must be called before [initializeWebEngine()](#initializewebengine) initializes the kernel. 8752 8753**System capability**: SystemCapability.Web.Webview.Core 8754 8755**Parameters** 8756 8757| Name | Type | Mandatory | Description | 8758| ---------------| ------- | ---- | ------------- | 8759| features | [BackForwardCacheSupportedFeatures](#backforwardcachesupportedfeatures12) | Yes | Features of the pages, which allow them to be added to the back-forward cache.| 8760 8761**Example** 8762 8763```ts 8764// EntryAbility.ets 8765import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 8766import { hilog } from '@kit.PerformanceAnalysisKit'; 8767import { window } from '@kit.ArkUI'; 8768import { webview } from '@kit.ArkWeb'; 8769 8770export default class EntryAbility extends UIAbility { 8771 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 8772 let features = new webview.BackForwardCacheSupportedFeatures(); 8773 features.nativeEmbed = true; 8774 features.mediaTakeOver = true; 8775 // 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. 8776 8777 webview.WebviewController.enableBackForwardCache(features); 8778 webview.WebviewController.initializeWebEngine(); 8779 AppStorage.setOrCreate("abilityWant", want); 8780 } 8781} 8782``` 8783 8784### setBackForwardCacheOptions<sup>12+</sup> 8785 8786setBackForwardCacheOptions(options: BackForwardCacheOptions): void 8787 8788Sets the back-forward cache options of the **Web** component. 8789 8790**System capability**: SystemCapability.Web.Webview.Core 8791 8792**Parameters** 8793 8794| Name | Type | Mandatory | Description | 8795| ---------------| ------- | ---- | ------------- | 8796| options | [BackForwardCacheOptions](#backforwardcacheoptions12) | Yes | Options to control the back-forward cache of the **Web** component.| 8797 8798**Error codes** 8799 8800For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8801 8802| ID| Error Message | 8803| -------- | ------------------------------------------------------------ | 8804| 17100001 | Init error. The WebviewController must be associated with a Web component. | 8805 8806**Example** 8807 8808```ts 8809// xxx.ts 8810import { webview } from '@kit.ArkWeb'; 8811 8812@Entry 8813@Component 8814struct Index { 8815 controller: webview.WebviewController = new webview.WebviewController(); 8816 8817 build() { 8818 Column() { 8819 Row() { 8820 Button("Add options").onClick((event: ClickEvent) => { 8821 let options = new webview.BackForwardCacheOptions(); 8822 options.size = 3; 8823 options.timeToLive = 10; 8824 this.controller.setBackForwardCacheOptions(options); 8825 }) 8826 Button("Backward").onClick((event: ClickEvent) => { 8827 this.controller.backward(); 8828 }) 8829 Button("Forward").onClick((event: ClickEvent) => { 8830 this.controller.forward(); 8831 }) 8832 } 8833 Web({ src: "https://www.example.com", controller: this.controller }) 8834 } 8835 .height('100%') 8836 .width('100%') 8837 } 8838} 8839``` 8840 8841### trimMemoryByPressureLevel<sup>14+</sup> 8842 8843trimMemoryByPressureLevel(level: PressureLevel): void 8844 8845Clears the cache occupied by **Web** component based on the specified memory pressure level. 8846 8847**System capability**: SystemCapability.Web.Webview.Core 8848 8849**Parameters** 8850 8851| Name | Type | Mandatory| Description | 8852| ------- | ------ | ---- | :-------------------- | 8853| level | [PressureLevel](#pressurelevel14) | Yes| Pressure level of the memory to be cleared.| 8854 8855**Error codes** 8856 8857For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8858 8859| ID| Error Message | 8860| -------- | ------------------------------------------------------------ | 8861| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Parameter string is too long. 3.Parameter verification failed. | 8862 8863**Example** 8864```ts 8865// xxx.ets 8866import { webview } from '@kit.ArkWeb'; 8867import { BusinessError } from '@kit.BasicServicesKit'; 8868 8869@Entry 8870@Component 8871struct WebComponent { 8872 controller: WebviewController = new webview.WebviewController(); 8873 build() { 8874 Column() { 8875 Row() { 8876 Button('trim_Memory') 8877 .onClick(() => { 8878 try { 8879 // Set the current memory pressure level to moderate and release a small amount of memory. 8880 webview.WebviewController.trimMemoryByPressureLevel( 8881 webview.PressureLevel.MEMORY_PRESSURE_LEVEL_MODERATE); 8882 } catch (error) { 8883 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8884 } 8885 }) 8886 }.height('10%') 8887 Web({ src: 'www.example.com', controller: this.controller }) 8888 } 8889 } 8890} 8891``` 8892 8893### createPdf<sup>14+</sup> 8894 8895createPdf(configuration: PdfConfiguration, callback: AsyncCallback\<PdfData\>): void 8896 8897Obtains the data stream of a specified web page using an asynchronous callback. 8898 8899**System capability**: SystemCapability.Web.Webview.Core 8900 8901**Parameters** 8902 8903| Name | Type | Mandatory| Description | 8904| ------------- | --------------------------------------- | ---- | ----------------------- | 8905| configuration | [PdfConfiguration](#pdfconfiguration14) | Yes | Parameters required for creating a PDF file. | 8906| callback | AsyncCallback<[PdfData](#pdfdata14)> | Yes | Callback used to return the data stream of an online PDF file.| 8907 8908**Error codes** 8909 8910For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8911 8912| ID| Error Message | 8913| -------- | ------------------------------------------------------------ | 8914| 401 | Invalid input parameter. | 8915| 17100001 | Init error. The WebviewController must be associated with a Web component. | 8916 8917**Example** 8918 8919```ts 8920import { fileIo as fs } from '@kit.CoreFileKit'; 8921import { webview } from '@kit.ArkWeb'; 8922import { BusinessError } from '@kit.BasicServicesKit'; 8923import { common } from '@kit.AbilityKit'; 8924 8925@Entry 8926@Component 8927struct Index { 8928 controller: webview.WebviewController = new webview.WebviewController(); 8929 pdfConfig: webview.PdfConfiguration = { 8930 width: 8.27, 8931 height: 11.69, 8932 marginTop: 0, 8933 marginBottom: 0, 8934 marginRight: 0, 8935 marginLeft: 0, 8936 shouldPrintBackground: true 8937 } 8938 8939 build() { 8940 Column() { 8941 Button('SavePDF') 8942 .onClick(() => { 8943 this.controller.createPdf( 8944 this.pdfConfig, 8945 (error, result: webview.PdfData) => { 8946 try { 8947 // Obtain the component context. 8948 let context = getContext(this) as common.UIAbilityContext; 8949 // Obtain the sandbox path and set the PDF file name. 8950 let filePath = context.filesDir + "/test.pdf"; 8951 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 8952 fs.write(file.fd, result.pdfArrayBuffer().buffer).then((writeLen: number) => { 8953 console.info("createPDF write data to file succeed and size is:" + writeLen); 8954 }).catch((err: BusinessError) => { 8955 console.error("createPDF write data to file failed with error message: " + err.message + 8956 ", error code: " + err.code); 8957 }).finally(() => { 8958 fs.closeSync(file); 8959 }); 8960 } catch (resError) { 8961 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8962 } 8963 }); 8964 }) 8965 Web({ src: "www.example.com", controller: this.controller }) 8966 } 8967 } 8968} 8969``` 8970 8971### createPdf<sup>14+</sup> 8972 8973createPdf(configuration: PdfConfiguration): Promise\<PdfData\> 8974 8975Obtains the data stream of a specified web page using a promise. 8976 8977**System capability**: SystemCapability.Web.Webview.Core 8978 8979**Parameters** 8980 8981| Name | Type | Mandatory| Description | 8982| ------------- | --------------------------------------- | ---- | ----------------- | 8983| configuration | [PdfConfiguration](#pdfconfiguration14) | Yes | Parameters required for creating a PDF file.| 8984 8985**Return value** 8986 8987| Type | Description | 8988| ------------------------------ | ----------------------------- | 8989| Promise<[PdfData](#pdfdata14)> | Promise used to return the data stream of a web page.| 8990 8991**Error codes** 8992 8993For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8994 8995| ID| Error Message | 8996| -------- | ------------------------------------------------------------ | 8997| 401 | Invalid input parameter. | 8998| 17100001 | Init error. The WebviewController must be associated with a Web component. | 8999 9000**Example** 9001 9002```ts 9003import { fileIo as fs } from '@kit.CoreFileKit'; 9004import { webview } from '@kit.ArkWeb'; 9005import { BusinessError } from '@kit.BasicServicesKit'; 9006import { common } from '@kit.AbilityKit'; 9007 9008@Entry 9009@Component 9010struct Index { 9011 controller: webview.WebviewController = new webview.WebviewController(); 9012 pdfConfig: webview.PdfConfiguration = { 9013 width: 8.27, 9014 height: 11.69, 9015 marginTop: 0, 9016 marginBottom: 0, 9017 marginRight: 0, 9018 marginLeft: 0, 9019 shouldPrintBackground: true 9020 } 9021 9022 build() { 9023 Column() { 9024 Button('SavePDF') 9025 .onClick(() => { 9026 this.controller.createPdf(this.pdfConfig) 9027 .then((result: webview.PdfData) => { 9028 try { 9029 // Obtain the component context. 9030 let context = getContext(this) as common.UIAbilityContext; 9031 // Obtain the sandbox path and set the PDF file name. 9032 let filePath = context.filesDir + "/test.pdf"; 9033 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 9034 fs.write(file.fd, result.pdfArrayBuffer().buffer).then((writeLen: number) => { 9035 console.info("createPDF write data to file succeed and size is:" + writeLen); 9036 }).catch((err: BusinessError) => { 9037 console.error("createPDF write data to file failed with error message: " + err.message + 9038 ", error code: " + err.code); 9039 }).finally(() => { 9040 fs.closeSync(file); 9041 }); 9042 } catch (resError) { 9043 console.error(`ErrorCode: ${(resError as BusinessError).code}, Message: ${(resError as BusinessError).message}`); 9044 } 9045 }) 9046 }) 9047 Web({ src: "www.example.com", controller: this.controller }) 9048 } 9049 } 9050} 9051``` 9052 9053### getScrollOffset<sup>13+</sup> 9054 9055getScrollOffset(): ScrollOffset 9056 9057Obtains the current scrolling offset of a web page. 9058 9059**System capability**: SystemCapability.Web.Webview.Core 9060 9061**Return value** 9062 9063| Type | Description | 9064| :------------------------------ | ---------------------- | 9065| [ScrollOffset](#scrolloffset13) | Current scrolling offset of the web page.| 9066 9067**Example** 9068 9069```ts 9070import { webview } from '@kit.ArkWeb'; 9071import { componentUtils } from '@kit.ArkUI'; 9072 9073@Entry 9074@Component 9075struct WebComponent { 9076 @State testTitle: string = 'webScroll' 9077 controller: webview.WebviewController = new webview.WebviewController(); 9078 @State controllerX: number =-100; 9079 @State controllerY: number =-100; 9080 @State mode: OverScrollMode = OverScrollMode.ALWAYS; 9081 9082 build() { 9083 Column() { 9084 Row() { 9085 Text(this.testTitle) 9086 .fontSize(30) 9087 .fontWeight(FontWeight.Bold) 9088 .margin(5) 9089 } 9090 Column() { 9091 Text(`controllerX: ${this.controllerX}, controllerY: ${this.controllerY}`) 9092 } 9093 .margin({ top: 10, bottom: 10 }) 9094 Web({ src: $rawfile("scrollByTo.html"), controller: this.controller }) 9095 .key("web_01") 9096 .overScrollMode(this.mode) 9097 .onTouch((event) => { 9098 this.controllerX = this.controller.getScrollOffset().x; 9099 this.controllerY = this.controller.getScrollOffset().y; 9100 let componentInfo = componentUtils.getRectangleById("web_01"); 9101 let webHeight = px2vp(componentInfo.size.height); 9102 let pageHeight = this.controller.getPageHeight(); 9103 if (this.controllerY < 0) { 9104 // Case 1: When a web page is scrolled down, use ScrollOffset.y directly. 9105 console.log(`get downwards overscroll offsetY = ${this.controllerY}`); 9106 } else if ((this.controllerY != 0) && (this.controllerY > (pageHeight - webHeight))) { 9107 // 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. 9108 console.log(`get upwards overscroll offsetY = ${this.controllerY - (pageHeight >= webHeight ? (pageHeight - webHeight) : 0)}`); 9109 } else { 9110 // Case 3: If the web page is not scrolled, use ScrollOffset.y directly. 9111 console.log(`get scroll offsetY = ${this.controllerY}`); 9112 } 9113 }) 9114 .height(600) 9115 } 9116 .width('100%') 9117 .height('100%') 9118 } 9119} 9120``` 9121 9122## WebCookieManager 9123 9124Implements a **WebCookieManager** instance to manage behavior of cookies in **Web** components. All **Web** components in an application share a **WebCookieManager** instance. 9125 9126### getCookie<sup>(deprecated)</sup> 9127 9128static getCookie(url: string): string 9129 9130Obtains the cookie value of the specified URL. 9131 9132> **NOTE** 9133> 9134> This API is supported since API version 9 and deprecated since API version 11. You are advised to use [fetchCookieSync](#fetchcookiesync11) instead. 9135 9136**System capability**: SystemCapability.Web.Webview.Core 9137 9138**Parameters** 9139 9140| Name| Type | Mandatory| Description | 9141| ------ | ------ | ---- | :------------------------ | 9142| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 9143 9144**Return value** 9145 9146| Type | Description | 9147| ------ | ------------------------- | 9148| string | Cookie value corresponding to the specified URL.| 9149 9150**Error codes** 9151 9152For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9153 9154| ID| Error Message | 9155| -------- | ------------------------------------------------------ | 9156| 17100002 | Invalid url. | 9157| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 9158 9159**Example** 9160 9161```ts 9162// xxx.ets 9163import { webview } from '@kit.ArkWeb'; 9164import { BusinessError } from '@kit.BasicServicesKit'; 9165 9166@Entry 9167@Component 9168struct WebComponent { 9169 controller: webview.WebviewController = new webview.WebviewController(); 9170 9171 build() { 9172 Column() { 9173 Button('getCookie') 9174 .onClick(() => { 9175 try { 9176 let value = webview.WebCookieManager.getCookie('https://www.example.com'); 9177 console.log("value: " + value); 9178 } catch (error) { 9179 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9180 } 9181 }) 9182 Web({ src: 'www.example.com', controller: this.controller }) 9183 } 9184 } 9185} 9186``` 9187 9188### fetchCookieSync<sup>11+</sup> 9189 9190static fetchCookieSync(url: string, incognito?: boolean): string 9191 9192Obtains the cookie value of the specified URL. 9193 9194> **NOTE** 9195> 9196> The system automatically deletes expired cookies. For data with the same key name, the new data overwrites the previous data. 9197> 9198> To obtain the cookie value that can be used, pass a complete link to **fetchCookieSync()**. 9199> 9200> **fetchCookieSync()** is used to obtain all cookie values. Cookie values are separated by semicolons (;). However, a specific cookie value cannot be obtained separately. 9201 9202**System capability**: SystemCapability.Web.Webview.Core 9203 9204**Parameters** 9205 9206| Name| Type | Mandatory| Description | 9207| ------ | ------ | ---- | :------------------------ | 9208| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 9209| 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.| 9210 9211**Return value** 9212 9213| Type | Description | 9214| ------ | ------------------------- | 9215| string | Cookie value corresponding to the specified URL.| 9216 9217**Error codes** 9218 9219For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9220 9221| ID| Error Message | 9222| -------- | ------------------------------------------------------ | 9223| 17100002 | Invalid url. | 9224| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9225 9226**Example** 9227 9228```ts 9229// xxx.ets 9230import { webview } from '@kit.ArkWeb'; 9231import { BusinessError } from '@kit.BasicServicesKit'; 9232 9233@Entry 9234@Component 9235struct WebComponent { 9236 controller: webview.WebviewController = new webview.WebviewController(); 9237 9238 build() { 9239 Column() { 9240 Button('fetchCookieSync') 9241 .onClick(() => { 9242 try { 9243 let value = webview.WebCookieManager.fetchCookieSync('https://www.example.com'); 9244 console.log("fetchCookieSync cookie = " + value); 9245 } catch (error) { 9246 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9247 } 9248 }) 9249 Web({ src: 'www.example.com', controller: this.controller }) 9250 } 9251 } 9252} 9253``` 9254 9255### fetchCookie<sup>11+</sup> 9256 9257static fetchCookie(url: string, callback: AsyncCallback\<string>): void 9258 9259Obtains the cookie value of a specified URL. This API uses an asynchronous callback to return the result. 9260 9261**System capability**: SystemCapability.Web.Webview.Core 9262 9263**Parameters** 9264 9265| Name| Type | Mandatory| Description | 9266| ------ | ------ | ---- | :------------------------ | 9267| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 9268| callback | AsyncCallback\<string> | Yes| Callback used to return the result.| 9269 9270**Error codes** 9271 9272For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9273 9274| ID| Error Message | 9275| -------- | ------------------------------------------------------ | 9276| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9277| 17100002 | Invalid url. | 9278 9279**Example** 9280 9281```ts 9282// xxx.ets 9283import { webview } from '@kit.ArkWeb'; 9284import { BusinessError } from '@kit.BasicServicesKit'; 9285 9286@Entry 9287@Component 9288struct WebComponent { 9289 controller: webview.WebviewController = new webview.WebviewController(); 9290 9291 build() { 9292 Column() { 9293 Button('fetchCookie') 9294 .onClick(() => { 9295 try { 9296 webview.WebCookieManager.fetchCookie('https://www.example.com', (error, cookie) => { 9297 if (error) { 9298 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9299 return; 9300 } 9301 if (cookie) { 9302 console.log('fetchCookie cookie = ' + cookie); 9303 } 9304 }) 9305 } catch (error) { 9306 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9307 } 9308 }) 9309 Web({ src: 'www.example.com', controller: this.controller }) 9310 } 9311 } 9312} 9313``` 9314 9315### fetchCookie<sup>11+</sup> 9316 9317static fetchCookie(url: string): Promise\<string> 9318 9319Obtains the cookie value of a specified URL. This API uses a promise to return the result. 9320 9321**System capability**: SystemCapability.Web.Webview.Core 9322 9323**Parameters** 9324 9325| Name| Type | Mandatory| Description | 9326| ------ | ------ | ---- | :------------------------ | 9327| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 9328 9329**Return value** 9330 9331| Type | Description | 9332| ------ | ------------------------- | 9333| Promise\<string> | Promise used to return the result.| 9334 9335**Error codes** 9336 9337For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9338 9339| ID| Error Message | 9340| -------- | ------------------------------------------------------ | 9341| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9342| 17100002 | Invalid url. | 9343 9344**Example** 9345 9346```ts 9347// xxx.ets 9348import { webview } from '@kit.ArkWeb'; 9349import { BusinessError } from '@kit.BasicServicesKit'; 9350 9351@Entry 9352@Component 9353struct WebComponent { 9354 controller: webview.WebviewController = new webview.WebviewController(); 9355 9356 build() { 9357 Column() { 9358 Button('fetchCookie') 9359 .onClick(() => { 9360 try { 9361 webview.WebCookieManager.fetchCookie('https://www.example.com') 9362 .then(cookie => { 9363 console.log("fetchCookie cookie = " + cookie); 9364 }) 9365 .catch((error: BusinessError) => { 9366 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 9367 }) 9368 } catch (error) { 9369 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9370 } 9371 }) 9372 Web({ src: 'www.example.com', controller: this.controller }) 9373 } 9374 } 9375} 9376``` 9377 9378### fetchCookie<sup>14+</sup> 9379 9380static fetchCookie(url: string, incognito: boolean): Promise\<string> 9381 9382Obtains the cookie value of a specified URL. This API uses a promise to return the result. 9383 9384**System capability**: SystemCapability.Web.Webview.Core 9385 9386**Parameters** 9387 9388| Name| Type | Mandatory| Description | 9389| ------ | ------ | ---- | :------------------------ | 9390| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 9391| 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.| 9392 9393**Return value** 9394 9395| Type | Description | 9396| ------ | ------------------------- | 9397| Promise\<string> | Promise used to return the result.| 9398 9399**Error codes** 9400 9401For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9402 9403| ID| Error Message | 9404| -------- | ------------------------------------------------------ | 9405| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9406| 17100002 | Invalid url. | 9407 9408**Example** 9409 9410```ts 9411// xxx.ets 9412import { webview } from '@kit.ArkWeb'; 9413import { BusinessError } from '@kit.BasicServicesKit'; 9414 9415@Entry 9416@Component 9417struct WebComponent { 9418 controller: webview.WebviewController = new webview.WebviewController(); 9419 9420 build() { 9421 Column() { 9422 Button('fetchCookie') 9423 .onClick(() => { 9424 try { 9425 webview.WebCookieManager.fetchCookie('https://www.example.com', false) 9426 .then(cookie => { 9427 console.log("fetchCookie cookie = " + cookie); 9428 }) 9429 .catch((error: BusinessError) => { 9430 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 9431 }) 9432 } catch (error) { 9433 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9434 } 9435 }) 9436 Web({ src: 'www.example.com', controller: this.controller }) 9437 } 9438 } 9439} 9440``` 9441 9442### setCookie<sup>(deprecated)</sup> 9443 9444static setCookie(url: string, value: string): void 9445 9446Sets a cookie for the specified URL. 9447 9448> **NOTE** 9449> 9450> 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. 9451 9452**System capability**: SystemCapability.Web.Webview.Core 9453 9454**Parameters** 9455 9456| Name| Type | Mandatory| Description | 9457| ------ | ------ | ---- | :------------------------ | 9458| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 9459| value | string | Yes | Cookie value to set. | 9460 9461**Error codes** 9462 9463For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9464 9465| ID| Error Message | 9466| -------- | ------------------------------------------------------ | 9467| 17100002 | Invalid url. | 9468| 17100005 | Invalid cookie value. | 9469| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9470 9471**Example** 9472 9473```ts 9474// xxx.ets 9475import { webview } from '@kit.ArkWeb'; 9476import { BusinessError } from '@kit.BasicServicesKit'; 9477 9478@Entry 9479@Component 9480struct WebComponent { 9481 controller: webview.WebviewController = new webview.WebviewController(); 9482 9483 build() { 9484 Column() { 9485 Button('setCookie') 9486 .onClick(() => { 9487 try { 9488 webview.WebCookieManager.setCookie('https://www.example.com', 'a=b'); 9489 } catch (error) { 9490 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9491 } 9492 }) 9493 Web({ src: 'www.example.com', controller: this.controller }) 9494 } 9495 } 9496} 9497``` 9498 9499### configCookieSync<sup>11+</sup> 9500 9501static configCookieSync(url: string, value: string, incognito?: boolean): void 9502 9503Sets a cookie for the specified URL. 9504 9505> **NOTE** 9506> 9507> You can set **url** in **configCookieSync** to a domain name so that the cookie is attached to the requests on the page. 9508> 9509> It is recommended that cookie syncing be completed before the **Web** component is loaded. 9510> 9511> If **configCookieSync()** is used to set cookies for two or more times, the cookies set each time are separated by semicolons (;). 9512 9513**System capability**: SystemCapability.Web.Webview.Core 9514 9515**Parameters** 9516 9517| Name| Type | Mandatory| Description | 9518| ------ | ------ | ---- | :------------------------ | 9519| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 9520| value | string | Yes | Cookie value to set. | 9521| 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.| 9522 9523**Error codes** 9524 9525For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9526 9527| ID| Error Message | 9528| -------- | ------------------------------------------------------ | 9529| 17100002 | Invalid url. | 9530| 17100005 | Invalid cookie value. | 9531| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9532 9533**Example** 9534 9535```ts 9536// xxx.ets 9537import { webview } from '@kit.ArkWeb'; 9538import { BusinessError } from '@kit.BasicServicesKit'; 9539 9540@Entry 9541@Component 9542struct WebComponent { 9543 controller: webview.WebviewController = new webview.WebviewController(); 9544 9545 build() { 9546 Column() { 9547 Button('configCookieSync') 9548 .onClick(() => { 9549 try { 9550 // Only one cookie value can be set in configCookieSync at a time. 9551 webview.WebCookieManager.configCookieSync('https://www.example.com', 'a=b'); 9552 } catch (error) { 9553 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9554 } 9555 }) 9556 Web({ src: 'www.example.com', controller: this.controller }) 9557 } 9558 } 9559} 9560``` 9561 9562### configCookieSync<sup>14+</sup> 9563 9564static configCookieSync(url: string, value: string, incognito: boolean, includeHttpOnly: boolean): void 9565 9566Sets the cookie value for the specified URL. 9567 9568**System capability**: SystemCapability.Web.Webview.Core 9569 9570**Parameters** 9571 9572| Name| Type | Mandatory| Description | 9573| ------ | ------ | ---- | :------------------------ | 9574| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 9575| value | string | Yes | Cookie value to set. | 9576| 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.| 9577| includeHttpOnly | boolean | Yes | Whether to overwrite cookies containing **HttpOnly**. The value **true** means to overwrite cookies containing **HttpOnly**, and **false** means the opposite.| 9578 9579**Error codes** 9580 9581For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9582 9583| ID| Error Message | 9584| -------- | ------------------------------------------------------ | 9585| 17100002 | Invalid url. | 9586| 17100005 | Invalid cookie value. | 9587| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9588 9589**Example** 9590 9591```ts 9592// xxx.ets 9593import { webview } from '@kit.ArkWeb'; 9594import { BusinessError } from '@kit.BasicServicesKit'; 9595 9596@Entry 9597@Component 9598struct WebComponent { 9599 controller: webview.WebviewController = new webview.WebviewController(); 9600 9601 build() { 9602 Column() { 9603 Button('configCookieSync') 9604 .onClick(() => { 9605 try { 9606 // Only a single cookie value can be set. 9607 webview.WebCookieManager.configCookieSync('https://www.example.com', 'a=b', false, false); 9608 } catch (error) { 9609 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9610 } 9611 }) 9612 Web({ src: 'www.example.com', controller: this.controller }) 9613 } 9614 } 9615} 9616``` 9617 9618### configCookie<sup>11+</sup> 9619 9620static configCookie(url: string, value: string, callback: AsyncCallback\<void>): void 9621 9622Sets the value of a single cookie for a specified URL. This API uses an asynchronous callback to return the result. 9623 9624**System capability**: SystemCapability.Web.Webview.Core 9625 9626**Parameters** 9627 9628| Name| Type | Mandatory| Description | 9629| ------ | ------ | ---- | :------------------------ | 9630| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 9631| value | string | Yes | Cookie value to set. | 9632| callback | AsyncCallback\<void> | Yes| Callback used to return the result.| 9633 9634**Error codes** 9635 9636For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9637 9638| ID| Error Message | 9639| -------- | ------------------------------------------------------ | 9640| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9641| 17100002 | Invalid url. | 9642| 17100005 | Invalid cookie value. | 9643 9644**Example** 9645 9646```ts 9647// xxx.ets 9648import { webview } from '@kit.ArkWeb'; 9649import { BusinessError } from '@kit.BasicServicesKit'; 9650 9651@Entry 9652@Component 9653struct WebComponent { 9654 controller: webview.WebviewController = new webview.WebviewController(); 9655 9656 build() { 9657 Column() { 9658 Button('configCookie') 9659 .onClick(() => { 9660 try { 9661 webview.WebCookieManager.configCookie('https://www.example.com', "a=b", (error) => { 9662 if (error) { 9663 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9664 } 9665 }) 9666 } catch (error) { 9667 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9668 } 9669 }) 9670 Web({ src: 'www.example.com', controller: this.controller }) 9671 } 9672 } 9673} 9674``` 9675 9676### configCookie<sup>11+</sup> 9677 9678static configCookie(url: string, value: string): Promise\<void> 9679 9680Sets the value of a single cookie for a specified URL. This API uses a promise to return the result. 9681 9682**System capability**: SystemCapability.Web.Webview.Core 9683 9684**Parameters** 9685 9686| Name| Type | Mandatory| Description | 9687| ------ | ------ | ---- | :------------------------ | 9688| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 9689| value | string | Yes | Cookie value to set. | 9690 9691**Return value** 9692 9693| Type | Description | 9694| ------ | ------------------------- | 9695| Promise\<void> | Promise used to return the result.| 9696 9697**Error codes** 9698 9699For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9700 9701| ID| Error Message | 9702| -------- | ------------------------------------------------------ | 9703| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9704| 17100002 | Invalid url. | 9705| 17100005 | Invalid cookie value. | 9706 9707**Example** 9708 9709```ts 9710// xxx.ets 9711import { webview } from '@kit.ArkWeb'; 9712import { BusinessError } from '@kit.BasicServicesKit'; 9713 9714@Entry 9715@Component 9716struct WebComponent { 9717 controller: webview.WebviewController = new webview.WebviewController(); 9718 9719 build() { 9720 Column() { 9721 Button('configCookie') 9722 .onClick(() => { 9723 try { 9724 webview.WebCookieManager.configCookie('https://www.example.com', 'a=b') 9725 .then(() => { 9726 console.log('configCookie success!'); 9727 }) 9728 .catch((error: BusinessError) => { 9729 console.log('error: ' + JSON.stringify(error)); 9730 }) 9731 } catch (error) { 9732 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9733 } 9734 }) 9735 Web({ src: 'www.example.com', controller: this.controller }) 9736 } 9737 } 9738} 9739``` 9740 9741### configCookie<sup>14+</sup> 9742 9743static configCookie(url: string, value: string, incognito: boolean, includeHttpOnly: boolean): Promise\<void> 9744 9745Sets the value of a single cookie for a specified URL. This API uses a promise to return the result. 9746 9747**System capability**: SystemCapability.Web.Webview.Core 9748 9749**Parameters** 9750 9751| Name| Type | Mandatory| Description | 9752| ------ | ------ | ---- | :------------------------ | 9753| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 9754| value | string | Yes | Cookie value to set. | 9755| 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.| 9756| includeHttpOnly | boolean | Yes | Whether to overwrite cookies containing **HttpOnly**. The value **true** means to overwrite cookies containing **HttpOnly**, and **false** means the opposite.| 9757 9758**Return value** 9759 9760| Type | Description | 9761| ------ | ------------------------- | 9762| Promise\<void> | Promise used to return the result.| 9763 9764**Error codes** 9765 9766For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9767 9768| ID| Error Message | 9769| -------- | ------------------------------------------------------ | 9770| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9771| 17100002 | Invalid url. | 9772| 17100005 | Invalid cookie value. | 9773 9774**Example** 9775 9776```ts 9777// xxx.ets 9778import { webview } from '@kit.ArkWeb'; 9779import { BusinessError } from '@kit.BasicServicesKit'; 9780 9781@Entry 9782@Component 9783struct WebComponent { 9784 controller: webview.WebviewController = new webview.WebviewController(); 9785 9786 build() { 9787 Column() { 9788 Button('configCookie') 9789 .onClick(() => { 9790 try { 9791 webview.WebCookieManager.configCookie('https://www.example.com', 'a=b', false, false) 9792 .then(() => { 9793 console.log('configCookie success!'); 9794 }) 9795 .catch((error: BusinessError) => { 9796 console.log('error: ' + JSON.stringify(error)); 9797 }) 9798 } catch (error) { 9799 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9800 } 9801 }) 9802 Web({ src: 'www.example.com', controller: this.controller }) 9803 } 9804 } 9805} 9806``` 9807 9808### saveCookieSync<sup>16+</sup> 9809 9810static saveCookieSync(): void 9811 9812Saves the cookies in the memory to the drive. This API uses a synchronous callback to return the result. 9813 9814**System capability**: SystemCapability.Web.Webview.Core 9815 9816> **Description** 9817> 9818> **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. 9819 9820**Example** 9821 9822```ts 9823// xxx.ets 9824import { webview } from '@kit.ArkWeb'; 9825import { BusinessError } from '@kit.BasicServicesKit'; 9826 9827@Entry 9828@Component 9829struct WebComponent { 9830 controller: webview.WebviewController = new webview.WebviewController(); 9831 9832 build() { 9833 Column() { 9834 Button('saveCookieSync') 9835 .onClick(() => { 9836 try { 9837 webview.WebCookieManager.saveCookieSync(); 9838 } catch (error) { 9839 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9840 } 9841 }) 9842 Web({ src: 'www.example.com', controller: this.controller }) 9843 } 9844 } 9845} 9846``` 9847 9848### saveCookieAsync 9849 9850static saveCookieAsync(callback: AsyncCallback\<void>): void 9851 9852Saves the cookies in the memory to the drive. This API uses an asynchronous callback to return the result. 9853 9854**System capability**: SystemCapability.Web.Webview.Core 9855 9856**Parameters** 9857 9858| Name | Type | Mandatory| Description | 9859| -------- | ---------------------- | ---- | :------------------------------------------------- | 9860| callback | AsyncCallback\<void> | Yes | Callback used to return whether the cookies are successfully saved.| 9861 9862**Error codes** 9863 9864For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9865 9866| ID| Error Message | 9867| -------- | ------------------------------------------------------ | 9868| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 9869 9870**Example** 9871 9872```ts 9873// xxx.ets 9874import { webview } from '@kit.ArkWeb'; 9875import { BusinessError } from '@kit.BasicServicesKit'; 9876 9877@Entry 9878@Component 9879struct WebComponent { 9880 controller: webview.WebviewController = new webview.WebviewController(); 9881 9882 build() { 9883 Column() { 9884 Button('saveCookieAsync') 9885 .onClick(() => { 9886 try { 9887 webview.WebCookieManager.saveCookieAsync((error) => { 9888 if (error) { 9889 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9890 } 9891 }) 9892 } catch (error) { 9893 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9894 } 9895 }) 9896 Web({ src: 'www.example.com', controller: this.controller }) 9897 } 9898 } 9899} 9900``` 9901 9902### saveCookieAsync 9903 9904static saveCookieAsync(): Promise\<void> 9905 9906Saves the cookies in the memory to the drive. This API uses a promise to return the result. 9907 9908**System capability**: SystemCapability.Web.Webview.Core 9909 9910**Return value** 9911 9912| Type | Description | 9913| ---------------- | ----------------------------------------- | 9914| Promise\<void> | Promise used to return the operation result.| 9915 9916**Error codes** 9917 9918For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9919 9920| ID| Error Message | 9921| -------- | ------------------------------------------------------ | 9922| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 9923 9924**Example** 9925 9926```ts 9927// xxx.ets 9928import { webview } from '@kit.ArkWeb'; 9929import { BusinessError } from '@kit.BasicServicesKit'; 9930 9931@Entry 9932@Component 9933struct WebComponent { 9934 controller: webview.WebviewController = new webview.WebviewController(); 9935 9936 build() { 9937 Column() { 9938 Button('saveCookieAsync') 9939 .onClick(() => { 9940 try { 9941 webview.WebCookieManager.saveCookieAsync() 9942 .then(() => { 9943 console.log("saveCookieAsyncCallback success!"); 9944 }) 9945 .catch((error: BusinessError) => { 9946 console.error("error: " + error); 9947 }); 9948 } catch (error) { 9949 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9950 } 9951 }) 9952 Web({ src: 'www.example.com', controller: this.controller }) 9953 } 9954 } 9955} 9956``` 9957 9958### putAcceptCookieEnabled 9959 9960static putAcceptCookieEnabled(accept: boolean): void 9961 9962Sets whether the **WebCookieManager** instance has the permission to send and receive cookies. 9963 9964**System capability**: SystemCapability.Web.Webview.Core 9965 9966**Parameters** 9967 9968| Name| Type | Mandatory| Description | 9969| ------ | ------- | ---- | :----------------------------------- | 9970| accept | boolean | Yes | Whether the **WebCookieManager** instance has the permission to send and receive cookies.<br>Default value: **true**| 9971 9972**Error codes** 9973 9974For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9975 9976| ID| Error Message | 9977| -------- | ------------------------------------------------------ | 9978| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 9979 9980**Example** 9981 9982```ts 9983// xxx.ets 9984import { webview } from '@kit.ArkWeb'; 9985import { BusinessError } from '@kit.BasicServicesKit'; 9986 9987@Entry 9988@Component 9989struct WebComponent { 9990 controller: webview.WebviewController = new webview.WebviewController(); 9991 9992 build() { 9993 Column() { 9994 Button('putAcceptCookieEnabled') 9995 .onClick(() => { 9996 try { 9997 webview.WebCookieManager.putAcceptCookieEnabled(false); 9998 } catch (error) { 9999 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10000 } 10001 }) 10002 Web({ src: 'www.example.com', controller: this.controller }) 10003 } 10004 } 10005} 10006``` 10007 10008### isCookieAllowed 10009 10010static isCookieAllowed(): boolean 10011 10012Checks whether the **WebCookieManager** instance has the permission to send and receive cookies. 10013 10014**System capability**: SystemCapability.Web.Webview.Core 10015 10016**Return value** 10017 10018| Type | Description | 10019| ------- | -------------------------------- | 10020| boolean | Whether the **WebCookieManager** instance has the permission to send and receive cookies. The default value is **true**.| 10021 10022**Example** 10023 10024```ts 10025// xxx.ets 10026import { webview } from '@kit.ArkWeb'; 10027 10028@Entry 10029@Component 10030struct WebComponent { 10031 controller: webview.WebviewController = new webview.WebviewController(); 10032 10033 build() { 10034 Column() { 10035 Button('isCookieAllowed') 10036 .onClick(() => { 10037 let result = webview.WebCookieManager.isCookieAllowed(); 10038 console.log("result: " + result); 10039 }) 10040 Web({ src: 'www.example.com', controller: this.controller }) 10041 } 10042 } 10043} 10044``` 10045 10046### putAcceptThirdPartyCookieEnabled 10047 10048static putAcceptThirdPartyCookieEnabled(accept: boolean): void 10049 10050Sets whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. 10051 10052**System capability**: SystemCapability.Web.Webview.Core 10053 10054**Parameters** 10055 10056| Name| Type | Mandatory| Description | 10057| ------ | ------- | ---- | :----------------------------------------- | 10058| accept | boolean | Yes | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies.<br>Default value: **false**| 10059 10060**Error codes** 10061 10062For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10063 10064| ID| Error Message | 10065| -------- | ------------------------------------------------------ | 10066| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10067 10068**Example** 10069 10070```ts 10071// xxx.ets 10072import { webview } from '@kit.ArkWeb'; 10073import { BusinessError } from '@kit.BasicServicesKit'; 10074 10075@Entry 10076@Component 10077struct WebComponent { 10078 controller: webview.WebviewController = new webview.WebviewController(); 10079 10080 build() { 10081 Column() { 10082 Button('putAcceptThirdPartyCookieEnabled') 10083 .onClick(() => { 10084 try { 10085 webview.WebCookieManager.putAcceptThirdPartyCookieEnabled(false); 10086 } catch (error) { 10087 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10088 } 10089 }) 10090 Web({ src: 'www.example.com', controller: this.controller }) 10091 } 10092 } 10093} 10094``` 10095 10096### isThirdPartyCookieAllowed 10097 10098static isThirdPartyCookieAllowed(): boolean 10099 10100Checks whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. 10101 10102**System capability**: SystemCapability.Web.Webview.Core 10103 10104**Return value** 10105 10106| Type | Description | 10107| ------- | -------------------------------------- | 10108| boolean | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. The default value is **false**.| 10109 10110**Example** 10111 10112```ts 10113// xxx.ets 10114import { webview } from '@kit.ArkWeb'; 10115 10116@Entry 10117@Component 10118struct WebComponent { 10119 controller: webview.WebviewController = new webview.WebviewController(); 10120 10121 build() { 10122 Column() { 10123 Button('isThirdPartyCookieAllowed') 10124 .onClick(() => { 10125 let result = webview.WebCookieManager.isThirdPartyCookieAllowed(); 10126 console.log("result: " + result); 10127 }) 10128 Web({ src: 'www.example.com', controller: this.controller }) 10129 } 10130 } 10131} 10132``` 10133 10134### existCookie 10135 10136static existCookie(incognito?: boolean): boolean 10137 10138Checks whether cookies exist. 10139 10140**System capability**: SystemCapability.Web.Webview.Core 10141 10142**Parameters** 10143 10144| Name| Type | Mandatory| Description | 10145| ------ | ------- | ---- | :----------------------------------------- | 10146| 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.| 10147 10148**Return value** 10149 10150| Type | Description | 10151| ------- | -------------------------------------- | 10152| boolean | Whether cookies exist. The value **true** means that cookies exist, and **false** means the opposite.| 10153 10154**Example** 10155 10156```ts 10157// xxx.ets 10158import { webview } from '@kit.ArkWeb'; 10159 10160@Entry 10161@Component 10162struct WebComponent { 10163 controller: webview.WebviewController = new webview.WebviewController(); 10164 10165 build() { 10166 Column() { 10167 Button('existCookie') 10168 .onClick(() => { 10169 let result = webview.WebCookieManager.existCookie(); 10170 console.log("result: " + result); 10171 }) 10172 Web({ src: 'www.example.com', controller: this.controller }) 10173 } 10174 } 10175} 10176``` 10177 10178### deleteEntireCookie<sup>(deprecated)</sup> 10179 10180static deleteEntireCookie(): void 10181 10182Deletes all cookies. 10183 10184> **NOTE** 10185> 10186> This API is supported since API version 9 and deprecated since API version 11. You are advised to use [clearAllCookiesSync](#clearallcookiessync11) instead. 10187 10188**System capability**: SystemCapability.Web.Webview.Core 10189 10190**Example** 10191 10192```ts 10193// xxx.ets 10194import { webview } from '@kit.ArkWeb'; 10195 10196@Entry 10197@Component 10198struct WebComponent { 10199 controller: webview.WebviewController = new webview.WebviewController(); 10200 10201 build() { 10202 Column() { 10203 Button('deleteEntireCookie') 10204 .onClick(() => { 10205 webview.WebCookieManager.deleteEntireCookie(); 10206 }) 10207 Web({ src: 'www.example.com', controller: this.controller }) 10208 } 10209 } 10210} 10211``` 10212 10213### clearAllCookiesSync<sup>11+</sup> 10214 10215static clearAllCookiesSync(incognito?: boolean): void 10216 10217Deletes all cookies. 10218 10219**System capability**: SystemCapability.Web.Webview.Core 10220 10221**Parameters** 10222 10223| Name| Type | Mandatory| Description | 10224| ------ | ------- | ---- | :----------------------------------------- | 10225| 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.| 10226 10227**Example** 10228 10229```ts 10230// xxx.ets 10231import { webview } from '@kit.ArkWeb'; 10232 10233@Entry 10234@Component 10235struct WebComponent { 10236 controller: webview.WebviewController = new webview.WebviewController(); 10237 10238 build() { 10239 Column() { 10240 Button('clearAllCookiesSync') 10241 .onClick(() => { 10242 webview.WebCookieManager.clearAllCookiesSync(); 10243 }) 10244 Web({ src: 'www.example.com', controller: this.controller }) 10245 } 10246 } 10247} 10248``` 10249 10250### clearAllCookies<sup>11+</sup> 10251 10252static clearAllCookies(callback: AsyncCallback\<void>): void 10253 10254Clears all cookies. This API uses an asynchronous callback to return the result. 10255 10256**System capability**: SystemCapability.Web.Webview.Core 10257 10258**Parameters** 10259 10260| Name | Type | Mandatory| Description | 10261| -------- | ---------------------- | ---- | :------------------------------------------------- | 10262| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 10263 10264**Error codes** 10265 10266For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10267 10268| ID| Error Message | 10269| -------- | ------------------------------------------------------ | 10270| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 10271 10272**Example** 10273 10274```ts 10275// xxx.ets 10276import { webview } from '@kit.ArkWeb'; 10277import { BusinessError } from '@kit.BasicServicesKit'; 10278 10279@Entry 10280@Component 10281struct WebComponent { 10282 controller: webview.WebviewController = new webview.WebviewController(); 10283 10284 build() { 10285 Column() { 10286 Button('clearAllCookies') 10287 .onClick(() => { 10288 try { 10289 webview.WebCookieManager.clearAllCookies((error) => { 10290 if (error) { 10291 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10292 } 10293 }) 10294 } catch (error) { 10295 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10296 } 10297 }) 10298 Web({ src: 'www.example.com', controller: this.controller }) 10299 } 10300 } 10301} 10302``` 10303 10304### clearAllCookies<sup>11+</sup> 10305 10306static clearAllCookies(): Promise\<void> 10307 10308Clears all cookies. This API uses a promise to return the result. 10309 10310**System capability**: SystemCapability.Web.Webview.Core 10311 10312**Return value** 10313 10314| Type | Description | 10315| ---------------- | ----------------------------------------- | 10316| Promise\<void> | Promise used to return the result.| 10317 10318**Error codes** 10319 10320For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10321 10322| ID| Error Message | 10323| -------- | ------------------------------------------------------ | 10324| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 10325 10326**Example** 10327 10328```ts 10329// xxx.ets 10330import { webview } from '@kit.ArkWeb'; 10331import { BusinessError } from '@kit.BasicServicesKit'; 10332 10333@Entry 10334@Component 10335struct WebComponent { 10336 controller: webview.WebviewController = new webview.WebviewController(); 10337 10338 build() { 10339 Column() { 10340 Button('clearAllCookies') 10341 .onClick(() => { 10342 try { 10343 webview.WebCookieManager.clearAllCookies() 10344 .then(() => { 10345 console.log("clearAllCookies success!"); 10346 }) 10347 .catch((error: BusinessError) => { 10348 console.error("error: " + error); 10349 }); 10350 } catch (error) { 10351 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10352 } 10353 }) 10354 Web({ src: 'www.example.com', controller: this.controller }) 10355 } 10356 } 10357} 10358``` 10359 10360### deleteSessionCookie<sup>(deprecated)</sup> 10361 10362static deleteSessionCookie(): void 10363 10364Deletes all session cookies. 10365 10366> **NOTE** 10367> 10368> This API is supported since API version 9 and deprecated since API version 11. You are advised to use [clearSessionCookiesync](#clearsessioncookiesync11) instead. 10369 10370**System capability**: SystemCapability.Web.Webview.Core 10371 10372**Example** 10373 10374```ts 10375// xxx.ets 10376import { webview } from '@kit.ArkWeb'; 10377 10378@Entry 10379@Component 10380struct WebComponent { 10381 controller: webview.WebviewController = new webview.WebviewController(); 10382 10383 build() { 10384 Column() { 10385 Button('deleteSessionCookie') 10386 .onClick(() => { 10387 webview.WebCookieManager.deleteSessionCookie(); 10388 }) 10389 Web({ src: 'www.example.com', controller: this.controller }) 10390 } 10391 } 10392} 10393``` 10394 10395### clearSessionCookieSync<sup>11+</sup> 10396 10397static clearSessionCookieSync(): void 10398 10399Deletes all session cookies. 10400 10401**System capability**: SystemCapability.Web.Webview.Core 10402 10403**Example** 10404 10405```ts 10406// xxx.ets 10407import { webview } from '@kit.ArkWeb'; 10408 10409@Entry 10410@Component 10411struct WebComponent { 10412 controller: webview.WebviewController = new webview.WebviewController(); 10413 10414 build() { 10415 Column() { 10416 Button('clearSessionCookieSync') 10417 .onClick(() => { 10418 webview.WebCookieManager.clearSessionCookieSync(); 10419 }) 10420 Web({ src: 'www.example.com', controller: this.controller }) 10421 } 10422 } 10423} 10424``` 10425 10426### clearSessionCookie<sup>11+</sup> 10427 10428static clearSessionCookie(callback: AsyncCallback\<void>): void 10429 10430Clears all session cookies. This API uses an asynchronous callback to return the result. 10431 10432**System capability**: SystemCapability.Web.Webview.Core 10433 10434**Parameters** 10435 10436| Name | Type | Mandatory| Description | 10437| -------- | ---------------------- | ---- | :------------------------------------------------- | 10438| callback | AsyncCallback\<void> | Yes | Callback 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. 2. Incorrect parameter types. | 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('clearSessionCookie') 10463 .onClick(() => { 10464 try { 10465 webview.WebCookieManager.clearSessionCookie((error) => { 10466 if (error) { 10467 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10468 } 10469 }) 10470 } catch (error) { 10471 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10472 } 10473 }) 10474 Web({ src: 'www.example.com', controller: this.controller }) 10475 } 10476 } 10477} 10478``` 10479 10480### clearSessionCookie<sup>11+</sup> 10481 10482static clearSessionCookie(): Promise\<void> 10483 10484Clears all session cookies. This API uses a promise to return the result. 10485 10486**System capability**: SystemCapability.Web.Webview.Core 10487 10488**Return value** 10489 10490| Type | Description | 10491| ---------------- | ----------------------------------------- | 10492| Promise\<void> | Promise used to return the result.| 10493 10494**Error codes** 10495 10496For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10497 10498| ID| Error Message | 10499| -------- | ------------------------------------------------------ | 10500| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 10501 10502**Example** 10503 10504```ts 10505// xxx.ets 10506import { webview } from '@kit.ArkWeb'; 10507import { BusinessError } from '@kit.BasicServicesKit'; 10508 10509@Entry 10510@Component 10511struct WebComponent { 10512 controller: webview.WebviewController = new webview.WebviewController(); 10513 10514 build() { 10515 Column() { 10516 Button('clearSessionCookie') 10517 .onClick(() => { 10518 try { 10519 webview.WebCookieManager.clearSessionCookie() 10520 .then(() => { 10521 console.log("clearSessionCookie success!"); 10522 }) 10523 .catch((error: BusinessError) => { 10524 console.error("error: " + error); 10525 }); 10526 } catch (error) { 10527 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10528 } 10529 }) 10530 Web({ src: 'www.example.com', controller: this.controller }) 10531 } 10532 } 10533} 10534``` 10535 10536## WebStorage 10537 10538Implements a **WebStorage** object to manage the Web SQL database and HTML5 Web Storage APIs. All **Web** components in an application share a **WebStorage** object. 10539 10540> **NOTE** 10541> 10542> You must load the **Web** component before calling the APIs in **WebStorage**. 10543 10544### deleteOrigin 10545 10546static deleteOrigin(origin: string): void 10547 10548Deletes all data in the specified origin. 10549 10550**System capability**: SystemCapability.Web.Webview.Core 10551 10552**Parameters** 10553 10554| Name| Type | Mandatory| Description | 10555| ------ | ------ | ---- | ------------------------ | 10556| origin | string | Yes | Index of the origin, which is obtained through [getOrigins](#getorigins).| 10557 10558**Error codes** 10559 10560For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10561 10562| ID| Error Message | 10563| -------- | ------------------------------------------------------ | 10564| 17100011 | Invalid origin. | 10565| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10566 10567**Example** 10568 10569```ts 10570// xxx.ets 10571import { webview } from '@kit.ArkWeb'; 10572import { BusinessError } from '@kit.BasicServicesKit'; 10573 10574@Entry 10575@Component 10576struct WebComponent { 10577 controller: webview.WebviewController = new webview.WebviewController(); 10578 origin: string = "resource://rawfile/"; 10579 10580 build() { 10581 Column() { 10582 Button('deleteOrigin') 10583 .onClick(() => { 10584 try { 10585 webview.WebStorage.deleteOrigin(this.origin); 10586 } catch (error) { 10587 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10588 } 10589 10590 }) 10591 Web({ src: $rawfile('index.html'), controller: this.controller }) 10592 .databaseAccess(true) 10593 } 10594 } 10595} 10596``` 10597 10598HTML file to be loaded: 10599 ```html 10600 <!-- index.html --> 10601 <!DOCTYPE html> 10602 <html> 10603 <head> 10604 <meta charset="UTF-8"> 10605 <title>test</title> 10606 <script type="text/javascript"> 10607 10608 var db = openDatabase('mydb','1.0','Test DB',2 * 1024 * 1024); 10609 var msg; 10610 10611 db.transaction(function(tx){ 10612 tx.executeSql('INSERT INTO LOGS (id,log) VALUES(1,"test1")'); 10613 tx.executeSql('INSERT INTO LOGS (id,log) VALUES(2,"test2")'); 10614 msg = '<p>Data table created, with two data records inserted.</p>'; 10615 10616 document.querySelector('#status').innerHTML = msg; 10617 }); 10618 10619 db.transaction(function(tx){ 10620 tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) { 10621 var len = results.rows.length,i; 10622 msg = "<p>Number of records: " + len + "</p>"; 10623 10624 document.querySelector('#status').innerHTML += msg; 10625 10626 for(i = 0; i < len; i++){ 10627 msg = "<p><b>" + results.rows.item(i).log + "</b></p>"; 10628 10629 document.querySelector('#status').innerHTML += msg; 10630 } 10631 },null); 10632 }); 10633 10634 </script> 10635 </head> 10636 <body> 10637 <div id="status" name="status">Status</div> 10638 </body> 10639 </html> 10640 ``` 10641 10642### getOrigins 10643 10644static getOrigins(callback: AsyncCallback\<Array\<WebStorageOrigin>>): void 10645 10646Obtains information about all origins that are currently using the Web SQL Database. This API uses an asynchronous callback to return the result. 10647 10648**System capability**: SystemCapability.Web.Webview.Core 10649 10650**Parameters** 10651 10652| Name | Type | Mandatory| Description | 10653| -------- | -------------------------------------- | ---- | ------------------------------------------------------ | 10654| callback | AsyncCallback\<Array\<[WebStorageOrigin](#webstorageorigin)>> | Yes | Callback used to return the information about the origins. For details, see [WebStorageOrigin](#webstorageorigin).| 10655 10656**Error codes** 10657 10658For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10659 10660| ID| Error Message | 10661| -------- | ------------------------------------------------------ | 10662| 17100012 | Invalid web storage origin. | 10663| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10664 10665**Example** 10666 10667```ts 10668// xxx.ets 10669import { webview } from '@kit.ArkWeb'; 10670import { BusinessError } from '@kit.BasicServicesKit'; 10671 10672@Entry 10673@Component 10674struct WebComponent { 10675 controller: webview.WebviewController = new webview.WebviewController(); 10676 10677 build() { 10678 Column() { 10679 Button('getOrigins') 10680 .onClick(() => { 10681 try { 10682 webview.WebStorage.getOrigins((error, origins) => { 10683 if (error) { 10684 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10685 return; 10686 } 10687 for (let i = 0; i < origins.length; i++) { 10688 console.log('origin: ' + origins[i].origin); 10689 console.log('usage: ' + origins[i].usage); 10690 console.log('quota: ' + origins[i].quota); 10691 } 10692 }) 10693 } catch (error) { 10694 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10695 } 10696 10697 }) 10698 Web({ src: $rawfile('index.html'), controller: this.controller }) 10699 .databaseAccess(true) 10700 } 10701 } 10702} 10703``` 10704 10705For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 10706 10707### getOrigins 10708 10709static getOrigins(): Promise\<Array\<WebStorageOrigin>> 10710 10711Obtains information about all origins that are currently using the Web SQL Database. This API uses a promise to return the result. 10712 10713**System capability**: SystemCapability.Web.Webview.Core 10714 10715**Return value** 10716 10717| Type | Description | 10718| -------------------------------- | ------------------------------------------------------------ | 10719| Promise\<Array\<[WebStorageOrigin](#webstorageorigin)>> | Promise used to return the information about the origins. For details, see [WebStorageOrigin](#webstorageorigin).| 10720 10721**Error codes** 10722 10723For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10724 10725| ID| Error Message | 10726| -------- | ------------------------------------------------------ | 10727| 17100012 | Invalid web storage origin. | 10728| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10729 10730**Example** 10731 10732```ts 10733// xxx.ets 10734import { webview } from '@kit.ArkWeb'; 10735import { BusinessError } from '@kit.BasicServicesKit'; 10736 10737@Entry 10738@Component 10739struct WebComponent { 10740 controller: webview.WebviewController = new webview.WebviewController(); 10741 10742 build() { 10743 Column() { 10744 Button('getOrigins') 10745 .onClick(() => { 10746 try { 10747 webview.WebStorage.getOrigins() 10748 .then(origins => { 10749 for (let i = 0; i < origins.length; i++) { 10750 console.log('origin: ' + origins[i].origin); 10751 console.log('usage: ' + origins[i].usage); 10752 console.log('quota: ' + origins[i].quota); 10753 } 10754 }) 10755 .catch((e: BusinessError) => { 10756 console.log('error: ' + JSON.stringify(e)); 10757 }) 10758 } catch (error) { 10759 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10760 } 10761 10762 }) 10763 Web({ src: $rawfile('index.html'), controller: this.controller }) 10764 .databaseAccess(true) 10765 } 10766 } 10767} 10768``` 10769 10770For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 10771 10772### getOriginQuota 10773 10774static getOriginQuota(origin: string, callback: AsyncCallback\<number>): void 10775 10776Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. 10777 10778**System capability**: SystemCapability.Web.Webview.Core 10779 10780**Parameters** 10781 10782| Name | Type | Mandatory| Description | 10783| -------- | --------------------- | ---- | ------------------ | 10784| origin | string | Yes | Index of the origin.| 10785| callback | AsyncCallback\<number> | Yes | Storage quota of the origin. | 10786 10787**Error codes** 10788 10789For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10790 10791| ID| Error Message | 10792| -------- | ------------------------------------------------------ | 10793| 17100011 | Invalid origin. | 10794| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10795 10796**Example** 10797 10798```ts 10799// xxx.ets 10800import { webview } from '@kit.ArkWeb'; 10801import { BusinessError } from '@kit.BasicServicesKit'; 10802 10803@Entry 10804@Component 10805struct WebComponent { 10806 controller: webview.WebviewController = new webview.WebviewController(); 10807 origin: string = "resource://rawfile/"; 10808 10809 build() { 10810 Column() { 10811 Button('getOriginQuota') 10812 .onClick(() => { 10813 try { 10814 webview.WebStorage.getOriginQuota(this.origin, (error, quota) => { 10815 if (error) { 10816 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10817 return; 10818 } 10819 console.log('quota: ' + quota); 10820 }) 10821 } catch (error) { 10822 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10823 } 10824 10825 }) 10826 Web({ src: $rawfile('index.html'), controller: this.controller }) 10827 .databaseAccess(true) 10828 } 10829 } 10830} 10831``` 10832 10833For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 10834 10835### getOriginQuota 10836 10837static getOriginQuota(origin: string): Promise\<number> 10838 10839Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. 10840 10841**System capability**: SystemCapability.Web.Webview.Core 10842 10843**Parameters** 10844 10845| Name| Type | Mandatory| Description | 10846| ------ | ------ | ---- | ------------------ | 10847| origin | string | Yes | Index of the origin.| 10848 10849**Return value** 10850 10851| Type | Description | 10852| --------------- | --------------------------------------- | 10853| Promise\<number> | Promise used to return the storage quota of the origin.| 10854 10855**Error codes** 10856 10857For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10858 10859| ID| Error Message | 10860| -------- | ------------------------------------------------------ | 10861| 17100011 | Invalid origin. | 10862| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10863 10864**Example** 10865 10866```ts 10867// xxx.ets 10868import { webview } from '@kit.ArkWeb'; 10869import { BusinessError } from '@kit.BasicServicesKit'; 10870 10871@Entry 10872@Component 10873struct WebComponent { 10874 controller: webview.WebviewController = new webview.WebviewController(); 10875 origin: string = "resource://rawfile/"; 10876 10877 build() { 10878 Column() { 10879 Button('getOriginQuota') 10880 .onClick(() => { 10881 try { 10882 webview.WebStorage.getOriginQuota(this.origin) 10883 .then(quota => { 10884 console.log('quota: ' + quota); 10885 }) 10886 .catch((e: BusinessError) => { 10887 console.log('error: ' + JSON.stringify(e)); 10888 }) 10889 } catch (error) { 10890 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10891 } 10892 10893 }) 10894 Web({ src: $rawfile('index.html'), controller: this.controller }) 10895 .databaseAccess(true) 10896 } 10897 } 10898} 10899``` 10900 10901For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 10902 10903### getOriginUsage 10904 10905static getOriginUsage(origin: string, callback: AsyncCallback\<number>): void 10906 10907Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. 10908 10909**System capability**: SystemCapability.Web.Webview.Core 10910 10911**Parameters** 10912 10913| Name | Type | Mandatory| Description | 10914| -------- | --------------------- | ---- | ------------------ | 10915| origin | string | Yes | Index of the origin.| 10916| callback | AsyncCallback\<number> | Yes | Storage usage of the origin. | 10917 10918**Error codes** 10919 10920For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10921 10922| ID| Error Message | 10923| -------- | ------------------------------------------------------ | 10924| 17100011 | Invalid origin. | 10925| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10926 10927**Example** 10928 10929```ts 10930// xxx.ets 10931import { webview } from '@kit.ArkWeb'; 10932import { BusinessError } from '@kit.BasicServicesKit'; 10933 10934@Entry 10935@Component 10936struct WebComponent { 10937 controller: webview.WebviewController = new webview.WebviewController(); 10938 origin: string = "resource://rawfile/"; 10939 10940 build() { 10941 Column() { 10942 Button('getOriginUsage') 10943 .onClick(() => { 10944 try { 10945 webview.WebStorage.getOriginUsage(this.origin, (error, usage) => { 10946 if (error) { 10947 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10948 return; 10949 } 10950 console.log('usage: ' + usage); 10951 }) 10952 } catch (error) { 10953 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10954 } 10955 10956 }) 10957 Web({ src: $rawfile('index.html'), controller: this.controller }) 10958 .databaseAccess(true) 10959 } 10960 } 10961} 10962``` 10963 10964For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 10965 10966### getOriginUsage 10967 10968static getOriginUsage(origin: string): Promise\<number> 10969 10970Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. 10971 10972**System capability**: SystemCapability.Web.Webview.Core 10973 10974**Parameters** 10975 10976| Name| Type | Mandatory| Description | 10977| ------ | ------ | ---- | ------------------ | 10978| origin | string | Yes | Index of the origin.| 10979 10980**Return value** 10981 10982| Type | Description | 10983| --------------- | ------------------------------------- | 10984| Promise\<number> | Promise used to return the storage usage of the origin.| 10985 10986**Error codes** 10987 10988For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10989 10990| ID| Error Message | 10991| -------- | ----------------------------------------------------- | 10992| 17100011 | Invalid origin. | 10993| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10994 10995**Example** 10996 10997```ts 10998// xxx.ets 10999import { webview } from '@kit.ArkWeb'; 11000import { BusinessError } from '@kit.BasicServicesKit'; 11001 11002@Entry 11003@Component 11004struct WebComponent { 11005 controller: webview.WebviewController = new webview.WebviewController(); 11006 origin: string = "resource://rawfile/"; 11007 11008 build() { 11009 Column() { 11010 Button('getOriginUsage') 11011 .onClick(() => { 11012 try { 11013 webview.WebStorage.getOriginUsage(this.origin) 11014 .then(usage => { 11015 console.log('usage: ' + usage); 11016 }).catch((e: BusinessError) => { 11017 console.error('error: ' + JSON.stringify(e)); 11018 }) 11019 } catch (error) { 11020 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11021 } 11022 }) 11023 Web({ src: $rawfile('index.html'), controller: this.controller }) 11024 .databaseAccess(true) 11025 } 11026 } 11027} 11028``` 11029 11030For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 11031 11032### deleteAllData 11033 11034static deleteAllData(incognito?: boolean): void 11035 11036Deletes all data in the Web SQL Database. 11037 11038**System capability**: SystemCapability.Web.Webview.Core 11039 11040**Parameters** 11041 11042| Name| Type | Mandatory| Description | 11043| ------ | ------ | ---- | ------------------ | 11044| 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.| 11045 11046**Example** 11047 11048```ts 11049// xxx.ets 11050import { webview } from '@kit.ArkWeb'; 11051import { BusinessError } from '@kit.BasicServicesKit'; 11052 11053@Entry 11054@Component 11055struct WebComponent { 11056 controller: webview.WebviewController = new webview.WebviewController(); 11057 11058 build() { 11059 Column() { 11060 Button('deleteAllData') 11061 .onClick(() => { 11062 try { 11063 webview.WebStorage.deleteAllData(); 11064 } catch (error) { 11065 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11066 } 11067 }) 11068 Web({ src: $rawfile('index.html'), controller: this.controller }) 11069 .databaseAccess(true) 11070 } 11071 } 11072} 11073``` 11074 11075For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 11076 11077## WebDataBase 11078 11079Implements a **WebDataBase** object. 11080 11081> **NOTE** 11082> 11083> You must load the **Web** component before calling the APIs in **WebDataBase**. 11084 11085### getHttpAuthCredentials 11086 11087static getHttpAuthCredentials(host: string, realm: string): Array\<string> 11088 11089Retrieves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. 11090 11091**System capability**: SystemCapability.Web.Webview.Core 11092 11093**Parameters** 11094 11095| Name| Type | Mandatory| Description | 11096| ------ | ------ | ---- | ---------------------------- | 11097| host | string | Yes | Host to which HTTP authentication credentials apply.| 11098| realm | string | Yes | Realm to which HTTP authentication credentials apply. | 11099 11100**Return value** 11101 11102| Type | Description | 11103| ----- | -------------------------------------------- | 11104| Array\<string> | Returns the array of the matching user names and passwords if the operation is successful; returns an empty array otherwise.| 11105 11106**Error codes** 11107 11108For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11109 11110| ID| Error Message | 11111| -------- | ------------------------------------------------------ | 11112| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11113 11114**Example** 11115 11116```ts 11117// xxx.ets 11118import { webview } from '@kit.ArkWeb'; 11119import { BusinessError } from '@kit.BasicServicesKit'; 11120 11121@Entry 11122@Component 11123struct WebComponent { 11124 controller: webview.WebviewController = new webview.WebviewController(); 11125 host: string = "www.spincast.org"; 11126 realm: string = "protected example"; 11127 username_password: string[] = []; 11128 11129 build() { 11130 Column() { 11131 Button('getHttpAuthCredentials') 11132 .onClick(() => { 11133 try { 11134 this.username_password = webview.WebDataBase.getHttpAuthCredentials(this.host, this.realm); 11135 console.log('num: ' + this.username_password.length); 11136 } catch (error) { 11137 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11138 } 11139 }) 11140 Web({ src: 'www.example.com', controller: this.controller }) 11141 } 11142 } 11143} 11144``` 11145 11146### saveHttpAuthCredentials 11147 11148static saveHttpAuthCredentials(host: string, realm: string, username: string, password: string): void 11149 11150Saves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. 11151 11152**System capability**: SystemCapability.Web.Webview.Core 11153 11154**Parameters** 11155 11156| Name | Type | Mandatory| Description | 11157| -------- | ------ | ---- | ---------------------------- | 11158| host | string | Yes | Host to which HTTP authentication credentials apply.| 11159| realm | string | Yes | Realm to which HTTP authentication credentials apply. | 11160| username | string | Yes | User name. | 11161| password | string | Yes | Password. | 11162 11163**Error codes** 11164 11165For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11166 11167| ID| Error Message | 11168| -------- | ------------------------------------------------------ | 11169| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11170 11171**Example** 11172 11173```ts 11174// xxx.ets 11175import { webview } from '@kit.ArkWeb'; 11176import { BusinessError } from '@kit.BasicServicesKit'; 11177 11178@Entry 11179@Component 11180struct WebComponent { 11181 controller: webview.WebviewController = new webview.WebviewController(); 11182 host: string = "www.spincast.org"; 11183 realm: string = "protected example"; 11184 11185 build() { 11186 Column() { 11187 Button('saveHttpAuthCredentials') 11188 .onClick(() => { 11189 try { 11190 webview.WebDataBase.saveHttpAuthCredentials(this.host, this.realm, "Stromgol", "Laroche"); 11191 } catch (error) { 11192 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11193 } 11194 }) 11195 Web({ src: 'www.example.com', controller: this.controller }) 11196 } 11197 } 11198} 11199``` 11200 11201### existHttpAuthCredentials 11202 11203static existHttpAuthCredentials(): boolean 11204 11205Checks whether any saved HTTP authentication credentials exist. This API returns the result synchronously. 11206 11207**System capability**: SystemCapability.Web.Webview.Core 11208 11209**Return value** 11210 11211| Type | Description | 11212| ------- | ------------------------------------------------------------ | 11213| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist; returns **false** otherwise.| 11214 11215**Example** 11216 11217```ts 11218// xxx.ets 11219import { webview } from '@kit.ArkWeb'; 11220import { BusinessError } from '@kit.BasicServicesKit'; 11221 11222@Entry 11223@Component 11224struct WebComponent { 11225 controller: webview.WebviewController = new webview.WebviewController(); 11226 11227 build() { 11228 Column() { 11229 Button('existHttpAuthCredentials') 11230 .onClick(() => { 11231 try { 11232 let result = webview.WebDataBase.existHttpAuthCredentials(); 11233 } catch (error) { 11234 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11235 } 11236 }) 11237 Web({ src: 'www.example.com', controller: this.controller }) 11238 } 11239 } 11240} 11241``` 11242 11243### deleteHttpAuthCredentials 11244 11245static deleteHttpAuthCredentials(): void 11246 11247Deletes all HTTP authentication credentials saved in the cache. This API returns the result synchronously. 11248 11249**System capability**: SystemCapability.Web.Webview.Core 11250 11251**Example** 11252 11253```ts 11254// xxx.ets 11255import { webview } from '@kit.ArkWeb'; 11256import { BusinessError } from '@kit.BasicServicesKit'; 11257 11258@Entry 11259@Component 11260struct WebComponent { 11261 controller: webview.WebviewController = new webview.WebviewController(); 11262 11263 build() { 11264 Column() { 11265 Button('deleteHttpAuthCredentials') 11266 .onClick(() => { 11267 try { 11268 webview.WebDataBase.deleteHttpAuthCredentials(); 11269 } catch (error) { 11270 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11271 } 11272 }) 11273 Web({ src: 'www.example.com', controller: this.controller }) 11274 } 11275 } 11276} 11277``` 11278 11279## GeolocationPermissions 11280 11281Implements a **GeolocationPermissions** object. 11282 11283> **NOTE** 11284> 11285> You must load the **Web** component before calling the APIs in **GeolocationPermissions**. 11286 11287### Required Permissions 11288 11289**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). 11290 11291### allowGeolocation 11292 11293static allowGeolocation(origin: string, incognito?: boolean): void 11294 11295Allows the specified origin to use the geolocation information. 11296 11297**System capability**: SystemCapability.Web.Webview.Core 11298 11299**Parameters** 11300 11301| Name| Type | Mandatory| Description | 11302| ------ | ------ | ---- | ------------------ | 11303| origin | string | Yes |Index of the origin.| 11304| 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.| 11305 11306**Error codes** 11307 11308For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11309 11310| ID| Error Message | 11311| -------- | ------------------------------------------------------ | 11312| 17100011 | Invalid origin. | 11313| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11314 11315**Example** 11316 11317```ts 11318// xxx.ets 11319import { webview } from '@kit.ArkWeb'; 11320import { BusinessError } from '@kit.BasicServicesKit'; 11321 11322@Entry 11323@Component 11324struct WebComponent { 11325 controller: webview.WebviewController = new webview.WebviewController(); 11326 origin: string = "file:///"; 11327 11328 build() { 11329 Column() { 11330 Button('allowGeolocation') 11331 .onClick(() => { 11332 try { 11333 webview.GeolocationPermissions.allowGeolocation(this.origin); 11334 } catch (error) { 11335 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11336 } 11337 }) 11338 Web({ src: 'www.example.com', controller: this.controller }) 11339 } 11340 } 11341} 11342``` 11343 11344### deleteGeolocation 11345 11346static deleteGeolocation(origin: string, incognito?: boolean): void 11347 11348Clears the geolocation permission status of a specified origin. 11349 11350**System capability**: SystemCapability.Web.Webview.Core 11351 11352**Parameters** 11353 11354| Name| Type | Mandatory| Description | 11355| ------ | ------ | ---- | ------------------ | 11356| origin | string | Yes | Index of the origin.| 11357| 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.| 11358 11359**Error codes** 11360 11361For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11362 11363| ID| Error Message | 11364| -------- | ------------------------------------------------------ | 11365| 17100011 | Invalid origin. | 11366| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11367 11368**Example** 11369 11370```ts 11371// xxx.ets 11372import { webview } from '@kit.ArkWeb'; 11373import { BusinessError } from '@kit.BasicServicesKit'; 11374 11375@Entry 11376@Component 11377struct WebComponent { 11378 controller: webview.WebviewController = new webview.WebviewController(); 11379 origin: string = "file:///"; 11380 11381 build() { 11382 Column() { 11383 Button('deleteGeolocation') 11384 .onClick(() => { 11385 try { 11386 webview.GeolocationPermissions.deleteGeolocation(this.origin); 11387 } catch (error) { 11388 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11389 } 11390 }) 11391 Web({ src: 'www.example.com', controller: this.controller }) 11392 } 11393 } 11394} 11395``` 11396 11397### getAccessibleGeolocation 11398 11399static getAccessibleGeolocation(origin: string, callback: AsyncCallback\<boolean>, incognito?: boolean): void 11400 11401Obtains the geolocation permission status of the specified origin. This API uses an asynchronous callback to return the result. 11402 11403**System capability**: SystemCapability.Web.Webview.Core 11404 11405**Parameters** 11406 11407| Name | Type | Mandatory| Description | 11408| -------- | ---------------------- | ---- | ------------------------------------------------------------ | 11409| origin | string | Yes | Index of the origin. | 11410| 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.| 11411| 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.| 11412 11413**Error codes** 11414 11415For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11416 11417| ID| Error Message | 11418| -------- | ------------------------------------------------------ | 11419| 17100011 | Invalid origin. | 11420| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11421 11422**Example** 11423 11424```ts 11425// xxx.ets 11426import { webview } from '@kit.ArkWeb'; 11427import { BusinessError } from '@kit.BasicServicesKit'; 11428 11429@Entry 11430@Component 11431struct WebComponent { 11432 controller: webview.WebviewController = new webview.WebviewController(); 11433 origin: string = "file:///"; 11434 11435 build() { 11436 Column() { 11437 Button('getAccessibleGeolocation') 11438 .onClick(() => { 11439 try { 11440 webview.GeolocationPermissions.getAccessibleGeolocation(this.origin, (error, result) => { 11441 if (error) { 11442 console.error(`getAccessibleGeolocationAsync error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11443 return; 11444 } 11445 console.log('getAccessibleGeolocationAsync result: ' + result); 11446 }); 11447 } catch (error) { 11448 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11449 } 11450 }) 11451 Web({ src: 'www.example.com', controller: this.controller }) 11452 } 11453 } 11454} 11455``` 11456 11457### getAccessibleGeolocation 11458 11459static getAccessibleGeolocation(origin: string, incognito?: boolean): Promise\<boolean> 11460 11461Obtains the geolocation permission status of the specified origin. This API uses a promise to return the result. 11462 11463**System capability**: SystemCapability.Web.Webview.Core 11464 11465**Parameters** 11466 11467| Name| Type| Mandatory| Description | 11468| ------ | -------- | ---- | -------------------- | 11469| origin | string | Yes | Index of the origin.| 11470| 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.| 11471 11472**Return value** 11473 11474| Type | Description | 11475| ---------------- | ------------------------------------------------------------ | 11476| 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.| 11477 11478**Error codes** 11479 11480For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11481 11482| ID| Error Message | 11483| -------- | ------------------------------------------------------ | 11484| 17100011 | Invalid origin. | 11485| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11486 11487**Example** 11488 11489```ts 11490// xxx.ets 11491import { webview } from '@kit.ArkWeb'; 11492import { BusinessError } from '@kit.BasicServicesKit'; 11493 11494@Entry 11495@Component 11496struct WebComponent { 11497 controller: webview.WebviewController = new webview.WebviewController(); 11498 origin: string = "file:///"; 11499 11500 build() { 11501 Column() { 11502 Button('getAccessibleGeolocation') 11503 .onClick(() => { 11504 try { 11505 webview.GeolocationPermissions.getAccessibleGeolocation(this.origin) 11506 .then(result => { 11507 console.log('getAccessibleGeolocationPromise result: ' + result); 11508 }).catch((error: BusinessError) => { 11509 console.error(`getAccessibleGeolocationPromise error, ErrorCode: ${error.code}, Message: ${error.message}`); 11510 }); 11511 } catch (error) { 11512 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11513 } 11514 }) 11515 Web({ src: 'www.example.com', controller: this.controller }) 11516 } 11517 } 11518} 11519``` 11520 11521### getStoredGeolocation 11522 11523static getStoredGeolocation(callback: AsyncCallback\<Array\<string>>, incognito?: boolean): void 11524 11525Obtains the geolocation permission status of all origins. This API uses an asynchronous callback to return the result. 11526 11527**System capability**: SystemCapability.Web.Webview.Core 11528 11529**Parameters** 11530 11531| Name | Type | Mandatory| Description | 11532| -------- | ---------------------------- | ---- | ---------------------------------------- | 11533| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return the geolocation permission status of all origins.| 11534| 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.| 11535 11536**Error codes** 11537 11538For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11539 11540| ID| Error Message | 11541| -------- | ------------------------------------------------------ | 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 11556 build() { 11557 Column() { 11558 Button('getStoredGeolocation') 11559 .onClick(() => { 11560 try { 11561 webview.GeolocationPermissions.getStoredGeolocation((error, origins) => { 11562 if (error) { 11563 console.error(`getStoredGeolocationAsync error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11564 return; 11565 } 11566 let origins_str: string = origins.join(); 11567 console.log('getStoredGeolocationAsync origins: ' + origins_str); 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### getStoredGeolocation 11580 11581static getStoredGeolocation(incognito?: boolean): Promise\<Array\<string>> 11582 11583Obtains the geolocation permission status of all origins. 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| 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.| 11592 11593**Return value** 11594 11595| Type | Description | 11596| ---------------------- | --------------------------------------------------------- | 11597| Promise\<Array\<string>> | Promise used to return the geolocation permission status of all origins.| 11598 11599**Error codes** 11600 11601For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11602 11603| ID| Error Message | 11604| -------- | ------------------------------------------------------ | 11605| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11606 11607**Example** 11608 11609```ts 11610// xxx.ets 11611import { webview } from '@kit.ArkWeb'; 11612import { BusinessError } from '@kit.BasicServicesKit'; 11613 11614@Entry 11615@Component 11616struct WebComponent { 11617 controller: webview.WebviewController = new webview.WebviewController(); 11618 11619 build() { 11620 Column() { 11621 Button('getStoredGeolocation') 11622 .onClick(() => { 11623 try { 11624 webview.GeolocationPermissions.getStoredGeolocation() 11625 .then(origins => { 11626 let origins_str: string = origins.join(); 11627 console.log('getStoredGeolocationPromise origins: ' + origins_str); 11628 }).catch((error: BusinessError) => { 11629 console.error(`getStoredGeolocationPromise error, ErrorCode: ${error.code}, Message: ${error.message}`); 11630 }); 11631 } catch (error) { 11632 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11633 } 11634 }) 11635 Web({ src: 'www.example.com', controller: this.controller }) 11636 } 11637 } 11638} 11639``` 11640 11641### deleteAllGeolocation 11642 11643static deleteAllGeolocation(incognito?: boolean): void 11644 11645Clears the geolocation permission status of all sources. 11646 11647**System capability**: SystemCapability.Web.Webview.Core 11648 11649**Parameters** 11650 11651| Name | Type | Mandatory| Description | 11652| -------- | ---------------------------- | ---- | ---------------------------------------- | 11653| 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.| 11654 11655**Example** 11656 11657```ts 11658// xxx.ets 11659import { webview } from '@kit.ArkWeb'; 11660import { BusinessError } from '@kit.BasicServicesKit'; 11661 11662@Entry 11663@Component 11664struct WebComponent { 11665 controller: webview.WebviewController = new webview.WebviewController(); 11666 11667 build() { 11668 Column() { 11669 Button('deleteAllGeolocation') 11670 .onClick(() => { 11671 try { 11672 webview.GeolocationPermissions.deleteAllGeolocation(); 11673 } catch (error) { 11674 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11675 } 11676 }) 11677 Web({ src: 'www.example.com', controller: this.controller }) 11678 } 11679 } 11680} 11681``` 11682## WebHeader 11683 11684Describes the request/response header returned by the **Web** component. 11685 11686**System capability**: SystemCapability.Web.Webview.Core 11687 11688| Name | Type | Readable| Writable|Description | 11689| ----------- | ------ | -----|------|------------------- | 11690| headerKey | string | Yes| Yes| Key of the request/response header. | 11691| headerValue | string | Yes| Yes| Value of the request/response header.| 11692 11693## RequestInfo<sup>12+</sup> 11694 11695Describes the information about the resource request sent by the **Web** component. 11696 11697**System capability**: SystemCapability.Web.Webview.Core 11698 11699| Name | Type | Readable| Writable|Description | 11700| ---------| ------ | -----|------|-------- | 11701| url | string | Yes| Yes| URL of the request. | 11702| method | string | Yes| Yes| Method of the request. | 11703| formData | string | Yes| Yes| Form data in the request body.| 11704 11705## WebHitTestType 11706 11707The [getHitTest](#gethittest) API is used to indicate a cursor node. 11708 11709**System capability**: SystemCapability.Web.Webview.Core 11710 11711| Name | Value| Description | 11712| ------------- | -- |----------------------------------------- | 11713| EditText | 0 |Editable area. | 11714| Email | 1 |Email address. | 11715| HttpAnchor | 2 |Hyperlink, where **src** is **http**. | 11716| HttpAnchorImg | 3 |Image with a hyperlink, where **src** is http + HTML::img.| 11717| Img | 4 |HTML::img tag. | 11718| Map | 5 |Geographical address. | 11719| Phone | 6 |Phone number. | 11720| Unknown | 7 |Unknown content. | 11721 11722## SecurityLevel<sup>11+</sup> 11723 11724Defines the security level of the web page. 11725 11726**System capability**: SystemCapability.Web.Webview.Core 11727 11728| Name | Value| Description | 11729| ------------- | -- |----------------------------------------- | 11730| 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.| 11731| SECURE | 1 |The web page is secure, using the HTTPS protocol and a trusted certificate.| 11732| WARNING | 2 |The web page is possibly compromised. A typical example is a web page that uses the HTTP or HTTPS protocol but an outdated TLS version.| 11733| DANGEROUS | 3 |The web page is insecure. This means that the page may have attempted to load HTTPS scripts to no avail, have failed authentication, or contain insecure active content in HTTPS, malware, phishing, or any other sources of major threats.| 11734 11735## HitTestValue 11736 11737Provides the element information of the area being clicked. For details about the sample code, see [getHitTestValue](#gethittestvalue). 11738 11739**System capability**: SystemCapability.Web.Webview.Core 11740 11741| Name| Type| Readable| Writable| Description| 11742| ---- | ---- | ---- | ---- |---- | 11743| type | [WebHitTestType](#webhittesttype) | Yes| Yes| Element type of the area being clicked.| 11744| 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.| 11745 11746## WebMessage 11747 11748type WebMessage = ArrayBuffer | string 11749 11750Describes the data types supported for [WebMessagePort](#webmessageport). 11751 11752**System capability**: SystemCapability.Web.Webview.Core 11753 11754| Type | Description | 11755| -------- | -------------------------------------- | 11756| string | String type.| 11757| ArrayBuffer | Binary type.| 11758 11759## JsMessageType<sup>10+</sup> 11760 11761Describes the type of the returned result of script execution using [runJavaScriptExt](#runjavascriptext10). 11762 11763**System capability**: SystemCapability.Web.Webview.Core 11764 11765| Name | Value| Description | 11766| ------------ | -- |--------------------------------- | 11767| NOT_SUPPORT | 0 |Unsupported data type.| 11768| STRING | 1 |String type.| 11769| NUMBER | 2 |Number type.| 11770| BOOLEAN | 3 |Boolean type.| 11771| ARRAY_BUFFER | 4 |Raw binary data buffer.| 11772| ARRAY | 5 |Array type.| 11773 11774## WebMessageType<sup>10+</sup> 11775 11776Describes the data type supported by the [webMessagePort](#webmessageport) API. 11777 11778**System capability**: SystemCapability.Web.Webview.Core 11779 11780| Name | Value| Description | 11781| ------------ | -- |------------------------------- | 11782| NOT_SUPPORT | 0 |Unsupported data type.| 11783| STRING | 1 |String type.| 11784| NUMBER | 2 |Number type.| 11785| BOOLEAN | 3 |Boolean type.| 11786| ARRAY_BUFFER | 4 |Raw binary data buffer.| 11787| ARRAY | 5 |Array type.| 11788| ERROR | 6 |Error object type.| 11789 11790## MediaPlaybackState<sup>12+</sup> 11791 11792Enumerates the playback states on the current web page. 11793 11794**System capability**: SystemCapability.Web.Webview.Core 11795 11796| Name | Value | Description | 11797| ------- | ---- | ------------------ | 11798| NONE | 0 | No audio or video playback is started on the page.| 11799| PLAYING | 1 | The audio and video on the page are being played.| 11800| PAUSED | 2 | The audio and video on the page are paused. | 11801| STOPPED | 3 | The audio and video on the page are stopped. | 11802 11803## RenderProcessMode<sup>12+</sup> 11804 11805Enumerates the ArkWeb render subprocess modes. 11806 11807**System capability**: SystemCapability.Web.Webview.Core 11808 11809| Name | Value| Description | 11810| ------------- | -- |----------------------------------------- | 11811| SINGLE | 0 |ArkWeb single render subprocess mode. In this mode, multiple **Web** components share one render subprocess.| 11812| MULTIPLE | 1 |ArkWeb multi-render subprocess mode. In this mode, each **Web** component has a rendering subprocess.| 11813 11814 11815## JsMessageExt<sup>10+</sup> 11816 11817Implements the **JsMessageExt** data object that is returned after script execution using the [runJavaScriptExt](#runjavascriptext10) API. 11818 11819### getType<sup>10+</sup> 11820 11821getType(): JsMessageType 11822 11823Obtains the type of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 11824 11825**System capability**: SystemCapability.Web.Webview.Core 11826 11827**Return value** 11828 11829| Type | Description | 11830| --------------| --------------------------------------------------------- | 11831| [JsMessageType](#jsmessagetype10) | Type of the data object that is returned after script execution using the [runJavaScriptExt](#runjavascriptext10) API.| 11832 11833### getString<sup>10+</sup> 11834 11835getString(): string 11836 11837Obtains string-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 11838 11839**System capability**: SystemCapability.Web.Webview.Core 11840 11841**Return value** 11842 11843| Type | Description | 11844| --------------| ------------- | 11845| string | Data of the string type.| 11846 11847**Error codes** 11848 11849For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11850 11851| ID| Error Message | 11852| -------- | ------------------------------------- | 11853| 17100014 | The type and value of the message do not match. | 11854 11855### getNumber<sup>10+</sup> 11856 11857getNumber(): number 11858 11859Obtains number-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 11860 11861**System capability**: SystemCapability.Web.Webview.Core 11862 11863**Return value** 11864 11865| Type | Description | 11866| --------------| ------------- | 11867| number | Data of the number type.| 11868 11869**Error codes** 11870 11871For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11872 11873| ID| Error Message | 11874| -------- | ------------------------------------- | 11875| 17100014 | The type and value of the message do not match. | 11876 11877### getBoolean<sup>10+</sup> 11878 11879getBoolean(): boolean 11880 11881Obtains Boolean-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 11882 11883**System capability**: SystemCapability.Web.Webview.Core 11884 11885**Return value** 11886 11887| Type | Description | 11888| --------------| ------------- | 11889| boolean | Data of the Boolean type.| 11890 11891**Error codes** 11892 11893For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11894 11895| ID| Error Message | 11896| -------- | ------------------------------------- | 11897| 17100014 | The type and value of the message do not match. | 11898 11899### getArrayBuffer<sup>10+</sup> 11900 11901getArrayBuffer(): ArrayBuffer 11902 11903Obtains raw binary data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 11904 11905**System capability**: SystemCapability.Web.Webview.Core 11906 11907**Return value** 11908 11909| Type | Description | 11910| --------------| ------------- | 11911| ArrayBuffer | Raw binary data.| 11912 11913**Error codes** 11914 11915For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11916 11917| ID| Error Message | 11918| -------- | ------------------------------------- | 11919| 17100014 | The type and value of the message do not match. | 11920 11921### getArray<sup>10+</sup> 11922 11923getArray(): Array\<string | number | boolean\> 11924 11925Obtains array-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 11926 11927**System capability**: SystemCapability.Web.Webview.Core 11928 11929**Return value** 11930 11931| Type | Description | 11932| --------------| ------------- | 11933| Array\<string \| number \| boolean\> | Data of the array type.| 11934 11935**Error codes** 11936 11937For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11938 11939| ID| Error Message | 11940| -------- | ------------------------------------- | 11941| 17100014 | The type and value of the message do not match. | 11942 11943## WebMessageExt<sup>10+</sup> 11944 11945Represents a data object received and sent through the [webMessagePort](#webmessageport) API. 11946 11947### getType<sup>10+</sup> 11948 11949getType(): WebMessageType 11950 11951Obtains the type of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11952 11953**System capability**: SystemCapability.Web.Webview.Core 11954 11955**Return value** 11956 11957| Type | Description | 11958| --------------| --------------------------------------------------------- | 11959| [WebMessageType](#webmessagetype10) | Data type supported by the [webMessagePort](#webmessageport) API.| 11960 11961### getString<sup>10+</sup> 11962 11963getString(): string 11964 11965Obtains string-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11966 11967**System capability**: SystemCapability.Web.Webview.Core 11968 11969**Return value** 11970 11971| Type | Description | 11972| --------------| ------------- | 11973| string | Data of the string type.| 11974 11975**Error codes** 11976 11977For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11978 11979| ID| Error Message | 11980| -------- | ------------------------------------- | 11981| 17100014 | The type and value of the message do not match. | 11982 11983### getNumber<sup>10+</sup> 11984 11985getNumber(): number 11986 11987Obtains number-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11988 11989**System capability**: SystemCapability.Web.Webview.Core 11990 11991**Return value** 11992 11993| Type | Description | 11994| --------------| ------------- | 11995| number | Data of the number type.| 11996 11997**Error codes** 11998 11999For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12000 12001| ID| Error Message | 12002| -------- | ------------------------------------- | 12003| 17100014 | The type and value of the message do not match. | 12004 12005### getBoolean<sup>10+</sup> 12006 12007getBoolean(): boolean 12008 12009Obtains Boolean-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12010 12011**System capability**: SystemCapability.Web.Webview.Core 12012 12013**Return value** 12014 12015| Type | Description | 12016| --------------| ------------- | 12017| boolean | Data of the Boolean type.| 12018 12019**Error codes** 12020 12021For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12022 12023| ID| Error Message | 12024| -------- | ------------------------------------- | 12025| 17100014 | The type and value of the message do not match. | 12026 12027### getArrayBuffer<sup>10+</sup> 12028 12029getArrayBuffer(): ArrayBuffer 12030 12031Obtains raw binary data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12032 12033**System capability**: SystemCapability.Web.Webview.Core 12034 12035**Return value** 12036 12037| Type | Description | 12038| --------------| ------------- | 12039| ArrayBuffer | Raw binary data.| 12040 12041**Error codes** 12042 12043For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12044 12045| ID| Error Message | 12046| -------- | ------------------------------------- | 12047| 17100014 | The type and value of the message do not match. | 12048 12049### getArray<sup>10+</sup> 12050 12051getArray(): Array\<string | number | boolean\> 12052 12053Obtains array-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12054 12055**System capability**: SystemCapability.Web.Webview.Core 12056 12057**Return value** 12058 12059| Type | Description | 12060| --------------| ------------- | 12061| Array\<string \| number \| boolean\> | Data of the array type.| 12062 12063**Error codes** 12064 12065For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12066 12067| ID| Error Message | 12068| -------- | ------------------------------------- | 12069| 17100014 | The type and value of the message do not match. | 12070 12071### getError<sup>10+</sup> 12072 12073getError(): Error 12074 12075Obtains the error-object-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12076 12077**System capability**: SystemCapability.Web.Webview.Core 12078 12079**Return value** 12080 12081| Type | Description | 12082| --------------| ------------- | 12083| Error | Data of the error object type.| 12084 12085**Error codes** 12086 12087For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12088 12089| ID| Error Message | 12090| -------- | ------------------------------------- | 12091| 17100014 | The type and value of the message do not match. | 12092 12093### setType<sup>10+</sup> 12094 12095setType(type: WebMessageType): void 12096 12097Sets the type for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12098 12099**System capability**: SystemCapability.Web.Webview.Core 12100 12101**Parameters** 12102 12103| Name| Type | Mandatory| Description | 12104| ------ | ------ | ---- | ---------------------- | 12105| type | [WebMessageType](#webmessagetype10) | Yes | Data type supported by the [webMessagePort](#webmessageport) API.| 12106 12107**Error codes** 12108 12109| ID| Error Message | 12110| -------- | ------------------------------------- | 12111| 17100014 | The type and value of the message do not match. | 12112| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12113 12114### setString<sup>10+</sup> 12115 12116setString(message: string): void 12117 12118Sets the string-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12119 12120**System capability**: SystemCapability.Web.Webview.Core 12121 12122**Parameters** 12123 12124| Name| Type | Mandatory| Description | 12125| ------ | ------ | ---- | -------------------- | 12126| message | string | Yes | String type.| 12127 12128**Error codes** 12129 12130| ID| Error Message | 12131| -------- | ------------------------------------- | 12132| 17100014 | The type and value of the message do not match. | 12133| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12134 12135### setNumber<sup>10+</sup> 12136 12137setNumber(message: number): void 12138 12139Sets the number-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12140 12141**System capability**: SystemCapability.Web.Webview.Core 12142 12143**Parameters** 12144 12145| Name| Type | Mandatory| Description | 12146| ------ | ------ | ---- | -------------------- | 12147| message | number | Yes | Data of the number type.| 12148 12149**Error codes** 12150 12151| ID| Error Message | 12152| -------- | ------------------------------------- | 12153| 17100014 | The type and value of the message do not match. | 12154| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12155 12156### setBoolean<sup>10+</sup> 12157 12158setBoolean(message: boolean): void 12159 12160Sets the Boolean-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12161 12162**System capability**: SystemCapability.Web.Webview.Core 12163 12164**Parameters** 12165 12166| Name| Type | Mandatory| Description | 12167| ------ | ------ | ---- | -------------------- | 12168| message | boolean | Yes | Data of the Boolean type.| 12169 12170**Error codes** 12171 12172| ID| Error Message | 12173| -------- | ------------------------------------- | 12174| 17100014 | The type and value of the message do not match. | 12175| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12176 12177### setArrayBuffer<sup>10+</sup> 12178 12179setArrayBuffer(message: ArrayBuffer): void 12180 12181Sets the raw binary data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12182 12183**System capability**: SystemCapability.Web.Webview.Core 12184 12185**Parameters** 12186 12187| Name| Type | Mandatory| Description | 12188| ------ | ------ | ---- | -------------------- | 12189| message | ArrayBuffer | Yes | Raw binary data.| 12190 12191**Error codes** 12192 12193For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12194 12195| ID| Error Message | 12196| -------- | ------------------------------------- | 12197| 17100014 | The type and value of the message do not match. | 12198| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12199 12200### setArray<sup>10+</sup> 12201 12202setArray(message: Array\<string | number | boolean\>): void 12203 12204Sets the array-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12205 12206**System capability**: SystemCapability.Web.Webview.Core 12207 12208**Parameters** 12209 12210| Name| Type | Mandatory| Description | 12211| ------ | ------ | ---- | -------------------- | 12212| message | Array\<string \| number \| boolean\> | Yes | Data of the array type.| 12213 12214**Error codes** 12215 12216For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12217 12218| ID| Error Message | 12219| -------- | ------------------------------------- | 12220| 17100014 | The type and value of the message do not match. | 12221| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12222 12223### setError<sup>10+</sup> 12224 12225setError(message: Error): void 12226 12227Sets the error-object-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12228 12229**System capability**: SystemCapability.Web.Webview.Core 12230 12231**Parameters** 12232 12233| Name| Type | Mandatory| Description | 12234| ------ | ------ | ---- | -------------------- | 12235| message | Error | Yes | Data of the error object type.| 12236 12237**Error codes** 12238 12239For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12240 12241| ID| Error Message | 12242| -------- | ------------------------------------- | 12243| 17100014 | The type and value of the message do not match. | 12244| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12245 12246## WebStorageOrigin 12247 12248Provides usage information of the Web SQL Database. 12249 12250**System capability**: SystemCapability.Web.Webview.Core 12251 12252| Name | Type | Readable| Writable| Description| 12253| ------ | ------ | ---- | ---- | ---- | 12254| origin | string | Yes | Yes| Index of the origin.| 12255| usage | number | Yes | Yes| Storage usage of the origin. | 12256| quota | number | Yes | Yes| Storage quota of the origin. | 12257 12258## BackForwardList 12259 12260Provides the historical information list of the current webview. 12261 12262**System capability**: SystemCapability.Web.Webview.Core 12263 12264| Name | Type | Readable| Writable| Description | 12265| ------------ | ------ | ---- | ---- | ------------------------------------------------------------ | 12266| currentIndex | number | Yes | Yes | Index of the current page in the page history stack. | 12267| 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.| 12268 12269### getItemAtIndex 12270 12271getItemAtIndex(index: number): HistoryItem 12272 12273Obtains the page record with the specified index in the history stack. 12274 12275**System capability**: SystemCapability.Web.Webview.Core 12276 12277**Parameters** 12278 12279| Name| Type | Mandatory| Description | 12280| ------ | ------ | ---- | ---------------------- | 12281| index | number | Yes | Index of the target page record in the history stack.| 12282 12283**Return value** 12284 12285| Type | Description | 12286| --------------------------- | ------------ | 12287| [HistoryItem](#historyitem) | Historical page record.| 12288 12289**Error codes** 12290 12291For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12292 12293| ID| Error Message | 12294| -------- | ------------------------------------------------------ | 12295| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12296 12297**Example** 12298 12299```ts 12300// xxx.ets 12301import { webview } from '@kit.ArkWeb'; 12302import { BusinessError } from '@kit.BasicServicesKit'; 12303import { image } from '@kit.ImageKit'; 12304 12305@Entry 12306@Component 12307struct WebComponent { 12308 controller: webview.WebviewController = new webview.WebviewController(); 12309 @State icon: image.PixelMap | undefined = undefined; 12310 12311 build() { 12312 Column() { 12313 Button('getBackForwardEntries') 12314 .onClick(() => { 12315 try { 12316 let list = this.controller.getBackForwardEntries(); 12317 let historyItem = list.getItemAtIndex(list.currentIndex); 12318 console.log("HistoryItem: " + JSON.stringify(historyItem)); 12319 this.icon = historyItem.icon; 12320 } catch (error) { 12321 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12322 } 12323 }) 12324 Web({ src: 'www.example.com', controller: this.controller }) 12325 } 12326 } 12327} 12328``` 12329 12330## HistoryItem 12331 12332Describes a historical page record. 12333 12334**System capability**: SystemCapability.Web.Webview.Core 12335 12336| Name | Type | Readable| Writable| Description | 12337| ------------- | -------------------------------------- | ---- | ---- | ---------------------------- | 12338| icon | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | No | **PixelMap** object of the icon on the historical page.| 12339| historyUrl | string | Yes | Yes | URL of the historical page. | 12340| historyRawUrl | string | Yes | Yes | Original URL of the historical page. | 12341| title | string | Yes | Yes | Title of the historical page. | 12342 12343## WebCustomScheme 12344 12345Defines a custom URL scheme. 12346 12347**System capability**: SystemCapability.Web.Webview.Core 12348 12349| Name | Type | Readable| Writable| Description | 12350| -------------- | --------- | ---- | ---- | ---------------------------- | 12351| 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. | 12352| isSupportCORS | boolean | Yes | Yes | Whether to support cross-origin resource sharing (CORS). | 12353| isSupportFetch | boolean | Yes | Yes | Whether to support fetch requests. | 12354| 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. | 12355| isLocal<sup>12+</sup> | boolean | Yes | Yes | Whether the scheme is treated with the same security rules as those applied to file URLs. | 12356| 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. | 12357| isSecure<sup>12+</sup> | boolean | Yes | Yes | Whether the scheme is treated with the same security rules as those applied to HTTPS URLs. | 12358| 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**. | 12359| 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**. | 12360 12361## SecureDnsMode<sup>10+</sup> 12362 12363Describes the mode in which the **Web** component uses HTTPDNS. 12364 12365**System capability**: SystemCapability.Web.Webview.Core 12366 12367| Name | Value| Description | 12368| ------------- | -- |----------------------------------------- | 12369| OFF | 0 |HTTPDNS is not used. This value can be used to revoke the previously used HTTPDNS configuration.| 12370| 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.| 12371| SECURE_ONLY | 2 |The specified HTTPDNS server is forcibly used for DNS resolution.| 12372 12373## WebDownloadState<sup>11+</sup> 12374 12375Describes the state of a download task. 12376 12377**System capability**: SystemCapability.Web.Webview.Core 12378 12379| Name | Value| Description | 12380| ------------- | -- |----------------------------------------- | 12381| IN_PROGRESS | 0 |The download task is in progress.| 12382| COMPLETED | 1 |The download task is completed.| 12383| CANCELED | 2 |The download task has been canceled.| 12384| INTERRUPTED | 3 |The download task is interrupted.| 12385| PENDING | 4 |The download task is pending.| 12386| PAUSED | 5 |The download task is paused.| 12387| UNKNOWN | 6 |The state of the download task is unknown.| 12388 12389## WebDownloadErrorCode<sup>11+</sup> 12390 12391Describes the download task error code. 12392 12393**System capability**: SystemCapability.Web.Webview.Core 12394 12395| Name | Value| Description | 12396| ------------- | -- |----------------------------------------- | 12397| ERROR_UNKNOWN | 0 |Unknown error.| 12398| FILE_FAILED | 1 | Failed to operate the file.| 12399| FILE_ACCESS_DENIED | 2 | No permission to access the file.| 12400| FILE_NO_SPACE | 3 | The disk space is insufficient.| 12401| FILE_NAME_TOO_LONG | 5 | The file name is too long.| 12402| FILE_TOO_LARGE | 6 | The file is too large.| 12403| FILE_TRANSIENT_ERROR | 10 | Some temporary issues occur, such as insufficient memory, files in use, and too many files open at the same time.| 12404| FILE_BLOCKED | 11 | Access to the file is blocked due to certain local policies.| 12405| FILE_TOO_SHORT | 13 | The file to resume downloading is not long enough. It may not exist.| 12406| FILE_HASH_MISMATCH | 14 | Hash mismatch.| 12407| FILE_SAME_AS_SOURCE | 15 | The file already exists.| 12408| NETWORK_FAILED | 20 | Common network error.| 12409| NETWORK_TIMEOUT | 21 | Network connection timeout.| 12410| NETWORK_DISCONNECTED | 22 | Network disconnected.| 12411| NETWORK_SERVER_DOWN | 23 | The server is shut down.| 12412| NETWORK_INVALID_REQUEST | 24 | Invalid network request. The request may be redirected to an unsupported scheme or an invalid URL.| 12413| SERVER_FAILED | 30 | The server returns a general error.| 12414| SERVER_NO_RANGE | 31 | The server does not support the range request.| 12415| SERVER_BAD_CONTENT | 33 | The server does not have the requested data.| 12416| SERVER_UNAUTHORIZED | 34 | The file cannot be downloaded from the server.| 12417| SERVER_CERT_PROBLEM | 35 | The server certificate is incorrect.| 12418| SERVER_FORBIDDEN | 36 | The access to the server is forbidden.| 12419| SERVER_UNREACHABLE | 37 | The server cannot be accessed.| 12420| SERVER_CONTENT_LENGTH_MISMATCH | 38 | The received data does not match the content length.| 12421| SERVER_CROSS_ORIGIN_REDIRECT | 39 | An unexpected cross-site redirection occurs.| 12422| USER_CANCELED | 40 | The user cancels the download.| 12423| USER_SHUTDOWN | 41 | The user closes the application.| 12424| CRASH | 50 | The application crashes.| 12425 12426## WebDownloadItem<sup>11+</sup> 12427 12428 Implements a **WebDownloadItem** object. You can use this object to perform operations on the corresponding download task. 12429 12430> **NOTE** 12431> 12432> During the download, the download process is notified to the user through **WebDownloadDelegate**. The user can operate the download task through the **WebDownloadItem** parameter. 12433 12434### getGuid<sup>11+</sup> 12435 12436getGuid(): string 12437 12438Obtains the unique ID of this download task. 12439 12440**System capability**: SystemCapability.Web.Webview.Core 12441 12442**Return value** 12443 12444| Type | Description | 12445| ------ | ------------------------- | 12446| string | Unique ID of the download task.| 12447 12448**Example** 12449 12450```ts 12451// xxx.ets 12452import { webview } from '@kit.ArkWeb'; 12453import { BusinessError } from '@kit.BasicServicesKit'; 12454 12455@Entry 12456@Component 12457struct WebComponent { 12458 controller: webview.WebviewController = new webview.WebviewController(); 12459 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12460 12461 build() { 12462 Column() { 12463 Button('setDownloadDelegate') 12464 .onClick(() => { 12465 try { 12466 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12467 console.log("will start a download."); 12468 // Pass in a download path and start the download. 12469 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12470 }) 12471 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12472 console.log("download update guid: " + webDownloadItem.getGuid()); 12473 }) 12474 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12475 console.log("download failed guid: " + webDownloadItem.getGuid()); 12476 }) 12477 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12478 console.log("download finish guid: " + webDownloadItem.getGuid()); 12479 }) 12480 this.controller.setDownloadDelegate(this.delegate); 12481 } catch (error) { 12482 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12483 } 12484 }) 12485 Button('startDownload') 12486 .onClick(() => { 12487 try { 12488 this.controller.startDownload('https://www.example.com'); 12489 } catch (error) { 12490 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12491 } 12492 }) 12493 Web({ src: 'www.example.com', controller: this.controller }) 12494 } 12495 } 12496} 12497``` 12498 12499### getCurrentSpeed<sup>11+</sup> 12500 12501getCurrentSpeed(): number 12502 12503Obtains the download speed, in bytes per second. 12504 12505**System capability**: SystemCapability.Web.Webview.Core 12506 12507**Return value** 12508 12509| Type | Description | 12510| ------ | ------------------------- | 12511| number | Download speed, in bytes per second.| 12512 12513**Example** 12514 12515```ts 12516// xxx.ets 12517import { webview } from '@kit.ArkWeb'; 12518import { BusinessError } from '@kit.BasicServicesKit'; 12519 12520@Entry 12521@Component 12522struct WebComponent { 12523 controller: webview.WebviewController = new webview.WebviewController(); 12524 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12525 12526 build() { 12527 Column() { 12528 Button('setDownloadDelegate') 12529 .onClick(() => { 12530 try { 12531 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12532 console.log("will start a download."); 12533 // Pass in a download path and start the download. 12534 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12535 }) 12536 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12537 console.log("download update current speed: " + webDownloadItem.getCurrentSpeed()); 12538 }) 12539 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12540 console.log("download failed guid: " + webDownloadItem.getGuid()); 12541 }) 12542 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12543 console.log("download finish guid: " + webDownloadItem.getGuid()); 12544 }) 12545 this.controller.setDownloadDelegate(this.delegate); 12546 } catch (error) { 12547 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12548 } 12549 }) 12550 Button('startDownload') 12551 .onClick(() => { 12552 try { 12553 this.controller.startDownload('https://www.example.com'); 12554 } catch (error) { 12555 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12556 } 12557 }) 12558 Web({ src: 'www.example.com', controller: this.controller }) 12559 } 12560 } 12561} 12562``` 12563 12564### getPercentComplete<sup>11+</sup> 12565 12566getPercentComplete(): number 12567 12568Obtains the download progress. The value **100** indicates that the download is complete. 12569 12570**System capability**: SystemCapability.Web.Webview.Core 12571 12572**Return value** 12573 12574| Type | Description | 12575| ------ | ------------------------- | 12576| number | Download progress. The value **100** indicates that the download is complete.| 12577 12578**Example** 12579 12580```ts 12581// xxx.ets 12582import { webview } from '@kit.ArkWeb'; 12583import { BusinessError } from '@kit.BasicServicesKit'; 12584 12585@Entry 12586@Component 12587struct WebComponent { 12588 controller: webview.WebviewController = new webview.WebviewController(); 12589 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12590 12591 build() { 12592 Column() { 12593 Button('setDownloadDelegate') 12594 .onClick(() => { 12595 try { 12596 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12597 console.log("will start a download."); 12598 // Pass in a download path and start the download. 12599 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12600 }) 12601 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12602 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12603 }) 12604 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12605 console.log("download failed guid: " + webDownloadItem.getGuid()); 12606 }) 12607 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12608 console.log("download finish guid: " + webDownloadItem.getGuid()); 12609 }) 12610 this.controller.setDownloadDelegate(this.delegate); 12611 } catch (error) { 12612 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12613 } 12614 }) 12615 Button('startDownload') 12616 .onClick(() => { 12617 try { 12618 this.controller.startDownload('https://www.example.com'); 12619 } catch (error) { 12620 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12621 } 12622 }) 12623 Web({ src: 'www.example.com', controller: this.controller }) 12624 } 12625 } 12626} 12627``` 12628 12629### getTotalBytes<sup>11+</sup> 12630 12631getTotalBytes(): number 12632 12633Obtains the total length of the file to be downloaded. 12634 12635**System capability**: SystemCapability.Web.Webview.Core 12636 12637**Return value** 12638 12639| Type | Description | 12640| ------ | ------------------------- | 12641| number | Total length of the file to be downloaded.| 12642 12643**Example** 12644 12645```ts 12646// xxx.ets 12647import { webview } from '@kit.ArkWeb'; 12648import { BusinessError } from '@kit.BasicServicesKit'; 12649 12650@Entry 12651@Component 12652struct WebComponent { 12653 controller: webview.WebviewController = new webview.WebviewController(); 12654 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12655 12656 build() { 12657 Column() { 12658 Button('setDownloadDelegate') 12659 .onClick(() => { 12660 try { 12661 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12662 console.log("will start a download."); 12663 // Pass in a download path and start the download. 12664 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12665 }) 12666 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12667 console.log("download update total bytes: " + webDownloadItem.getTotalBytes()); 12668 }) 12669 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12670 console.log("download failed guid: " + webDownloadItem.getGuid()); 12671 }) 12672 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12673 console.log("download finish guid: " + webDownloadItem.getGuid()); 12674 }) 12675 this.controller.setDownloadDelegate(this.delegate); 12676 } catch (error) { 12677 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12678 } 12679 }) 12680 Button('startDownload') 12681 .onClick(() => { 12682 try { 12683 this.controller.startDownload('https://www.example.com'); 12684 } catch (error) { 12685 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12686 } 12687 }) 12688 Web({ src: 'www.example.com', controller: this.controller }) 12689 } 12690 } 12691} 12692``` 12693 12694### getState<sup>11+</sup> 12695 12696getState(): WebDownloadState 12697 12698Obtains the download state. 12699 12700**System capability**: SystemCapability.Web.Webview.Core 12701 12702**Return value** 12703 12704| Type | Description | 12705| ------ | ------------------------- | 12706| [WebDownloadState](#webdownloadstate11) | Download state.| 12707 12708**Example** 12709 12710```ts 12711// xxx.ets 12712import { webview } from '@kit.ArkWeb'; 12713import { BusinessError } from '@kit.BasicServicesKit'; 12714 12715@Entry 12716@Component 12717struct WebComponent { 12718 controller: webview.WebviewController = new webview.WebviewController(); 12719 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12720 12721 build() { 12722 Column() { 12723 Button('setDownloadDelegate') 12724 .onClick(() => { 12725 try { 12726 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12727 console.log("will start a download."); 12728 // Pass in a download path and start the download. 12729 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12730 }) 12731 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12732 console.log("download update download state: " + webDownloadItem.getState()); 12733 }) 12734 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12735 console.log("download failed guid: " + webDownloadItem.getGuid()); 12736 }) 12737 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12738 console.log("download finish guid: " + webDownloadItem.getGuid()); 12739 }) 12740 this.controller.setDownloadDelegate(this.delegate); 12741 } catch (error) { 12742 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12743 } 12744 }) 12745 Button('startDownload') 12746 .onClick(() => { 12747 try { 12748 this.controller.startDownload('https://www.example.com'); 12749 } catch (error) { 12750 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12751 } 12752 }) 12753 Web({ src: 'www.example.com', controller: this.controller }) 12754 } 12755 } 12756} 12757``` 12758 12759### getLastErrorCode<sup>11+</sup> 12760 12761getLastErrorCode(): WebDownloadErrorCode 12762 12763Obtains the download error code. 12764 12765**System capability**: SystemCapability.Web.Webview.Core 12766 12767**Return value** 12768 12769| Type | Description | 12770| ------ | ------------------------- | 12771| [WebDownloadErrorCode](#webdownloaderrorcode11) | Error code returned when the download error occurs.| 12772 12773**Example** 12774 12775```ts 12776// xxx.ets 12777import { webview } from '@kit.ArkWeb'; 12778import { BusinessError } from '@kit.BasicServicesKit'; 12779 12780@Entry 12781@Component 12782struct WebComponent { 12783 controller: webview.WebviewController = new webview.WebviewController(); 12784 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12785 12786 build() { 12787 Column() { 12788 Button('setDownloadDelegate') 12789 .onClick(() => { 12790 try { 12791 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12792 console.log("will start a download."); 12793 // Pass in a download path and start the download. 12794 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12795 }) 12796 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12797 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12798 }) 12799 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12800 console.log("download failed guid: " + webDownloadItem.getGuid()); 12801 console.log("download error code: " + webDownloadItem.getLastErrorCode()); 12802 }) 12803 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12804 console.log("download finish guid: " + webDownloadItem.getGuid()); 12805 }) 12806 this.controller.setDownloadDelegate(this.delegate); 12807 } catch (error) { 12808 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12809 } 12810 }) 12811 Button('startDownload') 12812 .onClick(() => { 12813 try { 12814 this.controller.startDownload('https://www.example.com'); 12815 } catch (error) { 12816 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12817 } 12818 }) 12819 Web({ src: 'www.example.com', controller: this.controller }) 12820 } 12821 } 12822} 12823``` 12824 12825### getMethod<sup>11+</sup> 12826 12827getMethod(): string 12828 12829Obtains the request mode of this download task. 12830 12831**System capability**: SystemCapability.Web.Webview.Core 12832 12833**Return value** 12834 12835| Type | Description | 12836| ------ | ------------------------- | 12837| string | Request mode of the download task.| 12838 12839**Example** 12840 12841```ts 12842// xxx.ets 12843import { webview } from '@kit.ArkWeb'; 12844import { BusinessError } from '@kit.BasicServicesKit'; 12845 12846@Entry 12847@Component 12848struct WebComponent { 12849 controller: webview.WebviewController = new webview.WebviewController(); 12850 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12851 12852 build() { 12853 Column() { 12854 Button('setDownloadDelegate') 12855 .onClick(() => { 12856 try { 12857 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12858 console.log("Download will start. Method:" + webDownloadItem.getMethod()); 12859 // Pass in a download path and start the download. 12860 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12861 }) 12862 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12863 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12864 }) 12865 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12866 console.log("download failed guid: " + webDownloadItem.getGuid()); 12867 }) 12868 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12869 console.log("download finish guid: " + webDownloadItem.getGuid()); 12870 }) 12871 this.controller.setDownloadDelegate(this.delegate); 12872 } catch (error) { 12873 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12874 } 12875 }) 12876 Button('startDownload') 12877 .onClick(() => { 12878 try { 12879 this.controller.startDownload('https://www.example.com'); 12880 } catch (error) { 12881 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12882 } 12883 }) 12884 Web({ src: 'www.example.com', controller: this.controller }) 12885 } 12886 } 12887} 12888``` 12889 12890### getMimeType<sup>11+</sup> 12891 12892getMimeType(): string 12893 12894Obtains 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). 12895 12896**System capability**: SystemCapability.Web.Webview.Core 12897 12898**Return value** 12899 12900| Type | Description | 12901| ------ | ------------------------- | 12902| string | MIME type (for example, audio/ogg for a sound file, and image/png for an image file).| 12903 12904**Example** 12905 12906```ts 12907// xxx.ets 12908import { webview } from '@kit.ArkWeb'; 12909import { BusinessError } from '@kit.BasicServicesKit'; 12910 12911@Entry 12912@Component 12913struct WebComponent { 12914 controller: webview.WebviewController = new webview.WebviewController(); 12915 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12916 12917 build() { 12918 Column() { 12919 Button('setDownloadDelegate') 12920 .onClick(() => { 12921 try { 12922 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12923 console.log("Download will start. MIME type:" + webDownloadItem.getMimeType()); 12924 // Pass in a download path and start the download. 12925 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12926 }) 12927 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12928 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12929 }) 12930 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12931 console.log("download failed guid: " + webDownloadItem.getGuid()); 12932 }) 12933 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12934 console.log("download finish guid: " + webDownloadItem.getGuid()); 12935 }) 12936 this.controller.setDownloadDelegate(this.delegate); 12937 } catch (error) { 12938 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12939 } 12940 }) 12941 Button('startDownload') 12942 .onClick(() => { 12943 try { 12944 this.controller.startDownload('https://www.example.com'); 12945 } catch (error) { 12946 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12947 } 12948 }) 12949 Web({ src: 'www.example.com', controller: this.controller }) 12950 } 12951 } 12952} 12953``` 12954 12955### getUrl<sup>11+</sup> 12956 12957getUrl(): string 12958 12959Obtains the download request URL. 12960 12961**System capability**: SystemCapability.Web.Webview.Core 12962 12963**Return value** 12964 12965| Type | Description | 12966| ------ | ------------------------- | 12967| string | Download request URL.| 12968 12969**Example** 12970 12971```ts 12972// xxx.ets 12973import { webview } from '@kit.ArkWeb'; 12974import { BusinessError } from '@kit.BasicServicesKit'; 12975 12976@Entry 12977@Component 12978struct WebComponent { 12979 controller: webview.WebviewController = new webview.WebviewController(); 12980 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12981 12982 build() { 12983 Column() { 12984 Button('setDownloadDelegate') 12985 .onClick(() => { 12986 try { 12987 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12988 console.log("will start a download, url:" + webDownloadItem.getUrl()); 12989 // Pass in a download path and start the download. 12990 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12991 }) 12992 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12993 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12994 }) 12995 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12996 console.log("download failed guid: " + webDownloadItem.getGuid()); 12997 }) 12998 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12999 console.log("download finish guid: " + webDownloadItem.getGuid()); 13000 }) 13001 this.controller.setDownloadDelegate(this.delegate); 13002 } catch (error) { 13003 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13004 } 13005 }) 13006 Button('startDownload') 13007 .onClick(() => { 13008 try { 13009 this.controller.startDownload('https://www.example.com'); 13010 } catch (error) { 13011 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13012 } 13013 }) 13014 Web({ src: 'www.example.com', controller: this.controller }) 13015 } 13016 } 13017} 13018``` 13019 13020### getSuggestedFileName<sup>11+</sup> 13021 13022getSuggestedFileName(): string 13023 13024Obtains the suggested file name for this download task. 13025 13026**System capability**: SystemCapability.Web.Webview.Core 13027 13028**Return value** 13029 13030| Type | Description | 13031| ------ | ------------------------- | 13032| string | Suggested file name.| 13033 13034**Example** 13035 13036```ts 13037// xxx.ets 13038import { webview } from '@kit.ArkWeb'; 13039import { BusinessError } from '@kit.BasicServicesKit'; 13040 13041@Entry 13042@Component 13043struct WebComponent { 13044 controller: webview.WebviewController = new webview.WebviewController(); 13045 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13046 13047 build() { 13048 Column() { 13049 Button('setDownloadDelegate') 13050 .onClick(() => { 13051 try { 13052 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13053 console.log("will start a download, suggest name:" + webDownloadItem.getSuggestedFileName()); 13054 // Pass in a download path and start the download. 13055 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13056 }) 13057 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13058 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13059 }) 13060 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13061 console.log("download failed guid: " + webDownloadItem.getGuid()); 13062 }) 13063 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13064 console.log("download finish guid: " + webDownloadItem.getGuid()); 13065 }) 13066 this.controller.setDownloadDelegate(this.delegate); 13067 } catch (error) { 13068 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13069 } 13070 }) 13071 Button('startDownload') 13072 .onClick(() => { 13073 try { 13074 this.controller.startDownload('https://www.example.com'); 13075 } catch (error) { 13076 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13077 } 13078 }) 13079 Web({ src: 'www.example.com', controller: this.controller }) 13080 } 13081 } 13082} 13083``` 13084 13085### getReceivedBytes<sup>11+</sup> 13086 13087getReceivedBytes(): number 13088 13089Obtains the number of received bytes. 13090 13091**System capability**: SystemCapability.Web.Webview.Core 13092 13093**Return value** 13094 13095| Type | Description | 13096| ------ | ------------------------- | 13097| number | Number of received bytes.| 13098 13099**Example** 13100 13101```ts 13102// xxx.ets 13103import { webview } from '@kit.ArkWeb'; 13104import { BusinessError } from '@kit.BasicServicesKit'; 13105 13106@Entry 13107@Component 13108struct WebComponent { 13109 controller: webview.WebviewController = new webview.WebviewController(); 13110 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13111 13112 build() { 13113 Column() { 13114 Button('setDownloadDelegate') 13115 .onClick(() => { 13116 try { 13117 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13118 console.log("will start a download."); 13119 // Pass in a download path and start the download. 13120 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13121 }) 13122 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13123 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13124 console.log("download update received bytes: " + webDownloadItem.getReceivedBytes()); 13125 }) 13126 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13127 console.log("download failed guid: " + webDownloadItem.getGuid()); 13128 }) 13129 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13130 console.log("download finish guid: " + webDownloadItem.getGuid()); 13131 }) 13132 this.controller.setDownloadDelegate(this.delegate); 13133 } catch (error) { 13134 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13135 } 13136 }) 13137 Button('startDownload') 13138 .onClick(() => { 13139 try { 13140 this.controller.startDownload('https://www.example.com'); 13141 } catch (error) { 13142 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13143 } 13144 }) 13145 Web({ src: 'www.example.com', controller: this.controller }) 13146 } 13147 } 13148} 13149``` 13150 13151### getFullPath<sup>11+</sup> 13152 13153getFullPath(): string 13154 13155Obtains the full path of the downloaded file on the disk. 13156 13157**System capability**: SystemCapability.Web.Webview.Core 13158 13159**Return value** 13160 13161| Type | Description | 13162| ------ | ------------------------- | 13163| string | Full path of the downloaded file on the disk.| 13164 13165**Example** 13166 13167```ts 13168// xxx.ets 13169import { webview } from '@kit.ArkWeb'; 13170import { BusinessError } from '@kit.BasicServicesKit'; 13171 13172@Entry 13173@Component 13174struct WebComponent { 13175 controller: webview.WebviewController = new webview.WebviewController(); 13176 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13177 13178 build() { 13179 Column() { 13180 Button('setDownloadDelegate') 13181 .onClick(() => { 13182 try { 13183 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13184 console.log("will start a download."); 13185 // Pass in a download path and start the download. 13186 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13187 }) 13188 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13189 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13190 }) 13191 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13192 console.log("download failed guid: " + webDownloadItem.getGuid()); 13193 }) 13194 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13195 console.log("download finish guid: " + webDownloadItem.getGuid()); 13196 console.log("download finish full path: " + webDownloadItem.getFullPath()); 13197 }) 13198 this.controller.setDownloadDelegate(this.delegate); 13199 } catch (error) { 13200 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13201 } 13202 }) 13203 Button('startDownload') 13204 .onClick(() => { 13205 try { 13206 this.controller.startDownload('https://www.example.com'); 13207 } catch (error) { 13208 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13209 } 13210 }) 13211 Web({ src: 'www.example.com', controller: this.controller }) 13212 } 13213 } 13214} 13215``` 13216 13217### serialize<sup>11+</sup> 13218 13219serialize(): Uint8Array 13220 13221Serializes the failed download to a byte array. 13222 13223**System capability**: SystemCapability.Web.Webview.Core 13224 13225**Return value** 13226 13227| Type | Description | 13228| ------ | ------------------------- | 13229| Uint8Array | Byte array into which the failed download is serialized.| 13230 13231**Example** 13232 13233```ts 13234// xxx.ets 13235import { webview } from '@kit.ArkWeb'; 13236import { BusinessError } from '@kit.BasicServicesKit'; 13237 13238@Entry 13239@Component 13240struct WebComponent { 13241 controller: webview.WebviewController = new webview.WebviewController(); 13242 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13243 failedData: Uint8Array = new Uint8Array(); 13244 13245 build() { 13246 Column() { 13247 Button('setDownloadDelegate') 13248 .onClick(() => { 13249 try { 13250 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13251 console.log("will start a download."); 13252 // Pass in a download path and start the download. 13253 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13254 }) 13255 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13256 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13257 }) 13258 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13259 console.log("download failed guid: " + webDownloadItem.getGuid()); 13260 // Serialize the failed download to a byte array. 13261 this.failedData = webDownloadItem.serialize(); 13262 }) 13263 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13264 console.log("download finish guid: " + webDownloadItem.getGuid()); 13265 }) 13266 this.controller.setDownloadDelegate(this.delegate); 13267 } catch (error) { 13268 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13269 } 13270 }) 13271 Button('startDownload') 13272 .onClick(() => { 13273 try { 13274 this.controller.startDownload('https://www.example.com'); 13275 } catch (error) { 13276 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13277 } 13278 }) 13279 Web({ src: 'www.example.com', controller: this.controller }) 13280 } 13281 } 13282} 13283``` 13284 13285### deserialize<sup>11+</sup> 13286 13287static deserialize(serializedData: Uint8Array): WebDownloadItem 13288 13289Deserializes the serialized byte array into a **WebDownloadItem** object. 13290 13291**System capability**: SystemCapability.Web.Webview.Core 13292 13293**Parameters** 13294 13295| Name | Type | Mandatory | Description| 13296| ------------------ | ------- | ---- | ------------- | 13297| serializedData | Uint8Array | Yes | Byte array into which the download is serialized.| 13298 13299**Return value** 13300 13301| Type | Description | 13302| ------ | ------------------------- | 13303| [WebDownloadItem](#webdownloaditem11) | **WebDownloadItem** object.| 13304 13305**Error codes** 13306 13307For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 13308 13309| ID| Error Message | 13310| -------- | ------------------------------------------------------------ | 13311| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. 2. Parameter verification failed. | 13312 13313**Example** 13314 13315```ts 13316// xxx.ets 13317import { webview } from '@kit.ArkWeb'; 13318import { BusinessError } from '@kit.BasicServicesKit'; 13319 13320@Entry 13321@Component 13322struct WebComponent { 13323 controller: webview.WebviewController = new webview.WebviewController(); 13324 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13325 failedData: Uint8Array = new Uint8Array(); 13326 13327 build() { 13328 Column() { 13329 Button('setDownloadDelegate') 13330 .onClick(() => { 13331 try { 13332 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13333 console.log("will start a download."); 13334 // Pass in a download path and start the download. 13335 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13336 }) 13337 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13338 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13339 }) 13340 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13341 console.log("download failed guid: " + webDownloadItem.getGuid()); 13342 // Serialize the failed download to a byte array. 13343 this.failedData = webDownloadItem.serialize(); 13344 }) 13345 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13346 console.log("download finish guid: " + webDownloadItem.getGuid()); 13347 }) 13348 this.controller.setDownloadDelegate(this.delegate); 13349 } catch (error) { 13350 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13351 } 13352 }) 13353 Button('startDownload') 13354 .onClick(() => { 13355 try { 13356 this.controller.startDownload('https://www.example.com'); 13357 } catch (error) { 13358 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13359 } 13360 }) 13361 Button('resumeDownload') 13362 .onClick(() => { 13363 try { 13364 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13365 } catch (error) { 13366 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13367 } 13368 }) 13369 Web({ src: 'www.example.com', controller: this.controller }) 13370 } 13371 } 13372} 13373``` 13374 13375### start<sup>11+</sup> 13376 13377start(downloadPath: string): void 13378 13379Starts a download to a specified directory. 13380 13381> **NOTE** 13382> 13383>This API must be used in the **onBeforeDownload** callback of **WebDownloadDelegateb**. 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. 13384 13385**System capability**: SystemCapability.Web.Webview.Core 13386 13387**Parameters** 13388 13389| Name| Type | Mandatory| Description | 13390| ------ | ---------------------- | ---- | ------------------------------| 13391| downloadPath | string | Yes | Path (including the file name) of the file to download.| 13392 13393**Error codes** 13394 13395For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 13396 13397| ID| Error Message | 13398| -------- | ------------------------------------------------------------ | 13399| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. 2. Parameter verification failed. | 13400 13401**Example** 13402 13403```ts 13404// xxx.ets 13405import { webview } from '@kit.ArkWeb'; 13406import { BusinessError } from '@kit.BasicServicesKit'; 13407 13408@Entry 13409@Component 13410struct WebComponent { 13411 controller: webview.WebviewController = new webview.WebviewController(); 13412 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13413 failedData: Uint8Array = new Uint8Array(); 13414 13415 build() { 13416 Column() { 13417 Button('setDownloadDelegate') 13418 .onClick(() => { 13419 try { 13420 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13421 console.log("will start a download."); 13422 // Pass in a download path and start the download. 13423 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13424 }) 13425 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13426 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13427 }) 13428 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13429 console.log("download failed guid: " + webDownloadItem.getGuid()); 13430 // Serialize the failed download to a byte array. 13431 this.failedData = webDownloadItem.serialize(); 13432 }) 13433 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13434 console.log("download finish guid: " + webDownloadItem.getGuid()); 13435 }) 13436 this.controller.setDownloadDelegate(this.delegate); 13437 } catch (error) { 13438 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13439 } 13440 }) 13441 Button('startDownload') 13442 .onClick(() => { 13443 try { 13444 this.controller.startDownload('https://www.example.com'); 13445 } catch (error) { 13446 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13447 } 13448 }) 13449 Button('resumeDownload') 13450 .onClick(() => { 13451 try { 13452 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13453 } catch (error) { 13454 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13455 } 13456 }) 13457 Web({ src: 'www.example.com', controller: this.controller }) 13458 } 13459 } 13460} 13461``` 13462 13463### cancel<sup>11+</sup> 13464 13465cancel(): void 13466 13467Cancels a download task. 13468 13469**System capability**: SystemCapability.Web.Webview.Core 13470 13471**Example** 13472 13473```ts 13474// xxx.ets 13475import { webview } from '@kit.ArkWeb'; 13476import { BusinessError } from '@kit.BasicServicesKit'; 13477 13478@Entry 13479@Component 13480struct WebComponent { 13481 controller: webview.WebviewController = new webview.WebviewController(); 13482 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13483 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13484 failedData: Uint8Array = new Uint8Array(); 13485 13486 build() { 13487 Column() { 13488 Button('setDownloadDelegate') 13489 .onClick(() => { 13490 try { 13491 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13492 console.log("will start a download."); 13493 // Pass in a download path and start the download. 13494 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13495 }) 13496 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13497 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13498 this.download = webDownloadItem; 13499 }) 13500 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13501 console.log("download failed guid: " + webDownloadItem.getGuid()); 13502 // Serialize the failed download to a byte array. 13503 this.failedData = webDownloadItem.serialize(); 13504 }) 13505 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13506 console.log("download finish guid: " + webDownloadItem.getGuid()); 13507 }) 13508 this.controller.setDownloadDelegate(this.delegate); 13509 } catch (error) { 13510 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13511 } 13512 }) 13513 Button('startDownload') 13514 .onClick(() => { 13515 try { 13516 this.controller.startDownload('https://www.example.com'); 13517 } catch (error) { 13518 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13519 } 13520 }) 13521 Button('resumeDownload') 13522 .onClick(() => { 13523 try { 13524 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13525 } catch (error) { 13526 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13527 } 13528 }) 13529 Button('cancel') 13530 .onClick(() => { 13531 try { 13532 this.download.cancel(); 13533 } catch (error) { 13534 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13535 } 13536 }) 13537 Web({ src: 'www.example.com', controller: this.controller }) 13538 } 13539 } 13540} 13541``` 13542 13543### pause<sup>11+</sup> 13544 13545pause(): void 13546 13547Pauses a download task. 13548 13549**System capability**: SystemCapability.Web.Webview.Core 13550 13551**Error codes** 13552 13553For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 13554 13555| ID | Error Message | 13556| -------- | ------------------------------------------------------------ | 13557| 17100019 | The download task is not started yet. | 13558 13559**Example** 13560 13561```ts 13562// xxx.ets 13563import { webview } from '@kit.ArkWeb'; 13564import { BusinessError } from '@kit.BasicServicesKit'; 13565 13566@Entry 13567@Component 13568struct WebComponent { 13569 controller: webview.WebviewController = new webview.WebviewController(); 13570 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13571 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13572 failedData: Uint8Array = new Uint8Array(); 13573 13574 build() { 13575 Column() { 13576 Button('setDownloadDelegate') 13577 .onClick(() => { 13578 try { 13579 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13580 console.log("will start a download."); 13581 // Pass in a download path and start the download. 13582 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13583 }) 13584 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13585 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13586 this.download = webDownloadItem; 13587 }) 13588 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13589 console.log("download failed guid: " + webDownloadItem.getGuid()); 13590 // Serialize the failed download to a byte array. 13591 this.failedData = webDownloadItem.serialize(); 13592 }) 13593 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13594 console.log("download finish guid: " + webDownloadItem.getGuid()); 13595 }) 13596 this.controller.setDownloadDelegate(this.delegate); 13597 } catch (error) { 13598 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13599 } 13600 }) 13601 Button('startDownload') 13602 .onClick(() => { 13603 try { 13604 this.controller.startDownload('https://www.example.com'); 13605 } catch (error) { 13606 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13607 } 13608 }) 13609 Button('resumeDownload') 13610 .onClick(() => { 13611 try { 13612 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13613 } catch (error) { 13614 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13615 } 13616 }) 13617 Button('cancel') 13618 .onClick(() => { 13619 try { 13620 this.download.cancel(); 13621 } catch (error) { 13622 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13623 } 13624 }) 13625 Button('pause') 13626 .onClick(() => { 13627 try { 13628 this.download.pause(); 13629 } catch (error) { 13630 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13631 } 13632 }) 13633 Web({ src: 'www.example.com', controller: this.controller }) 13634 } 13635 } 13636} 13637``` 13638 13639### resume<sup>11+</sup> 13640 13641resume(): void 13642 13643Resumes a download task. 13644 13645**System capability**: SystemCapability.Web.Webview.Core 13646 13647**Error codes** 13648 13649For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 13650 13651| ID | Error Message | 13652| -------- | ------------------------------------------------------------ | 13653| 17100016 | The download task is not paused. | 13654 13655**Example** 13656 13657```ts 13658// xxx.ets 13659import { webview } from '@kit.ArkWeb'; 13660import { BusinessError } from '@kit.BasicServicesKit'; 13661 13662@Entry 13663@Component 13664struct WebComponent { 13665 controller: webview.WebviewController = new webview.WebviewController(); 13666 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13667 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13668 failedData: Uint8Array = new Uint8Array(); 13669 13670 build() { 13671 Column() { 13672 Button('setDownloadDelegate') 13673 .onClick(() => { 13674 try { 13675 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13676 console.log("will start a download."); 13677 // Pass in a download path and start the download. 13678 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13679 }) 13680 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13681 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13682 this.download = webDownloadItem; 13683 }) 13684 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13685 console.log("download failed guid: " + webDownloadItem.getGuid()); 13686 // Serialize the failed download to a byte array. 13687 this.failedData = webDownloadItem.serialize(); 13688 }) 13689 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13690 console.log("download finish guid: " + webDownloadItem.getGuid()); 13691 }) 13692 this.controller.setDownloadDelegate(this.delegate); 13693 } catch (error) { 13694 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13695 } 13696 }) 13697 Button('startDownload') 13698 .onClick(() => { 13699 try { 13700 this.controller.startDownload('https://www.example.com'); 13701 } catch (error) { 13702 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13703 } 13704 }) 13705 Button('resumeDownload') 13706 .onClick(() => { 13707 try { 13708 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13709 } catch (error) { 13710 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13711 } 13712 }) 13713 Button('cancel') 13714 .onClick(() => { 13715 try { 13716 this.download.cancel(); 13717 } catch (error) { 13718 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13719 } 13720 }) 13721 Button('pause') 13722 .onClick(() => { 13723 try { 13724 this.download.pause(); 13725 } catch (error) { 13726 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13727 } 13728 }) 13729 Button('resume') 13730 .onClick(() => { 13731 try { 13732 this.download.resume(); 13733 } catch (error) { 13734 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13735 } 13736 }) 13737 Web({ src: 'www.example.com', controller: this.controller }) 13738 } 13739 } 13740} 13741``` 13742 13743## WebDownloadDelegate<sup>11+</sup> 13744 13745 Implements a **WebDownloadDelegate** class. You can use the callbacks of this class to notify users of the download state. 13746 13747### onBeforeDownload<sup>11+</sup> 13748 13749onBeforeDownload(callback: Callback\<WebDownloadItem>): void 13750 13751Invoked 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. 13752 13753> **NOTE** 13754> 13755>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. 13756 13757**System capability**: SystemCapability.Web.Webview.Core 13758 13759**Parameters** 13760 13761| Name | Type | Mandatory| Description | 13762| ------- | ------ | ---- | :------------- | 13763| callback | Callback\<[WebDownloadItem](#webdownloaditem11)> | Yes | Callback for triggering a download.| 13764 13765**Example** 13766 13767```ts 13768// xxx.ets 13769import { webview } from '@kit.ArkWeb'; 13770import { BusinessError } from '@kit.BasicServicesKit'; 13771 13772@Entry 13773@Component 13774struct WebComponent { 13775 controller: webview.WebviewController = new webview.WebviewController(); 13776 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13777 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13778 failedData: Uint8Array = new Uint8Array(); 13779 13780 build() { 13781 Column() { 13782 Button('setDownloadDelegate') 13783 .onClick(() => { 13784 try { 13785 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13786 console.log("will start a download."); 13787 // Pass in a download path and start the download. 13788 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13789 }) 13790 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13791 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13792 this.download = webDownloadItem; 13793 }) 13794 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13795 console.log("download failed guid: " + webDownloadItem.getGuid()); 13796 // Serialize the failed download to a byte array. 13797 this.failedData = webDownloadItem.serialize(); 13798 }) 13799 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13800 console.log("download finish guid: " + webDownloadItem.getGuid()); 13801 }) 13802 this.controller.setDownloadDelegate(this.delegate); 13803 } catch (error) { 13804 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13805 } 13806 }) 13807 Button('startDownload') 13808 .onClick(() => { 13809 try { 13810 this.controller.startDownload('https://www.example.com'); 13811 } catch (error) { 13812 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13813 } 13814 }) 13815 Button('resumeDownload') 13816 .onClick(() => { 13817 try { 13818 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13819 } catch (error) { 13820 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13821 } 13822 }) 13823 Button('cancel') 13824 .onClick(() => { 13825 try { 13826 this.download.cancel(); 13827 } catch (error) { 13828 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13829 } 13830 }) 13831 Button('pause') 13832 .onClick(() => { 13833 try { 13834 this.download.pause(); 13835 } catch (error) { 13836 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13837 } 13838 }) 13839 Button('resume') 13840 .onClick(() => { 13841 try { 13842 this.download.resume(); 13843 } catch (error) { 13844 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13845 } 13846 }) 13847 Web({ src: 'www.example.com', controller: this.controller }) 13848 } 13849 } 13850} 13851``` 13852 13853### onDownloadUpdated<sup>11+</sup> 13854 13855onDownloadUpdated(callback: Callback\<WebDownloadItem>): void 13856 13857Invoked when the download progress is updated. 13858 13859**System capability**: SystemCapability.Web.Webview.Core 13860 13861**Parameters** 13862 13863| Name | Type | Mandatory| Description | 13864| ------- | ------ | ---- | :------------- | 13865| callback | Callback\<[WebDownloadItem](#webdownloaditem11)> | Yes | Callback invoked when the downloaded progress is updated.| 13866 13867**Example** 13868 13869```ts 13870// xxx.ets 13871import { webview } from '@kit.ArkWeb'; 13872import { BusinessError } from '@kit.BasicServicesKit'; 13873 13874@Entry 13875@Component 13876struct WebComponent { 13877 controller: webview.WebviewController = new webview.WebviewController(); 13878 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13879 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13880 failedData: Uint8Array = new Uint8Array(); 13881 13882 build() { 13883 Column() { 13884 Button('setDownloadDelegate') 13885 .onClick(() => { 13886 try { 13887 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13888 console.log("will start a download."); 13889 // Pass in a download path and start the download. 13890 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13891 }) 13892 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13893 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13894 this.download = webDownloadItem; 13895 }) 13896 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13897 console.log("download failed guid: " + webDownloadItem.getGuid()); 13898 // Serialize the failed download to a byte array. 13899 this.failedData = webDownloadItem.serialize(); 13900 }) 13901 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13902 console.log("download finish guid: " + webDownloadItem.getGuid()); 13903 }) 13904 this.controller.setDownloadDelegate(this.delegate); 13905 } catch (error) { 13906 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13907 } 13908 }) 13909 Button('startDownload') 13910 .onClick(() => { 13911 try { 13912 this.controller.startDownload('https://www.example.com'); 13913 } catch (error) { 13914 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13915 } 13916 }) 13917 Button('resumeDownload') 13918 .onClick(() => { 13919 try { 13920 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13921 } catch (error) { 13922 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13923 } 13924 }) 13925 Button('cancel') 13926 .onClick(() => { 13927 try { 13928 this.download.cancel(); 13929 } catch (error) { 13930 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13931 } 13932 }) 13933 Button('pause') 13934 .onClick(() => { 13935 try { 13936 this.download.pause(); 13937 } catch (error) { 13938 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13939 } 13940 }) 13941 Button('resume') 13942 .onClick(() => { 13943 try { 13944 this.download.resume(); 13945 } catch (error) { 13946 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13947 } 13948 }) 13949 Web({ src: 'www.example.com', controller: this.controller }) 13950 } 13951 } 13952} 13953``` 13954 13955### onDownloadFinish<sup>11+</sup> 13956 13957onDownloadFinish(callback: Callback\<WebDownloadItem>): void 13958 13959Invoked when the download is complete. 13960 13961**System capability**: SystemCapability.Web.Webview.Core 13962 13963**Parameters** 13964 13965| Name | Type | Mandatory| Description | 13966| ------- | ------ | ---- | :------------- | 13967| callback | Callback\<[WebDownloadItem](#webdownloaditem11)> | Yes | Callback invoked when the download is complete.| 13968 13969**Example** 13970 13971```ts 13972// xxx.ets 13973import { webview } from '@kit.ArkWeb'; 13974import { BusinessError } from '@kit.BasicServicesKit'; 13975 13976@Entry 13977@Component 13978struct WebComponent { 13979 controller: webview.WebviewController = new webview.WebviewController(); 13980 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13981 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13982 failedData: Uint8Array = new Uint8Array(); 13983 13984 build() { 13985 Column() { 13986 Button('setDownloadDelegate') 13987 .onClick(() => { 13988 try { 13989 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13990 console.log("will start a download."); 13991 // Pass in a download path and start the download. 13992 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13993 }) 13994 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13995 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13996 this.download = webDownloadItem; 13997 }) 13998 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13999 console.log("download failed guid: " + webDownloadItem.getGuid()); 14000 // Serialize the failed download to a byte array. 14001 this.failedData = webDownloadItem.serialize(); 14002 }) 14003 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 14004 console.log("download finish guid: " + webDownloadItem.getGuid()); 14005 }) 14006 this.controller.setDownloadDelegate(this.delegate); 14007 } catch (error) { 14008 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14009 } 14010 }) 14011 Button('startDownload') 14012 .onClick(() => { 14013 try { 14014 this.controller.startDownload('https://www.example.com'); 14015 } catch (error) { 14016 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14017 } 14018 }) 14019 Button('resumeDownload') 14020 .onClick(() => { 14021 try { 14022 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 14023 } catch (error) { 14024 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14025 } 14026 }) 14027 Button('cancel') 14028 .onClick(() => { 14029 try { 14030 this.download.cancel(); 14031 } catch (error) { 14032 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14033 } 14034 }) 14035 Button('pause') 14036 .onClick(() => { 14037 try { 14038 this.download.pause(); 14039 } catch (error) { 14040 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14041 } 14042 }) 14043 Button('resume') 14044 .onClick(() => { 14045 try { 14046 this.download.resume(); 14047 } catch (error) { 14048 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14049 } 14050 }) 14051 Web({ src: 'www.example.com', controller: this.controller }) 14052 } 14053 } 14054} 14055``` 14056 14057### onDownloadFailed<sup>11+</sup> 14058 14059onDownloadFailed(callback: Callback\<WebDownloadItem>): void 14060 14061Invoked when the download fails. 14062 14063**System capability**: SystemCapability.Web.Webview.Core 14064 14065**Parameters** 14066 14067| Name | Type | Mandatory| Description | 14068| ------- | ------ | ---- | :------------- | 14069| callback | Callback\<[WebDownloadItem](#webdownloaditem11)> | Yes | Callback invoked when the download fails.| 14070 14071**Example** 14072 14073```ts 14074// xxx.ets 14075import { webview } from '@kit.ArkWeb'; 14076import { BusinessError } from '@kit.BasicServicesKit'; 14077 14078@Entry 14079@Component 14080struct WebComponent { 14081 controller: webview.WebviewController = new webview.WebviewController(); 14082 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 14083 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 14084 failedData: Uint8Array = new Uint8Array(); 14085 14086 build() { 14087 Column() { 14088 Button('setDownloadDelegate') 14089 .onClick(() => { 14090 try { 14091 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 14092 console.log("will start a download."); 14093 // Pass in a download path and start the download. 14094 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 14095 }) 14096 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 14097 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 14098 this.download = webDownloadItem; 14099 }) 14100 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 14101 console.log("download failed guid: " + webDownloadItem.getGuid()); 14102 // Serialize the failed download to a byte array. 14103 this.failedData = webDownloadItem.serialize(); 14104 }) 14105 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 14106 console.log("download finish guid: " + webDownloadItem.getGuid()); 14107 }) 14108 this.controller.setDownloadDelegate(this.delegate); 14109 } catch (error) { 14110 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14111 } 14112 }) 14113 Button('startDownload') 14114 .onClick(() => { 14115 try { 14116 this.controller.startDownload('https://www.example.com'); 14117 } catch (error) { 14118 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14119 } 14120 }) 14121 Button('resumeDownload') 14122 .onClick(() => { 14123 try { 14124 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 14125 } catch (error) { 14126 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14127 } 14128 }) 14129 Button('cancel') 14130 .onClick(() => { 14131 try { 14132 this.download.cancel(); 14133 } catch (error) { 14134 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14135 } 14136 }) 14137 Button('pause') 14138 .onClick(() => { 14139 try { 14140 this.download.pause(); 14141 } catch (error) { 14142 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14143 } 14144 }) 14145 Button('resume') 14146 .onClick(() => { 14147 try { 14148 this.download.resume(); 14149 } catch (error) { 14150 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14151 } 14152 }) 14153 Web({ src: 'www.example.com', controller: this.controller }) 14154 } 14155 } 14156} 14157``` 14158 14159## WebDownloadManager<sup>11+</sup> 14160 14161Implements a **WebDownloadManager** class. You can use the APIs of this class to resume failed download tasks. 14162 14163### setDownloadDelegate<sup>11+</sup> 14164 14165static setDownloadDelegate(delegate: WebDownloadDelegate): void 14166 14167Sets the delegate used to receive download progress triggered from **WebDownloadManager**. 14168 14169**System capability**: SystemCapability.Web.Webview.Core 14170 14171**Parameters** 14172 14173| Name | Type | Mandatory | Description | 14174| ---------------| ------- | ---- | ------------- | 14175| delegate | [WebDownloadDelegate](#webdownloaddelegate11) | Yes | Delegate used to receive the download progress.| 14176 14177**Example** 14178 14179```ts 14180// xxx.ets 14181import { webview } from '@kit.ArkWeb'; 14182import { BusinessError } from '@kit.BasicServicesKit'; 14183 14184@Entry 14185@Component 14186struct WebComponent { 14187 controller: webview.WebviewController = new webview.WebviewController(); 14188 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 14189 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 14190 failedData: Uint8Array = new Uint8Array(); 14191 14192 build() { 14193 Column() { 14194 Button('setDownloadDelegate') 14195 .onClick(() => { 14196 try { 14197 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 14198 console.log("will start a download."); 14199 // Pass in a download path and start the download. 14200 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 14201 }) 14202 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 14203 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 14204 this.download = webDownloadItem; 14205 }) 14206 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 14207 console.log("download failed guid: " + webDownloadItem.getGuid()); 14208 // Serialize the failed download to a byte array. 14209 this.failedData = webDownloadItem.serialize(); 14210 }) 14211 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 14212 console.log("download finish guid: " + webDownloadItem.getGuid()); 14213 }) 14214 this.controller.setDownloadDelegate(this.delegate); 14215 webview.WebDownloadManager.setDownloadDelegate(this.delegate); 14216 } catch (error) { 14217 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14218 } 14219 }) 14220 Button('startDownload') 14221 .onClick(() => { 14222 try { 14223 this.controller.startDownload('https://www.example.com'); 14224 } catch (error) { 14225 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14226 } 14227 }) 14228 Button('resumeDownload') 14229 .onClick(() => { 14230 try { 14231 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 14232 } catch (error) { 14233 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14234 } 14235 }) 14236 Button('cancel') 14237 .onClick(() => { 14238 try { 14239 this.download.cancel(); 14240 } catch (error) { 14241 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14242 } 14243 }) 14244 Button('pause') 14245 .onClick(() => { 14246 try { 14247 this.download.pause(); 14248 } catch (error) { 14249 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14250 } 14251 }) 14252 Button('resume') 14253 .onClick(() => { 14254 try { 14255 this.download.resume(); 14256 } catch (error) { 14257 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14258 } 14259 }) 14260 Web({ src: 'www.example.com', controller: this.controller }) 14261 } 14262 } 14263} 14264``` 14265 14266### resumeDownload<sup>11+</sup> 14267 14268static resumeDownload(webDownloadItem: WebDownloadItem): void 14269 14270Resumes a failed download task. 14271 14272**System capability**: SystemCapability.Web.Webview.Core 14273 14274**Parameters** 14275 14276| Name | Type | Mandatory | Description | 14277| ---------------| ------- | ---- | ------------- | 14278| webDownloadItem | [WebDownloadItem](#webdownloaditem11) | Yes | Download task to resume.| 14279 14280**Error codes** 14281 14282For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14283 14284| ID| Error Message | 14285| -------- | ------------------------------------- | 14286| 17100018 | No WebDownloadDelegate has been set yet. | 14287 14288**Example** 14289 14290```ts 14291// xxx.ets 14292import { webview } from '@kit.ArkWeb'; 14293import { BusinessError } from '@kit.BasicServicesKit'; 14294 14295@Entry 14296@Component 14297struct WebComponent { 14298 controller: webview.WebviewController = new webview.WebviewController(); 14299 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 14300 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 14301 failedData: Uint8Array = new Uint8Array(); 14302 14303 build() { 14304 Column() { 14305 Button('setDownloadDelegate') 14306 .onClick(() => { 14307 try { 14308 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 14309 console.log("will start a download."); 14310 // Pass in a download path and start the download. 14311 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 14312 }) 14313 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 14314 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 14315 this.download = webDownloadItem; 14316 }) 14317 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 14318 console.log("download failed guid: " + webDownloadItem.getGuid()); 14319 // Serialize the failed download to a byte array. 14320 this.failedData = webDownloadItem.serialize(); 14321 }) 14322 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 14323 console.log("download finish guid: " + webDownloadItem.getGuid()); 14324 }) 14325 this.controller.setDownloadDelegate(this.delegate); 14326 webview.WebDownloadManager.setDownloadDelegate(this.delegate); 14327 } catch (error) { 14328 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14329 } 14330 }) 14331 Button('startDownload') 14332 .onClick(() => { 14333 try { 14334 this.controller.startDownload('https://www.example.com'); 14335 } catch (error) { 14336 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14337 } 14338 }) 14339 Button('resumeDownload') 14340 .onClick(() => { 14341 try { 14342 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 14343 } catch (error) { 14344 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14345 } 14346 }) 14347 Button('cancel') 14348 .onClick(() => { 14349 try { 14350 this.download.cancel(); 14351 } catch (error) { 14352 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14353 } 14354 }) 14355 Button('pause') 14356 .onClick(() => { 14357 try { 14358 this.download.pause(); 14359 } catch (error) { 14360 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14361 } 14362 }) 14363 Button('resume') 14364 .onClick(() => { 14365 try { 14366 this.download.resume(); 14367 } catch (error) { 14368 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14369 } 14370 }) 14371 Web({ src: 'www.example.com', controller: this.controller }) 14372 } 14373 } 14374} 14375``` 14376 14377## ProxySchemeFilter<sup>16+</sup> 14378 14379Filters the scheme that uses the proxy. 14380 14381**System capability**: SystemCapability.Web.Webview.Core 14382 14383| Name | Value| Description | 14384| ------------- | -- |----------------------------------------- | 14385| MATCH_ALL_SCHEMES | 0 |All schemes use proxies.| 14386| MATCH_HTTP | 1 |HTTP requests use proxies.| 14387| MATCH_HTTPS | 2 |HTTPS requests use proxies.| 14388 14389## ProxyConfig<sup>16+</sup> 14390 14391Implements a ProxyConfig class. You can use the APIs of this class to configure proxies. 14392 14393### insertProxyRule<sup>16+</sup> 14394 14395insertProxyRule(proxyRule: string, schemeFilter?: ProxySchemeFilter): void 14396 14397Inserts a rule to specify a proxy for URLs matching **schemeFilter**. If **schemeFilter** is empty, all URLs use the specified proxy. 14398 14399**System capability**: SystemCapability.Web.Webview.Core 14400 14401**Parameters** 14402 14403| Name | Type | Mandatory | Description | 14404| ---------------| ------- | ---- | ------------- | 14405| proxyRule | string | Yes | The specified proxy.| 14406| schemeFilter | [ProxySchemeFilter](#proxyschemefilter16) | No | Used to filter URLs to use the proxy. Default value: **MATCH_ALL_SCHEMES**.| 14407 14408**Error codes** 14409 14410For details about the following error codes, see [Universal Error Codes](../errorcode-universal.md). 14411 14412| ID| Error Message | 14413| -------- | ------------------------------------- | 14414| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 14415 14416**Example** 14417 14418For details about the complete sample code, see [removeProxyOverride](#removeproxyoverride16). 14419 14420### insertDirectRule<sup>16+</sup> 14421 14422insertDirectRule(schemeFilter?: ProxySchemeFilter): void 14423 14424Inserts a proxy rule to specify that URLs matching **schemeFilter** are directly connected to the server. 14425 14426**System capability**: SystemCapability.Web.Webview.Core 14427 14428**Parameters** 14429 14430| Name | Type | Mandatory | Description | 14431| ---------------| ------- | ---- | ------------- | 14432| schemeFilter | [ProxySchemeFilter](#proxyschemefilter16) | No | Used to filter URLs to be directly connected to the server. Default value: **MATCH_ALL_SCHEMES**.| 14433 14434**Error codes** 14435 14436For details about the following error codes, see [Universal Error Codes](../errorcode-universal.md). 14437 14438| ID| Error Message | 14439| -------- | ------------------------------------- | 14440| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 14441 14442**Example** 14443 14444For details about the complete sample code, see [removeProxyOverride](#removeproxyoverride16). 14445 14446### insertBypassRule<sup>16+</sup> 14447 14448insertBypassRule(bypassRule: string): void 14449 14450Inserts a bypass rule to specify the URLs that should bypass the proxy and directly connect to the server. 14451 14452**System capability**: SystemCapability.Web.Webview.Core 14453 14454**Parameters** 14455 14456| Name | Type | Mandatory | Description | 14457| ---------------| ------- | ---- | ------------- | 14458| bypassRule | string | Yes | Used to specify the URLs that should bypass the proxy.| 14459 14460**Error codes** 14461 14462For details about the following error codes, see [Universal Error Codes](../errorcode-universal.md). 14463 14464| ID| Error Message | 14465| -------- | ------------------------------------- | 14466| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 14467 14468**Example** 14469 14470For details about the complete sample code, see [removeProxyOverride](#removeproxyoverride16). 14471 14472### bypassHostnamesWithoutPeriod<sup>16+</sup> 14473 14474bypassHostnamesWithoutPeriod(): void 14475 14476Specifies that domain names without a period should bypass the proxy and directly connect to the server. 14477 14478**System capability**: SystemCapability.Web.Webview.Core 14479 14480**Example** 14481 14482For details about the complete sample code, see [removeProxyOverride](#removeproxyoverride16). 14483 14484### clearImplicitRules<sup>16+</sup> 14485 14486clearImplicitRules(): void 14487 14488Overrides 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.) 14489 14490**System capability**: SystemCapability.Web.Webview.Core 14491 14492**Example** 14493 14494For details about the complete sample code, see [removeProxyOverride](#removeproxyoverride16). 14495 14496### enableReverseBypass<sup>16+</sup> 14497 14498enableReverseBypass(reverse: boolean): void 14499 14500Reverses the bypass rule. 14501 14502**System capability**: SystemCapability.Web.Webview.Core 14503 14504**Parameters** 14505 14506| Name | Type | Mandatory | Description | 14507| ---------------| ------- | ---- | ------------- | 14508| reverse | boolean | Yes | Whether to reverse the bypass rule. The default value is **false**, indicating the bypass rule is not reversed. The value **true** indicates the opposite.| 14509 14510**Error codes** 14511 14512For details about the following error codes, see [Universal Error Codes](../errorcode-universal.md). 14513 14514| ID| Error Message | 14515| -------- | ------------------------------------- | 14516| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 14517 14518**Example** 14519 14520For details about the complete sample code, see [removeProxyOverride](#removeproxyoverride16). 14521 14522### getBypassRules<sup>16+</sup> 14523 14524getBypassRules(): Array\<string\> 14525 14526Obtains the list of URLs that do not use the proxy. 14527 14528**System capability**: SystemCapability.Web.Webview.Core 14529 14530**Return value** 14531 14532| Type | Description | 14533| ------ | ------------------------- | 14534| Array\<string\> | List of URLs that do not use the proxy.| 14535 14536**Example** 14537 14538For details about the complete sample code, see [removeProxyOverride](#removeproxyoverride16). 14539 14540### getProxyRules<sup>16+</sup> 14541 14542getProxyRules(): Array\<ProxyRule\> 14543 14544Obtains proxy rules. 14545 14546**System capability**: SystemCapability.Web.Webview.Core 14547 14548**Return value** 14549 14550| Type | Description | 14551| ------ | ------------------------- | 14552| Array\<[ProxyRule](#proxyrule16)\> | Proxy rule.| 14553 14554**Example** 14555 14556For details about the complete sample code, see [removeProxyOverride](#removeproxyoverride16). 14557 14558### isReverseBypassEnabled<sup>16+</sup> 14559 14560isReverseBypassEnabled(): boolean 14561 14562Obtains the value of [enableReverseBypass](#enablereversebypass16). For details, see [enableReverseBypass](#enablereversebypass16). 14563 14564**System capability**: SystemCapability.Web.Webview.Core 14565 14566**Return value** 14567 14568| Type | Description | 14569| ------ | ------------------------- | 14570| boolean | Value of [enableReverseBypass](#enablereversebypass16). The default value is **false**, indicating the bypass rule is not reversed. The value **true** indicates the opposite.| 14571 14572**Example** 14573 14574For details about the complete sample code, see [removeProxyOverride](#removeproxyoverride16). 14575 14576 14577## ProxyRule<sup>16+</sup> 14578 14579Indicates the proxy rule used in the [insertProxyRule](#insertproxyrule16). 14580 14581### getSchemeFilter<sup>16+</sup> 14582 14583getSchemeFilter(): ProxySchemeFilter 14584 14585Obtains the [ProxySchemeFilter](#proxyschemefilter16) information in the proxy rule. 14586 14587**System capability**: SystemCapability.Web.Webview.Core 14588 14589**Return value** 14590 14591| Type | Description | 14592| ------ | ------------------------- | 14593| [ProxySchemeFilter](#proxyschemefilter16) | The [ProxySchemeFilter](#proxyschemefilter16) information in the proxy rule.| 14594 14595**Example** 14596 14597For details about the complete sample code, see [removeProxyOverride](#removeproxyoverride16). 14598 14599### getUrl<sup>16+</sup> 14600 14601getUrl(): string 14602 14603Obtains the URL specified in the proxy rule. 14604 14605**System capability**: SystemCapability.Web.Webview.Core 14606 14607**Return value** 14608 14609| Type | Description | 14610| ------ | ------------------------- | 14611| string | The URL specified in the proxy rule.| 14612 14613**Example** 14614 14615For details about the complete sample code, see [removeProxyOverride](#removeproxyoverride16). 14616 14617## OnProxyConfigChangeCallback<sup>16+</sup> 14618 14619type OnProxyConfigChangeCallback = () => void 14620 14621Called when the proxy is set successfully. 14622 14623**System capability**: SystemCapability.Web.Webview.Core 14624 14625**Example** 14626 14627For details about the complete sample code, see [removeProxyOverride](#removeproxyoverride16). 14628 14629## ProxyController<sup>16+</sup> 14630 14631Implements a **ProxyController** object to set a proxy for an application. 14632 14633### applyProxyOverride<sup>16+</sup> 14634 14635static applyProxyOverride(proxyConfig: ProxyConfig, callback: OnProxyConfigChangeCallback): void 14636 14637Set the proxy used by all webs in an application. URLs that match the bypass rule inserted through [insertBypassRule](#insertbypassrule16) 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. 14638 14639**System capability**: SystemCapability.Web.Webview.Core 14640 14641**Parameters** 14642 14643| Name | Type | Mandatory | Description | 14644| ---------------| ------- | ---- | ------------- | 14645| proxyConfig | [ProxyConfig](#proxyconfig16) | Yes | Configuration of the proxy.| 14646| callback | [OnProxyConfigChangeCallback](#onproxyconfigchangecallback16) | Yes | Callback used when the proxy is successfully set.| 14647 14648**Error codes** 14649 14650For details about the following error codes, see [Universal Error Codes](../errorcode-universal.md). 14651 14652| ID| Error Message | 14653| -------- | ------------------------------------- | 14654| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 14655 14656**Example** 14657 14658For details about the complete sample code, see [removeProxyOverride](#removeproxyoverride16). 14659 14660### removeProxyOverride<sup>16+</sup> 14661 14662static removeProxyOverride(callback: OnProxyConfigChangeCallback): void 14663 14664Removes 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. 14665 14666**System capability**: SystemCapability.Web.Webview.Core 14667 14668**Parameters** 14669 14670| Name | Type | Mandatory | Description | 14671| ---------------| ------- | ---- | ------------- | 14672| callback | [OnProxyConfigChangeCallback](#onproxyconfigchangecallback16) | Yes | Callback used when the proxy is successfully set.| 14673 14674**Error codes** 14675 14676For details about the following error codes, see [Universal Error Codes](../errorcode-universal.md). 14677 14678| ID| Error Message | 14679| -------- | ------------------------------------- | 14680| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 14681 14682**Example** 14683 14684```ts 14685// xxx.ets 14686import { webview } from '@kit.ArkWeb'; 14687import { BusinessError } from '@kit.BasicServicesKit'; 14688 14689@Entry 14690@Component 14691struct WebComponent { 14692 controller: webview.WebviewController = new webview.WebviewController(); 14693 proxyRules: webview.ProxyRule[] = []; 14694 14695 build() { 14696 Row() { 14697 Column() { 14698 Button("applyProxyOverride").onClick(()=>{ 14699 let proxyConfig:webview.ProxyConfig = new webview.ProxyConfig(); 14700 // The first proxy configuration https://proxy.XXX.com is preferentially used. 14701 // When the proxy fails, insertDirectRule is used. 14702 try { 14703 proxyConfig.insertProxyRule("https://proxy.XXX.com", webview.ProxySchemeFilter.MATCH_ALL_SCHEMES); 14704 } catch (error) { 14705 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14706 } 14707 try { 14708 proxyConfig.insertDirectRule(webview.ProxySchemeFilter.MATCH_HTTP); 14709 } catch (error) { 14710 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14711 } 14712 try { 14713 proxyConfig.insertBypassRule("*.example.com"); 14714 } catch (error) { 14715 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14716 } 14717 proxyConfig.clearImplicitRules(); 14718 proxyConfig.bypassHostnamesWithoutPeriod(); 14719 try { 14720 proxyConfig.enableReverseBypass(true); 14721 } catch (error) { 14722 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14723 } 14724 let bypassRules = proxyConfig.getBypassRules(); 14725 for (let i = 0; i < bypassRules.length; i++) { 14726 console.log("bypassRules: " + bypassRules[i]); 14727 } 14728 this.proxyRules = proxyConfig.getProxyRules(); 14729 for (let i = 0; i < this.proxyRules.length; i++) { 14730 console.log("SchemeFiletr: " + this.proxyRules[i].getSchemeFilter()); 14731 console.log("Url: " + this.proxyRules[i].getUrl()); 14732 } 14733 let isReverseBypassRule = proxyConfig.isReverseBypassEnabled(); 14734 console.log("isReverseBypassRules: " + isReverseBypassRule); 14735 try { 14736 webview.ProxyController.applyProxyOverride(proxyConfig, () => { 14737 console.log("PROXYCONTROLLER proxy changed"); 14738 }); 14739 } catch (error) { 14740 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14741 } 14742 }) 14743 Button("loadUrl-https").onClick(()=>{ 14744 this.controller.loadUrl("https://www.example.com") 14745 }) 14746 Button("loadUrl-http").onClick(()=>{ 14747 this.controller.loadUrl("http://www.example.com") 14748 }) 14749 Button("removeProxyOverride").onClick(()=>{ 14750 try { 14751 webview.ProxyController.removeProxyOverride(() => { 14752 console.log("PROXYCONTROLLER proxy changed"); 14753 }); 14754 } catch (error) { 14755 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14756 } 14757 }) 14758 Web({ src: 'www.example.com', controller: this.controller}) 14759 } 14760 .width('100%') 14761 } 14762 .height('100%') 14763 } 14764} 14765 14766``` 14767 14768## WebHttpBodyStream<sup>12+</sup> 14769 14770Represents 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. 14771 14772### initialize<sup>12+</sup> 14773 14774initialize(): Promise\<void\> 14775 14776Initializes this **WebHttpBodyStream** instance. 14777 14778**System capability**: SystemCapability.Web.Webview.Core 14779 14780**Return value** 14781 14782| Type | Description | 14783| ------ | ------------------------- | 14784| Promise\<void\> | Promise used to return the result.| 14785 14786**Error codes** 14787 14788For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14789 14790| ID| Error Message | 14791| -------- | ------------------------------------- | 14792| 17100022 | Failed to initialize the HTTP body stream. | 14793 14794**Example** 14795 14796```ts 14797// xxx.ets 14798import { webview } from '@kit.ArkWeb'; 14799import { BusinessError } from '@kit.BasicServicesKit'; 14800import { buffer } from '@kit.ArkTS'; 14801import { WebNetErrorList } from '@ohos.web.netErrorList' 14802 14803@Entry 14804@Component 14805struct WebComponent { 14806 controller: webview.WebviewController = new webview.WebviewController(); 14807 schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); 14808 htmlData: string = "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>"; 14809 14810 build() { 14811 Column() { 14812 Button('postUrl') 14813 .onClick(() => { 14814 try { 14815 let postData = buffer.from(this.htmlData); 14816 this.controller.postUrl('https://www.example.com', postData.buffer); 14817 } catch (error) { 14818 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14819 } 14820 }) 14821 Web({ src: 'https://www.example.com', controller: this.controller }) 14822 .onControllerAttached(() => { 14823 try { 14824 this.schemeHandler.onRequestStart((request: webview.WebSchemeHandlerRequest, resourceHandler: webview.WebResourceHandler) => { 14825 console.log("[schemeHandler] onRequestStart"); 14826 try { 14827 let stream = request.getHttpBodyStream(); 14828 if (stream) { 14829 stream.initialize().then(() => { 14830 if (!stream) { 14831 return; 14832 } 14833 console.log("[schemeHandler] onRequestStart postDataStream size:" + stream.getSize()); 14834 console.log("[schemeHandler] onRequestStart postDataStream position:" + stream.getPosition()); 14835 console.log("[schemeHandler] onRequestStart postDataStream isChunked:" + stream.isChunked()); 14836 console.log("[schemeHandler] onRequestStart postDataStream isEof:" + stream.isEof()); 14837 console.log("[schemeHandler] onRequestStart postDataStream isInMemory:" + stream.isInMemory()); 14838 stream.read(stream.getSize()).then((buffer) => { 14839 if (!stream) { 14840 return; 14841 } 14842 console.log("[schemeHandler] onRequestStart postDataStream readlength:" + buffer.byteLength); 14843 console.log("[schemeHandler] onRequestStart postDataStream isEof:" + stream.isEof()); 14844 console.log("[schemeHandler] onRequestStart postDataStream position:" + stream.getPosition()); 14845 }).catch((error: BusinessError) => { 14846 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 14847 }) 14848 }).catch((error: BusinessError) => { 14849 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 14850 }) 14851 } else { 14852 console.log("[schemeHandler] onRequestStart has no http body stream"); 14853 } 14854 } catch (error) { 14855 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14856 } 14857 14858 return false; 14859 }) 14860 14861 this.schemeHandler.onRequestStop((request: webview.WebSchemeHandlerRequest) => { 14862 console.log("[schemeHandler] onRequestStop"); 14863 }); 14864 14865 this.controller.setWebSchemeHandler('https', this.schemeHandler); 14866 } catch (error) { 14867 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14868 } 14869 }) 14870 .javaScriptAccess(true) 14871 .domStorageAccess(true) 14872 } 14873 } 14874} 14875 14876``` 14877 14878### read<sup>12+</sup> 14879 14880read(size: number): Promise\<ArrayBuffer\> 14881 14882Reads data from this **WebHttpBodyStream** instance. 14883 14884**System capability**: SystemCapability.Web.Webview.Core 14885 14886**Parameters** 14887 14888| Name | Type | Mandatory | Description | 14889| --------| ------- | ---- | ---------------------------| 14890| size | number | Yes | Number of bytes obtained from the **WebHttpBodyStream** instance.| 14891 14892**Return value** 14893 14894| Type | Description | 14895| ------ | ------------------------- | 14896| Promise\<ArrayBuffer\> | Promise used to return the result.| 14897 14898**Error codes** 14899 14900For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14901 14902| ID| Error Message | 14903| -------- | ------------------------------------- | 14904| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 14905 14906**Example** 14907 14908For the complete sample code, see [initialize](#initialize12)). 14909 14910### getSize<sup>12+</sup> 14911 14912getSize(): number 14913 14914Obtains the size of data in this **WebHttpBodyStream** instance. This API always returns zero when chunked transfer is used. 14915 14916**System capability**: SystemCapability.Web.Webview.Core 14917 14918**Return value** 14919 14920| Type | Description | 14921| ------ | ------------------------- | 14922| number | Size of data in the current **WebHttpBodyStream** instance.| 14923 14924**Example** 14925 14926For the complete sample code, see [initialize](#initialize12)). 14927 14928### getPosition<sup>12+</sup> 14929 14930getPosition(): number 14931 14932Reads the current read position in this **WebHttpBodyStream** instance. 14933 14934**System capability**: SystemCapability.Web.Webview.Core 14935 14936**Return value** 14937 14938| Type | Description | 14939| ------ | ------------------------- | 14940| number | Current read position in the **WebHttpBodyStream** instance.| 14941 14942**Example** 14943 14944For the complete sample code, see [initialize](#initialize12)). 14945 14946### isChunked<sup>12+</sup> 14947 14948isChunked(): boolean 14949 14950Checks whether this **WebHttpBodyStream** instance is transmitted by chunk. 14951 14952**System capability**: SystemCapability.Web.Webview.Core 14953 14954**Return value** 14955 14956| Type | Description | 14957| ------ | ------------------------- | 14958| boolean | Whether the **WebHttpBodyStream** instance is transmitted by chunk.| 14959 14960**Example** 14961 14962For the complete sample code, see [initialize](#initialize12)). 14963 14964### isEof<sup>12+</sup> 14965 14966isEof(): boolean 14967 14968Checks 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. 14969 14970**System capability**: SystemCapability.Web.Webview.Core 14971 14972**Return value** 14973 14974| Type | Description | 14975| ------ | ------------------------- | 14976| boolean | Whether all data in the **WebHttpBodyStream** instance has been read.| 14977 14978**Example** 14979 14980For the complete sample code, see [initialize](#initialize12)). 14981 14982### isInMemory<sup>12+</sup> 14983 14984isInMemory(): boolean 14985 14986Checks 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. 14987 14988**System capability**: SystemCapability.Web.Webview.Core 14989 14990**Return value** 14991 14992| Type | Description | 14993| ------ | ------------------------- | 14994| boolean | Whether the uploaded data in the **WebHttpBodyStream** instance is stored in memory.| 14995 14996**Example** 14997 14998For the complete sample code, see [initialize](#initialize12)). 14999 15000## WebSchemeHandlerRequest<sup>12+</sup> 15001 15002Represents a request intercepted by the **WebSchemeHandler** object. 15003 15004### getHeader<sup>12+</sup> 15005 15006getHeader(): Array\<WebHeader\> 15007 15008Obtains the information about the resource request header. 15009 15010**System capability**: SystemCapability.Web.Webview.Core 15011 15012**Return value** 15013 15014| Type | Description | 15015| -------------------------- | ---------- | 15016| Array\<[WebHeader](#webheader)\> | Information about the resource request header.| 15017 15018**Example** 15019 15020For the complete sample code, see [onRequestStart](#onrequeststart12). 15021 15022### getRequestUrl<sup>12+</sup> 15023 15024getRequestUrl(): string 15025 15026Obtains the URL of the resource request. 15027 15028**System capability**: SystemCapability.Web.Webview.Core 15029 15030**Return value** 15031 15032| Type | Description | 15033| ------ | ------------- | 15034| string | URL of the resource request.| 15035 15036**Example** 15037 15038For the complete sample code, see [onRequestStart](#onrequeststart12). 15039 15040### getRequestMethod<sup>12+</sup> 15041 15042getRequestMethod(): string 15043 15044Obtains the request method. 15045 15046**System capability**: SystemCapability.Web.Webview.Core 15047 15048**Return value** 15049 15050| Type | Description | 15051| ------ | ------------- | 15052| string | Request method.| 15053 15054**Example** 15055 15056For the complete sample code, see [onRequestStart](#onrequeststart12). 15057 15058### getReferrer<sup>12+</sup> 15059 15060getReferrer(): string 15061 15062Obtains the referrer. 15063 15064**System capability**: SystemCapability.Web.Webview.Core 15065 15066**Return value** 15067 15068| Type | Description | 15069| ------ | ------------- | 15070| string | Obtained referrer.| 15071 15072**Example** 15073 15074For the complete sample code, see [onRequestStart](#onrequeststart12). 15075 15076### isMainFrame<sup>12+</sup> 15077 15078isMainFrame(): boolean 15079 15080Checks whether the resource request is for the main frame. 15081 15082**System capability**: SystemCapability.Web.Webview.Core 15083 15084**Return value** 15085 15086| Type | Description | 15087| ------ | ------------- | 15088| boolean | Whether the resource request is for the main frame.| 15089 15090**Example** 15091 15092For the complete sample code, see [onRequestStart](#onrequeststart12). 15093 15094### hasGesture<sup>12+</sup> 15095 15096hasGesture(): boolean 15097 15098Checks whether the resource request is associated with a gesture (for example, a tap). 15099 15100**System capability**: SystemCapability.Web.Webview.Core 15101 15102**Return value** 15103 15104| Type | Description | 15105| ------ | ------------- | 15106| boolean | Whether the resource request is associated with a gesture (for example, a tap).| 15107 15108**Example** 15109 15110For the complete sample code, see [onRequestStart](#onrequeststart12). 15111 15112### getHttpBodyStream<sup>12+</sup> 15113 15114getHttpBodyStream(): WebHttpBodyStream | null 15115 15116Obtains the **WebHttpBodyStream** instance in this resource request. 15117 15118**System capability**: SystemCapability.Web.Webview.Core 15119 15120**Return value** 15121 15122| Type | Description | 15123| ------ | ------------- | 15124| [WebHttpBodyStream](#webhttpbodystream12) \| null | **WebHttpBodyStream** instance in the resource request. If there is no **WebHttpBodyStream** instance, **null** is returned.| 15125 15126**Example** 15127 15128For the complete sample code, see [onRequestStart](#onrequeststart12). 15129 15130### getRequestResourceType<sup>12+</sup> 15131 15132getRequestResourceType(): WebResourceType 15133 15134Obtains the resource type of this resource request. 15135 15136**System capability**: SystemCapability.Web.Webview.Core 15137 15138**Return value** 15139 15140| Type | Description | 15141| ------ | ------------- | 15142| [WebResourceType](#webresourcetype12) | Resource type of the resource request.| 15143 15144**Example** 15145 15146For the complete sample code, see [onRequestStart](#onrequeststart12). 15147 15148### getFrameUrl<sup>12+</sup> 15149 15150getFrameUrl(): string 15151 15152Obtains the URL of the frame that triggers this request. 15153 15154**System capability**: SystemCapability.Web.Webview.Core 15155 15156**Return value** 15157 15158| Type | Description | 15159| ------ | ------------- | 15160| string | URL of the frame that triggers the request.| 15161 15162**Example** 15163 15164For the complete sample code, see [onRequestStart](#onrequeststart12). 15165 15166## WebSchemeHandlerResponse<sup>12+</sup> 15167 15168Represents a request response. You can create a response for an intercepted request, fill in custom content, and return the response to the **Web** component. 15169 15170### constructor<sup>12+</sup> 15171 15172constructor() 15173 15174A constructor used to create a **Response** object. 15175 15176**System capability**: SystemCapability.Web.Webview.Core 15177 15178**Example** 15179 15180```ts 15181// xxx.ets 15182import { webview } from '@kit.ArkWeb'; 15183import { BusinessError } from '@kit.BasicServicesKit'; 15184import { WebNetErrorList } from '@ohos.web.netErrorList'; 15185 15186@Entry 15187@Component 15188struct WebComponent { 15189 controller: webview.WebviewController = new webview.WebviewController(); 15190 schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); 15191 15192 build() { 15193 Column() { 15194 Button('response').onClick(() => { 15195 let response = new webview.WebSchemeHandlerResponse(); 15196 try { 15197 response.setUrl("http://www.example.com") 15198 response.setStatus(200) 15199 response.setStatusText("OK") 15200 response.setMimeType("text/html") 15201 response.setEncoding("utf-8") 15202 response.setHeaderByName("header1", "value1", false) 15203 response.setNetErrorCode(WebNetErrorList.NET_OK) 15204 console.log("[schemeHandler] getUrl:" + response.getUrl()) 15205 console.log("[schemeHandler] getStatus:" + response.getStatus()) 15206 console.log("[schemeHandler] getStatusText:" + response.getStatusText()) 15207 console.log("[schemeHandler] getMimeType:" + response.getMimeType()) 15208 console.log("[schemeHandler] getEncoding:" + response.getEncoding()) 15209 console.log("[schemeHandler] getHeaderByValue:" + response.getHeaderByName("header1")) 15210 console.log("[schemeHandler] getNetErrorCode:" + response.getNetErrorCode()) 15211 15212 } catch (error) { 15213 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 15214 } 15215 }) 15216 Web({ src: 'https://www.example.com', controller: this.controller }) 15217 } 15218 } 15219} 15220 15221``` 15222 15223### setUrl<sup>12+</sup> 15224 15225setUrl(url: string): void 15226 15227Sets 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. 15228 15229**System capability**: SystemCapability.Web.Webview.Core 15230 15231**Parameters** 15232 15233| Name | Type | Mandatory | Description | 15234| --------| ------- | ---- | ---------------------------| 15235| url | string | Yes | URL to be redirected to.| 15236 15237**Example** 15238 15239For the complete sample code, see [constructor](#constructor12). 15240 15241**Error codes** 15242 15243For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15244 15245| ID| Error Message | 15246| -------- | ----------------------- | 15247| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 15248 15249### setNetErrorCode<sup>12+</sup> 15250 15251setNetErrorCode(code: WebNetErrorList): void 15252 15253Sets the network error code for this response. 15254 15255**System capability**: SystemCapability.Web.Webview.Core 15256 15257**Parameters** 15258 15259| Name | Type | Mandatory | Description | 15260| --------| ------- | ---- | ---------------------------| 15261| code | [WebNetErrorList](js-apis-netErrorList.md#webneterrorlist) | Yes | Network error code.| 15262 15263**Error codes** 15264 15265For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15266 15267| ID| Error Message | 15268| -------- | ----------------------- | 15269| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 15270 15271**Example** 15272 15273For the complete sample code, see [constructor](#constructor12). 15274 15275### setStatus<sup>12+</sup> 15276 15277setStatus(code: number): void 15278 15279Sets the HTTP status code for this response. 15280 15281**System capability**: SystemCapability.Web.Webview.Core 15282 15283**Parameters** 15284 15285| Name | Type | Mandatory | Description | 15286| --------| ------- | ---- | ---------------------------| 15287| code | number | Yes | HTTP status code.| 15288 15289**Error codes** 15290 15291For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15292 15293| ID| Error Message | 15294| -------- | ----------------------- | 15295| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 15296 15297**Example** 15298 15299For the complete sample code, see [constructor](#constructor12). 15300 15301### setStatusText<sup>12+</sup> 15302 15303setStatusText(text: string): void 15304 15305Sets the status text for this response. 15306 15307**System capability**: SystemCapability.Web.Webview.Core 15308 15309**Parameters** 15310 15311| Name | Type | Mandatory | Description | 15312| --------| ------- | ---- | ---------------------------| 15313| text | string | Yes | Status text.| 15314 15315**Error codes** 15316 15317For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15318 15319| ID| Error Message | 15320| -------- | ----------------------- | 15321| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 15322 15323**Example** 15324 15325For the complete sample code, see [constructor](#constructor12). 15326 15327### setMimeType<sup>12+</sup> 15328 15329setMimeType(type: string): void 15330 15331Sets the MIME type for this response. 15332 15333**System capability**: SystemCapability.Web.Webview.Core 15334 15335**Parameters** 15336 15337| Name | Type | Mandatory | Description | 15338| --------| ------- | ---- | ---------------------------| 15339| type | string | Yes | MIME type.| 15340 15341**Error codes** 15342 15343For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15344 15345| ID| Error Message | 15346| -------- | ----------------------- | 15347| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 15348 15349**Example** 15350 15351For the complete sample code, see [constructor](#constructor12). 15352 15353### setEncoding<sup>12+</sup> 15354 15355setEncoding(encoding: string): void 15356 15357Sets the character set for this response. 15358 15359**System capability**: SystemCapability.Web.Webview.Core 15360 15361**Parameters** 15362 15363| Name | Type | Mandatory | Description | 15364| --------| ------- | ---- | ---------------------------| 15365| encoding | string | Yes | Character set.| 15366 15367**Error codes** 15368 15369For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15370 15371| ID| Error Message | 15372| -------- | ----------------------- | 15373| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 15374 15375**Example** 15376 15377For the complete sample code, see [constructor](#constructor12). 15378 15379### setHeaderByName<sup>12+</sup> 15380 15381setHeaderByName(name: string, value: string, overwrite: boolean): void 15382 15383Sets the header information for this response. 15384 15385**System capability**: SystemCapability.Web.Webview.Core 15386 15387**Parameters** 15388 15389| Name | Type | Mandatory | Description | 15390| --------| ------- | ---- | ---------------------------| 15391| name | string | Yes | Name of the header.| 15392| value | string | Yes | Value of the header.| 15393| overwrite | boolean | Yes | Whether to override the existing header. The value **true** means to override the existing header, and **false** means the opposite.| 15394 15395**Error codes** 15396 15397For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15398 15399| ID| Error Message | 15400| -------- | ----------------------- | 15401| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 15402 15403**Example** 15404 15405For the complete sample code, see [constructor](#constructor12). 15406 15407### getUrl<sup>12+</sup> 15408 15409getUrl(): string 15410 15411Obtains the redirection URL or the URL changed due to HSTS. 15412Caution: To obtain the URL for JavaScriptProxy communication API authentication, use [getLastJavascriptProxyCallingFrameUrl<sup>12+</sup>](#getlastjavascriptproxycallingframeurl12). 15413 15414**System capability**: SystemCapability.Web.Webview.Core 15415 15416**Return value** 15417 15418| Type | Description | 15419| ------- | --------------------------------------- | 15420| string | Redirection URL or the URL changed due to HSTS.| 15421 15422**Example** 15423 15424For the complete sample code, see [constructor](#constructor12). 15425 15426### getNetErrorCode<sup>12+</sup> 15427 15428getNetErrorCode(): WebNetErrorList 15429 15430Obtains the network error code of this response. 15431 15432**System capability**: SystemCapability.Web.Webview.Core 15433 15434**Return value** 15435 15436| Type | Description | 15437| ------- | --------------------------------------- | 15438| [WebNetErrorList](js-apis-netErrorList.md#webneterrorlist) | Network error code of the response.| 15439 15440**Example** 15441 15442For the complete sample code, see [constructor](#constructor12). 15443 15444### getStatus<sup>12+</sup> 15445 15446getStatus(): number 15447 15448Obtains the HTTP status code of this response. 15449 15450**System capability**: SystemCapability.Web.Webview.Core 15451 15452**Return value** 15453 15454| Type | Description | 15455| ------- | --------------------------------------- | 15456| number | HTTP status code of the response.| 15457 15458**Example** 15459 15460For the complete sample code, see [constructor](#constructor12). 15461 15462### getStatusText<sup>12+</sup> 15463 15464getStatusText(): string 15465 15466Obtains the status text of this response. 15467 15468**System capability**: SystemCapability.Web.Webview.Core 15469 15470**Return value** 15471 15472| Type | Description | 15473| ------- | --------------------------------------- | 15474| string | Status text.| 15475 15476**Example** 15477 15478For the complete sample code, see [constructor](#constructor12). 15479 15480### getMimeType<sup>12+</sup> 15481 15482getMimeType(): string 15483 15484Obtains the MIME type of this response. 15485 15486**System capability**: SystemCapability.Web.Webview.Core 15487 15488**Return value** 15489 15490| Type | Description | 15491| ------- | --------------------------------------- | 15492| string | MIME type.| 15493 15494**Example** 15495 15496For the complete sample code, see [constructor](#constructor12). 15497 15498### getEncoding<sup>12+</sup> 15499 15500getEncoding(): string 15501 15502Obtains the character set of this response. 15503 15504**System capability**: SystemCapability.Web.Webview.Core 15505 15506**Return value** 15507 15508| Type | Description | 15509| ------- | --------------------------------------- | 15510| string | Character set.| 15511 15512**Example** 15513 15514For the complete sample code, see [constructor](#constructor12). 15515 15516### getHeaderByName<sup>12+</sup> 15517 15518getHeaderByName(name: string): string 15519 15520Obtains the character set of this response. 15521 15522**System capability**: SystemCapability.Web.Webview.Core 15523 15524**Parameters** 15525 15526| Name | Type | Mandatory| Description | 15527| ------- | ---------------- | ---- | -------------------- | 15528| name | string | Yes | Name of the header. | 15529 15530 15531**Return value** 15532 15533| Type | Description | 15534| ------- | --------------------------------------- | 15535| string | Value of the header.| 15536 15537**Example** 15538 15539For the complete sample code, see [constructor](#constructor12). 15540 15541## WebResourceHandler<sup>12+</sup> 15542 15543Represents a **WebResourceHandler** object, which can return custom response headers and response bodies to the **Web** component. 15544 15545### didReceiveResponse<sup>12+</sup> 15546 15547didReceiveResponse(response: WebSchemeHandlerResponse): void 15548 15549Sends a response header for this request. 15550 15551**System capability**: SystemCapability.Web.Webview.Core 15552 15553**Parameters** 15554 15555| Name | Type | Mandatory | Description | 15556| ---------------| ------- | ---- | ------------- | 15557| response | [WebSchemeHandlerResponse](#webschemehandlerresponse12) | Yes | Response to send.| 15558 15559**Error codes** 15560 15561For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15562 15563| ID| Error Message | 15564| -------- | ------------------------------------- | 15565| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 15566| 17100021 | The resource handler is invalid. | 15567 15568**Example** 15569 15570See [OnRequestStart](#onrequeststart12). 15571 15572### didReceiveResponseBody<sup>12+</sup> 15573 15574didReceiveResponseBody(data: ArrayBuffer): void 15575 15576Sends a response body for this request. 15577 15578**System capability**: SystemCapability.Web.Webview.Core 15579 15580**Parameters** 15581 15582| Name | Type | Mandatory | Description | 15583| ---------------| ------- | ---- | ------------- | 15584| data | ArrayBuffer | Yes | Response body.| 15585 15586**Error codes** 15587 15588For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15589 15590| ID| Error Message | 15591| -------- | ------------------------------------- | 15592| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 15593| 17100021 | The resource handler is invalid. | 15594 15595**Example** 15596 15597See [OnRequestStart](#onrequeststart12). 15598 15599### didFinish<sup>12+</sup> 15600 15601didFinish(): void 15602 15603Notifies 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. 15604 15605**System capability**: SystemCapability.Web.Webview.Core 15606 15607**Error codes** 15608 15609For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15610 15611| ID| Error Message | 15612| -------- | ------------------------------------- | 15613| 17100021 | The resource handler is invalid. | 15614 15615**Example** 15616 15617See [OnRequestStart](#onrequeststart12). 15618 15619### didFail<sup>12+</sup> 15620 15621didFail(code: WebNetErrorList): void 15622 15623Notifies the ArkWeb kernel that this request fails. Before calling this API, call [didReceiveResponse](#didreceiveresponse12) to send a response header to this request. 15624 15625**System capability**: SystemCapability.Web.Webview.Core 15626 15627**Parameters** 15628 15629| Name | Type | Mandatory | Description | 15630| --------| ------- | ---- | ---------------------------| 15631| code | [WebNetErrorList](js-apis-netErrorList.md#webneterrorlist) | Yes | Network error code.| 15632 15633**Error codes** 15634 15635For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15636 15637| ID| Error Message | 15638| -------- | ------------------------------------- | 15639| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 15640| 17100021 | The resource handler is invalid. | 15641 15642**System capability**: SystemCapability.Web.Webview.Core 15643 15644**Example** 15645 15646See [OnRequestStart](#onrequeststart12). 15647 15648## WebSchemeHandler<sup>12+</sup> 15649 15650Represents a **WebSchemeHandler** object used to intercept requests for a specific scheme. 15651 15652### onRequestStart<sup>12+</sup> 15653 15654onRequestStart(callback: (request: WebSchemeHandlerRequest, handler: WebResourceHandler) => boolean): void 15655 15656Called 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. 15657 15658**System capability**: SystemCapability.Web.Webview.Core 15659 15660**Parameters** 15661 15662| Name | Type | Mandatory| Description | 15663| -------- | -------------------- | ---- | ---------- | 15664| 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.| 15665 15666**Error codes** 15667 15668For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15669 15670| ID| Error Message | 15671| -------- | ------------------------------------- | 15672| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 15673 15674**Example** 15675 15676```ts 15677// xxx.ets 15678import { webview } from '@kit.ArkWeb'; 15679import { BusinessError } from '@kit.BasicServicesKit'; 15680import { buffer } from '@kit.ArkTS'; 15681import { WebNetErrorList } from '@ohos.web.netErrorList'; 15682 15683@Entry 15684@Component 15685struct WebComponent { 15686 controller: webview.WebviewController = new webview.WebviewController(); 15687 schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); 15688 htmlData: string = "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>"; 15689 15690 build() { 15691 Column() { 15692 Web({ src: 'https://www.example.com', controller: this.controller }) 15693 .onControllerAttached(() => { 15694 try { 15695 this.schemeHandler.onRequestStart((request: webview.WebSchemeHandlerRequest, resourceHandler: webview.WebResourceHandler) => { 15696 console.log("[schemeHandler] onRequestStart"); 15697 try { 15698 console.log("[schemeHandler] onRequestStart url:" + request.getRequestUrl()); 15699 console.log("[schemeHandler] onRequestStart method:" + request.getRequestMethod()); 15700 console.log("[schemeHandler] onRequestStart referrer:" + request.getReferrer()); 15701 console.log("[schemeHandler] onRequestStart isMainFrame:" + request.isMainFrame()); 15702 console.log("[schemeHandler] onRequestStart hasGesture:" + request.hasGesture()); 15703 console.log("[schemeHandler] onRequestStart header size:" + request.getHeader().length); 15704 console.log("[schemeHandler] onRequestStart resource type:" + request.getRequestResourceType()); 15705 console.log("[schemeHandler] onRequestStart frame url:" + request.getFrameUrl()); 15706 let header = request.getHeader(); 15707 for (let i = 0; i < header.length; i++) { 15708 console.log("[schemeHandler] onRequestStart header:" + header[i].headerKey + " " + header[i].headerValue); 15709 } 15710 let stream = request.getHttpBodyStream(); 15711 if (stream) { 15712 console.log("[schemeHandler] onRequestStart has http body stream"); 15713 } else { 15714 console.log("[schemeHandler] onRequestStart has no http body stream"); 15715 } 15716 } catch (error) { 15717 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 15718 } 15719 15720 if (request.getRequestUrl().endsWith("example.com")) { 15721 return false; 15722 } 15723 15724 let response = new webview.WebSchemeHandlerResponse(); 15725 try { 15726 response.setNetErrorCode(WebNetErrorList.NET_OK); 15727 response.setStatus(200); 15728 response.setStatusText("OK"); 15729 response.setMimeType("text/html"); 15730 response.setEncoding("utf-8"); 15731 response.setHeaderByName("header1", "value1", false); 15732 } catch (error) { 15733 console.error(`[schemeHandler] ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 15734 } 15735 15736 // Before calling didFinish or didFail, call didReceiveResponse to send a response header to this request. 15737 let buf = buffer.from(this.htmlData) 15738 try { 15739 if (buf.length == 0) { 15740 console.log("[schemeHandler] length 0"); 15741 resourceHandler.didReceiveResponse(response); 15742 // If the value of buf.length is 0 in normal cases, call resourceHandler.didFinish(). Otherwise, call resourceHandler.didFail(). 15743 resourceHandler.didFail(WebNetErrorList.ERR_FAILED); 15744 } else { 15745 console.log("[schemeHandler] length 1"); 15746 resourceHandler.didReceiveResponse(response); 15747 resourceHandler.didReceiveResponseBody(buf.buffer); 15748 resourceHandler.didFinish(); 15749 } 15750 } catch (error) { 15751 console.error(`[schemeHandler] ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 15752 } 15753 return true; 15754 }) 15755 15756 this.schemeHandler.onRequestStop((request: webview.WebSchemeHandlerRequest) => { 15757 console.log("[schemeHandler] onRequestStop"); 15758 }); 15759 15760 this.controller.setWebSchemeHandler('https', this.schemeHandler); 15761 } catch (error) { 15762 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 15763 } 15764 }) 15765 .javaScriptAccess(true) 15766 .domStorageAccess(true) 15767 } 15768 } 15769} 15770``` 15771### onRequestStop<sup>12+</sup> 15772 15773onRequestStop(callback: Callback\<WebSchemeHandlerRequest\>): void 15774 15775Called 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: 15776 157771. The **WebResourceHandler** object calls **didFail** or **didFinish**. 15778 157792. The request is interrupted due to other reasons. 15780 15781**System capability**: SystemCapability.Web.Webview.Core 15782 15783**Parameters** 15784 15785| Name | Type | Mandatory| Description | 15786| -------- | -------------------- | ---- | ---------- | 15787| callback | Callback\<[WebSchemeHandlerRequest](#webschemehandlerrequest12)\> | Yes | Callback invoked when the request is complete.| 15788 15789**Error codes** 15790 15791For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15792 15793| ID| Error Message | 15794| -------- | ------------------------------------- | 15795| 401 | Invalid input parameter. | 15796 15797**Example** 15798 15799For the complete sample code, see [onRequestStart](#onrequeststart12). 15800 15801## CacheOptions<sup>12+</sup> 15802 15803Represents 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. 15804 15805**System capability**: SystemCapability.Web.Webview.Core 15806 15807| Name | Type | Readable| Writable|Description | 15808| ----------- | ------ | -----|------|------------------- | 15809| 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. | 15810 15811## PlaybackStatus<sup>12+</sup> 15812 15813Represents the playback status of the player, functioning as a parameter in [handleStatusChanged](#handlestatuschanged12). 15814 15815**System capability**: SystemCapability.Web.Webview.Core 15816 15817| Name| Value| Description| 15818|------|----|------| 15819| PAUSED | 0 | Playing.| 15820| PLAYING | 1 | Paused.| 15821 15822## NetworkState<sup>12+<sup> 15823 15824Describes the network status of the player. 15825 15826**System capability**: SystemCapability.Web.Webview.Core 15827 15828| Name| Value| Description| 15829|------|----|------| 15830| EMPTY | 0 | The player has not started downloading data.| 15831| 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.| 15832| LOADING | 2 | The player is downloading media data.| 15833| NETWORK_ERROR | 3 | A network error occurs.| 15834 15835## ReadyState<sup>12+<sup> 15836 15837Enumerates the cache states of the player. 15838 15839**System capability**: SystemCapability.Web.Webview.Core 15840 15841| Name| Value| Description| 15842|------|----|------| 15843| HAVE_NOTHING | 0 | There is no data cached.| 15844| HAVE_METADATA | 1 | Only media metadata is cached.| 15845| HAVE_CURRENT_DATA | 2 | Data up to the current playback position is cached.| 15846| HAVE_FUTURE_DATA | 3 | Data beyond the current playback position is cached, but there might still be stutters during playback.| 15847| HAVE_ENOUGH_DATA | 4 | Sufficient data has been cached to ensure smooth playback.| 15848 15849## MediaError<sup>12+<sup> 15850 15851Enumerates the error types of the player. 15852 15853**System capability**: SystemCapability.Web.Webview.Core 15854 15855| Name| Value| Description| 15856|------|----|------| 15857| NETWORK_ERROR | 1 | Network error.| 15858| FORMAT_ERROR | 2 | Media format error.| 15859| DECODE_ERROR | 3 | Decoding error.| 15860 15861## NativeMediaPlayerHandler<sup>12+<sup> 15862 15863Represents a **NativeMediaPlayerHandler** object used as the parameter of the [CreateNativeMediaPlayerCallback](#createnativemediaplayercallback12) callback. 15864The application uses this object to report the player status to the ArkWeb engine. 15865 15866### handleStatusChanged<sup>12+<sup> 15867 15868handleStatusChanged(status: PlaybackStatus): void 15869 15870Called to notify the ArkWeb engine of the playback status of the player when the playback status changes. 15871 15872**System capability**: SystemCapability.Web.Webview.Core 15873 15874**Parameters** 15875 15876| Name| Type| Mandatory| Description| 15877|--------|------|------|------| 15878| status | [PlaybackStatus](#playbackstatus12) | Yes| Player status.| 15879 15880**Example** 15881 15882For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15883 15884### handleVolumeChanged<sup>12+<sup> 15885 15886handleVolumeChanged(volume: number): void 15887 15888Called to notify the ArkWeb engine of the volume of the player when the volume changes. 15889 15890**System capability**: SystemCapability.Web.Webview.Core 15891 15892**Parameters** 15893 15894| Name| Type| Mandatory| Description| 15895|--------|------|------|------| 15896| volume | number | Yes| Volume of the player.| 15897 15898**Example** 15899 15900For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15901 15902### handleMutedChanged<sup>12+<sup> 15903 15904handleMutedChanged(muted: boolean): void 15905 15906Called to notify the ArkWeb engine of the muted status of the player when the muted status changes. 15907 15908**System capability**: SystemCapability.Web.Webview.Core 15909 15910**Parameters** 15911 15912| Name| Type| Mandatory| Description| 15913|--------|------|------|------| 15914| muted | boolean | Yes| Whether the player is muted.| 15915 15916**Example** 15917 15918For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15919 15920### handlePlaybackRateChanged<sup>12+<sup> 15921 15922handlePlaybackRateChanged(playbackRate: number): void 15923 15924Called to notify the ArkWeb engine of the playback rate of the player when the playback rate changes. 15925 15926**System capability**: SystemCapability.Web.Webview.Core 15927 15928**Parameters** 15929 15930| Name| Type| Mandatory| Description| 15931|--------|------|------|------| 15932| playbackRate | number | Yes| Playback rate.| 15933 15934**Example** 15935 15936For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15937 15938### handleDurationChanged<sup>12+<sup> 15939 15940handleDurationChanged(duration: number): void 15941 15942Called to notify the ArkWeb engine of the total duration of the media. 15943 15944**System capability**: SystemCapability.Web.Webview.Core 15945 15946**Parameters** 15947 15948| Name| Type| Mandatory| Description| 15949|--------|------|------|------| 15950| duration | number | Yes| Total duration of the media. Unit: second.| 15951 15952**Example** 15953 15954For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15955 15956### handleTimeUpdate<sup>12+<sup> 15957 15958handleTimeUpdate(currentPlayTime: number): void 15959 15960Called to notify the ArkWeb engine of the playback progress when the playback progress changes. 15961 15962**System capability**: SystemCapability.Web.Webview.Core 15963 15964**Parameters** 15965 15966| Name| Type| Mandatory| Description| 15967|--------|------|------|------| 15968| currentPlayTime | number | Yes| Current progress. Unit: second. | 15969 15970**Example** 15971 15972For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15973 15974### handleBufferedEndTimeChanged<sup>12+<sup> 15975 15976handleBufferedEndTimeChanged(bufferedEndTime: number): void 15977 15978Called to notify the ArkWeb engine of the buffer time when the buffer time changes. 15979 15980**System capability**: SystemCapability.Web.Webview.Core 15981 15982**Parameters** 15983 15984| Name| Type| Mandatory| Description| 15985|--------|------|------|------| 15986| bufferedEndTime | number | Yes| Duration of media data in the buffer.| 15987 15988**Example** 15989 15990For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15991 15992### handleEnded<sup>12+<sup> 15993 15994handleEnded(): void 15995 15996Called to notify the ArkWeb engine that the media playback ends. 15997 15998**System capability**: SystemCapability.Web.Webview.Core 15999 16000**Example** 16001 16002For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16003 16004### handleNetworkStateChanged<sup>12+<sup> 16005 16006handleNetworkStateChanged(state: NetworkState): void 16007 16008Called to notify the ArkWeb engine of the network status of the player when the network status changes. 16009 16010**System capability**: SystemCapability.Web.Webview.Core 16011 16012**Parameters** 16013 16014| Name| Type| Mandatory| Description| 16015|--------|------|------|------| 16016| state | [NetworkState](#networkstate12) | Yes| Network status of the player.| 16017 16018**Example** 16019 16020For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16021 16022### handleReadyStateChanged<sup>12+<sup> 16023 16024handleReadyStateChanged(state: ReadyState): void 16025 16026Called to notify the ArkWeb engine of the cache status of the player when the cache status changes. 16027 16028**System capability**: SystemCapability.Web.Webview.Core 16029 16030**Parameters** 16031 16032| Name| Type| Mandatory| Description| 16033|--------|------|------|------| 16034| state | [ReadyState](#readystate12) | Yes| Cache status of the player.| 16035 16036**Example** 16037 16038For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16039 16040### handleFullscreenChanged<sup>12+<sup> 16041 16042handleFullscreenChanged(fullscreen: boolean): void 16043 16044Called to notify the ArkWeb engine of the full screen status of the player when the full screen status changes. 16045 16046**System capability**: SystemCapability.Web.Webview.Core 16047 16048**Parameters** 16049 16050| Name| Type| Mandatory| Description| 16051|--------|------|------|------| 16052| fullscreen | boolean | Yes| Whether the player is in full screen.| 16053 16054**Example** 16055 16056For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16057 16058### handleSeeking<sup>12+<sup> 16059 16060handleSeeking(): void 16061 16062Called to notify the ArkWeb engine that the player enters the seek state. 16063 16064**System capability**: SystemCapability.Web.Webview.Core 16065 16066**Example** 16067 16068For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16069 16070### handleSeekFinished<sup>12+<sup> 16071 16072handleSeekFinished(): void 16073 16074Called to notify the ArkWeb engine that the seek operation is complete. 16075 16076**System capability**: SystemCapability.Web.Webview.Core 16077 16078**Example** 16079 16080For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16081 16082### handleError<sup>12+<sup> 16083 16084handleError(error: MediaError, errorMessage: string): void 16085 16086Called to notify the ArkWeb engine that an error occurs with the player. 16087 16088**System capability**: SystemCapability.Web.Webview.Core 16089 16090**Parameters** 16091 16092| Name| Type| Mandatory| Description| 16093|--------|------|------|------| 16094| error | [MediaError](#mediaerror12) | Yes| Error object type.| 16095| errorMessage | string | Yes| Error message.| 16096 16097**Example** 16098 16099For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16100 16101### handleVideoSizeChanged<sup>12+<sup> 16102 16103handleVideoSizeChanged(width: number, height: number): void 16104 16105Called to notify the ArkWeb engine of the video size of the player. 16106 16107**System capability**: SystemCapability.Web.Webview.Core 16108 16109**Parameters** 16110 16111| Name| Type| Mandatory| Description| 16112|--------|------|------|------| 16113| width | number | Yes| Video width.| 16114| height | number | Yes| Video height.| 16115 16116**Example** 16117 16118For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16119 16120## SuspendType<sup>12+<sup> 16121 16122Enumerates the suspension types of the player. 16123 16124**System capability**: SystemCapability.Web.Webview.Core 16125 16126| Name| Value| Description| 16127|------|----|------| 16128| ENTER_BACK_FORWARD_CACHE | 0 | The page enters the BFCache.| 16129| ENTER_BACKGROUND | 1 | The page is displayed in the background.| 16130| AUTO_CLEANUP | 2 | The page is automatically cleaned up by the system.| 16131 16132## NativeMediaPlayerBridge<sup>12+<sup> 16133 16134Implements a **NativeMediaPlayerBridge** object, which is the return value of the [CreateNativeMediaPlayerCallback](#createnativemediaplayercallback12) callback. 16135It is an interface class that acts as a bridge between the web media player and the ArkWeb kernel. 16136The ArkWeb engine uses an object of this interface class to control the player created by the application to take over web page media. 16137 16138### updateRect<sup>12+<sup> 16139 16140updateRect(x: number, y: number, width: number, height: number): void 16141 16142Updates the surface position information. 16143 16144**System capability**: SystemCapability.Web.Webview.Core 16145 16146**Parameters** 16147 16148| Name| Type| Mandatory| Description| 16149|--------|------|------|------| 16150| x | number | Yes| X coordinate of the surface relative to the web component.| 16151| y | number | Yes| Y coordinate of the surface relative to the web component.| 16152| width | number | Yes| Width of the surface.| 16153| height | number | Yes| Height of the surface.| 16154 16155**Example** 16156 16157For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16158 16159### play<sup>12+<sup> 16160 16161play(): void 16162 16163Plays this video. 16164 16165**System capability**: SystemCapability.Web.Webview.Core 16166 16167**Example** 16168 16169For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16170 16171### pause<sup>12+<sup> 16172 16173pause(): void 16174 16175Pauses playback. 16176 16177**System capability**: SystemCapability.Web.Webview.Core 16178 16179**Example** 16180 16181For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16182 16183### seek<sup>12+<sup> 16184 16185seek(targetTime: number): void 16186 16187Seeks to a specific time point in the media. 16188 16189**System capability**: SystemCapability.Web.Webview.Core 16190 16191**Parameters** 16192 16193| Name| Type| Mandatory| Description| 16194|--------|------|------|------| 16195| targetTime | number | Yes| Target time point. Unit: second.| 16196 16197**Example** 16198 16199For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16200 16201### setVolume<sup>12+<sup> 16202 16203setVolume(volume: number): void 16204 16205Sets the playback volume. 16206The value range is [0, 1.0]. 16207 16208**Parameters** 16209 16210| Name| Type| Mandatory| Description| 16211|--------|------|------|------| 16212| 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.| 16213 16214**System capability**: SystemCapability.Web.Webview.Core 16215 16216**Example** 16217 16218For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16219 16220### setMuted<sup>12+<sup> 16221 16222setMuted(muted: boolean): void 16223 16224Sets the muted status. 16225 16226**System capability**: SystemCapability.Web.Webview.Core 16227 16228**Parameters** 16229 16230| Name| Type| Mandatory| Description| 16231|--------|------|------|------| 16232| muted | boolean | Yes| Whether to mute the player.| 16233 16234**Example** 16235 16236For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16237 16238### setPlaybackRate<sup>12+<sup> 16239 16240setPlaybackRate(playbackRate: number): void 16241 16242Sets the playback rate. 16243The value range is [0, 10.0]. 16244 16245**System capability**: SystemCapability.Web.Webview.Core 16246 16247**Parameters** 16248 16249| Name| Type| Mandatory| Description| 16250|--------|------|------|------| 16251| playbackRate | number | Yes| Playback rate. The value range is [0, 10.0]. The value **1** indicates the original speed of playback.| 16252 16253**Example** 16254 16255For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16256 16257### release<sup>12+<sup> 16258 16259release(): void 16260 16261Releases this player. 16262 16263**System capability**: SystemCapability.Web.Webview.Core 16264 16265**Example** 16266 16267For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16268 16269### enterFullscreen<sup>12+<sup> 16270 16271enterFullscreen(): void 16272 16273Enables the player to enter full screen mode. 16274 16275**System capability**: SystemCapability.Web.Webview.Core 16276 16277**Example** 16278 16279For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16280 16281### exitFullscreen<sup>12+<sup> 16282 16283exitFullscreen(): void 16284 16285Enables the player to exit full screen mode. 16286 16287**System capability**: SystemCapability.Web.Webview.Core 16288 16289**Example** 16290 16291For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16292 16293### resumePlayer<sup>12+<sup> 16294 16295resumePlayer?(): void 16296 16297Resumes the player and its status information. 16298 16299**System capability**: SystemCapability.Web.Webview.Core 16300 16301**Example** 16302 16303For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16304 16305### suspendPlayer<sup>12+<sup> 16306 16307suspendPlayer?(type: SuspendType): void 16308 16309Suspends the player and save its status information. 16310 16311**System capability**: SystemCapability.Web.Webview.Core 16312 16313**Parameters** 16314 16315| Name| Type| Mandatory| Description| 16316|--------|------|------|------| 16317| type | [SuspendType](#suspendtype12) | Yes| Suspension type of the player.| 16318 16319**Example** 16320 16321For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16322 16323## MediaType<sup>12+<sup> 16324 16325Enumerates the media types. 16326 16327**System capability**: SystemCapability.Web.Webview.Core 16328 16329| Name| Value| Description| 16330|------|----|------| 16331| VIDEO | 0 | Video.| 16332| AUDIO | 1 | Audio.| 16333 16334## SourceType<sup>12+<sup> 16335 16336Enumerates the media source types. 16337 16338**System capability**: SystemCapability.Web.Webview.Core 16339 16340| Name| Value| Description| 16341|------|----|------| 16342| URL | 0 | URL.| 16343| MSE | 1 | Blob.| 16344 16345## MediaSourceInfo<sup>12+<sup> 16346 16347Provides the information about the media source. 16348 16349**System capability**: SystemCapability.Web.Webview.Core 16350 16351| Name| Type| Mandatory| Description| 16352|------|------|------|------| 16353| type | [SourceType](#sourcetype12) | Yes| Type of the media source.| 16354| source | string | Yes| Address of the media source.| 16355| format | string | Yes| Format of the media source, which may be empty. You need to determine the format by yourself.| 16356 16357## NativeMediaPlayerSurfaceInfo<sup>12+<sup> 16358 16359Provides 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). 16360 16361**System capability**: SystemCapability.Web.Webview.Core 16362 16363| Name| Type| Mandatory| Description| 16364|------|------|------|------| 16365| 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).| 16366| rect | [RectEvent](#rectevent12) | Yes| Position of the surface.| 16367 16368## Preload<sup>12+<sup> 16369 16370Defines how the player preloads media data. 16371 16372**System capability**: SystemCapability.Web.Webview.Core 16373 16374| Name| Value| Description| 16375|------|----|------| 16376| NONE | 0 | No media data is preloaded.| 16377| METADATA | 1 | Only the metadata of the media is preloaded.| 16378| AUTO | 2 | A sufficient amount of media data is preloaded to ensure smooth playback| 16379 16380## MediaInfo<sup>12+<sup> 16381 16382Represents a **MediaInfo** object used as a parameter of the [CreateNativeMediaPlayerCallback](#createnativemediaplayercallback12) callback. 16383The 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 . 16384 16385**System capability**: SystemCapability.Web.Webview.Core 16386 16387| Name| Type| Mandatory| Description| 16388|------|------|------|------| 16389| embedID | string | Yes| ID of **\<video>** or **\<audio>** on the web page.| 16390| mediaType | [MediaType](#mediatype12) | Yes| Type of the media.| 16391| mediaSrcList | [MediaSourceInfo](#mediasourceinfo12)[] | Yes| Source of the media. There may be multiple sources. The application needs to select a supported source to play.| 16392| surfaceInfo | [NativeMediaPlayerSurfaceInfo](#nativemediaplayersurfaceinfo12) | Yes| Surface information used for same-layer rendering.| 16393| controlsShown | boolean | Yes| Whether the **controls** attribute exists in **\<video>** or **\<audio>**.| 16394| controlList | string[] | Yes| Value of the **controlslist** attribute in **\<video>** or **\<audio>**.| 16395| muted | boolean | Yes| Whether to mute the player.| 16396| posterUrl | string | Yes| URL of a poster.| 16397| preload | [Preload](#preload12) | Yes| Whether preloading is required.| 16398| headers | Record\<string, string\> | Yes| HTTP headers that need to be included in the player's request for media resources.| 16399| attributes | Record\<string, string\> | Yes| Attributes in **\<video>** or **\<audio>**.| 16400 16401 16402## CreateNativeMediaPlayerCallback<sup>12+<sup> 16403 16404type CreateNativeMediaPlayerCallback = (handler: NativeMediaPlayerHandler, mediaInfo: MediaInfo) => NativeMediaPlayerBridge 16405 16406Represents a **CreateNativeMediaPlayerCallback** object used as a parameter of the [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12) callback. 16407This object is used to create a player to take over media playback of the web page. 16408 16409**System capability**: SystemCapability.Web.Webview.Core 16410 16411**Parameters** 16412 16413| Name| Type| Mandatory| Description| 16414|--------|------|------|------| 16415| handler | [NativeMediaPlayerHandler](#nativemediaplayerhandler12) | Yes| Object used to report the player status to the ArkWeb engine.| 16416| mediaInfo | [MediaInfo](#mediainfo12) | Yes| Information about the media on the web page.| 16417 16418**Return value** 16419 16420| Type| Description| 16421|------|------| 16422| [NativeMediaPlayerBridge](#nativemediaplayerbridge12) | Instance of the interface class between the player that takes over web media and the ArkWeb kernel.<br>The application needs to implement the interface class.<br> Object used by the ArkWeb engine to control the player created by the application to take over web page media.<br>If the application returns **null**, the application does not take over the media playback, and the media will be played by the ArkWeb engine.| 16423 16424**Example** 16425 16426For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 16427 16428## OfflineResourceMap<sup>12+</sup> 16429 16430Implements 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. 16431 16432**System capability**: SystemCapability.Web.Webview.Core 16433 16434| Name | Type | Readable| Writable|Description | 16435| ----------- | ------ | -----|------|------------------- | 16436| 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. | 16437| resource | Uint8Array | Yes | Yes | Content of a local offline resource. | 16438| 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**. | 16439| type | [OfflineResourceType](#offlineresourcetype12) | Yes | Yes | Resource type. Currently, only the JavaScript, image, and CSS types are supported. | 16440 16441## OfflineResourceType<sup>12+</sup> 16442 16443Represents the local offline resource type corresponding to an [OfflineResourceMap](#offlineresourcemap12) object. 16444 16445**System capability**: SystemCapability.Web.Webview.Core 16446 16447| Name | Value| Description | 16448| ------------ | -- |--------------------------------- | 16449| IMAGE | 0 | Resource of the image type.| 16450| CSS | 1 | Resource of the CSS type.| 16451| CLASSIC_JS | 2 | Javascript resource loaded through the <script src="" /\> tag.| 16452| MODULE_JS | 3 |Javascript resource loaded through the <script src="" type="module" /\> tag.| 16453 16454## WebResourceType<sup>12+</sup> 16455 16456Enumerates the types of requested resources. 16457 16458**System capability**: SystemCapability.Web.Webview.Core 16459 16460| Name | Value| Description | 16461| ------------ | -- |--------------------------------- | 16462| MAIN_FRAME | 0 | Top-level page.| 16463| SUB_FRAME | 1 | Frame or Iframe.| 16464| STYLE_SHEET | 2 | CSS style sheet.| 16465| SCRIPT | 3 | External script.| 16466| IMAGE | 4 | Image (JPG, GIF, PNG, or other format).| 16467| FONT_RESOURCE | 5 | Font.| 16468| SUB_RESOURCE | 6 | Other sub-resource. If the type is unknown, it is used as the default type.| 16469| OBJECT | 7 | Object (or embed) tag of the plug-in, or the resource requested by the plug-in.| 16470| MEDIA | 8 | Media resource.| 16471| WORKER | 9 | Main resource of a dedicated worker thread.| 16472| SHARED_WORKER | 10 | Main resource of a shared worker thread.| 16473| PREFETCH | 11 | Explicit prefetch request.| 16474| FAVICON | 12 | Website icon.| 16475| XHR | 13 | XMLHttpRequest.| 16476| PING | 14 | <a ping\>/sendBeacon ping request.| 16477| SERVICE_WORKER | 15 | Main resource of a service worker.| 16478| CSP_REPORT | 16 | Report of Content Security Policy violation.| 16479| PLUGIN_RESOURCE | 17 | Resource requested by the plug-in.| 16480| NAVIGATION_PRELOAD_MAIN_FRAME | 19 | Main frame redirection request that triggers service worker preloading.| 16481| NAVIGATION_PRELOAD_SUB_FRAME | 20 | Subframe redirection request that triggers service worker preloading.| 16482 16483## RectEvent<sup>12+<sup> 16484 16485Defines a rectangle. 16486 16487**System capability**: SystemCapability.Web.Webview.Core 16488 16489| Name | Type | Readable| Writable| Description | 16490| -------------- | --------- | ---- | ---- | ---------------------------- | 16491| x | number | Yes | Yes | X-axis coordinate of the upper left corner of the rectangle. | 16492| y | number | Yes | Yes | Y-axis coordinate of the upper left corner of the rectangle. | 16493| width | number | Yes | Yes | Width of the rectangle. | 16494| height | number | Yes | Yes | Height of the rectangle. | 16495 16496## BackForwardCacheSupportedFeatures<sup>12+<sup> 16497 16498Adds a page that uses any of the following features to the back-forward cache. For the complete sample code, see [enableBackForwardCache](#enablebackforwardcache12). 16499 16500**System capability**: SystemCapability.Web.Webview.Core 16501 16502| Name| Type| Mandatory| Description| 16503|------|------|------|------| 16504| 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.| 16505| 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.| 16506 16507### constructor<sup>12+</sup> 16508 16509constructor() 16510 16511Constructs a **BackForwardCacheSupportedFeatures** instance. 16512 16513**System capability**: SystemCapability.Web.Webview.Core 16514 16515## BackForwardCacheOptions<sup>12+<sup> 16516 16517Implements a **BackForwardCacheOptions** object to set back-forward cache options of the **Web** component. For the complete sample code, see [BackForwardCacheOptions](#backforwardcacheoptions12). 16518 16519**System capability**: SystemCapability.Web.Webview.Core 16520 16521| Name| Type| Mandatory| Description| 16522|------|------|------|------| 16523| 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.| 16524| 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.| 16525 16526### constructor<sup>12+</sup> 16527 16528constructor() 16529 16530Constructs a **BackForwardCacheOptions** instance. 16531 16532**System capability**: SystemCapability.Web.Webview.Core 16533 16534## AdsBlockManager<sup>12+</sup> 16535 16536Implements 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. 16537 16538### setAdsBlockRules<sup>12+</sup> 16539 16540static setAdsBlockRules(rulesFile: string, replace: boolean): void 16541 16542Sets a custom ad blocking rule file that conforms to the universal EasyList syntax in the **Web** components. 16543 16544> **NOTE** 16545> 16546> 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. 16547 16548**System capability**: SystemCapability.Web.Webview.Core 16549 16550**Parameters** 16551 16552| Name | Type | Mandatory| Description | 16553| ---------- | ------ | ---- | -------------------------------- | 16554| 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.| 16555| 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.| 16556 16557**Error codes** 16558 16559For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 16560 16561| ID| Error Message | 16562| -------- | ----------------------- | 16563| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 16564 16565**Example** 16566 16567```ts 16568// xxx.ets 16569import { webview } from '@kit.ArkWeb'; 16570import { picker, fileUri } from '@kit.CoreFileKit'; 16571 16572// 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. 16573@Entry 16574@Component 16575struct WebComponent { 16576 controller: webview.WebviewController = new webview.WebviewController(); 16577 16578 build() { 16579 Row() { 16580 Flex() { 16581 Button({ type: ButtonType.Capsule }) { 16582 Text("setAdsBlockRules") 16583 } 16584 .onClick(() => { 16585 try { 16586 let documentSelectionOptions: ESObject = new picker.DocumentSelectOptions(); 16587 let documentPicker: ESObject = new picker.DocumentViewPicker(); 16588 documentPicker.select(documentSelectionOptions).then((documentSelectResult: ESObject) => { 16589 if (documentSelectResult && documentSelectResult.length > 0) { 16590 let fileRealPath = new fileUri.FileUri(documentSelectResult[0]); 16591 console.info('DocumentViewPicker.select successfully, uri: ' + fileRealPath); 16592 webview.AdsBlockManager.setAdsBlockRules(fileRealPath.path, true); 16593 } 16594 }) 16595 } catch (err) { 16596 console.error('DocumentViewPicker.select failed with err:' + err); 16597 } 16598 }) 16599 } 16600 } 16601 } 16602} 16603``` 16604 16605### addAdsBlockDisallowedList<sup>12+</sup> 16606 16607static addAdsBlockDisallowedList(domainSuffixes: Array\<string\>): void 16608 16609Adds 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. 16610 16611> **NOTE** 16612> 16613> The domain name set by this API is not persistent; they need to be set again after the application is restarted. 16614> 16615> 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**. 16616 16617**System capability**: SystemCapability.Web.Webview.Core 16618 16619**Parameters** 16620 16621| Name | Type | Mandatory| Description | 16622| ---------- | ------ | ---- | -------------------------------- | 16623| domainSuffixes | Array\<string\> | Yes | Array of domain names, for example, ['example.com', 'abcd.efg.com'].| 16624 16625**Error codes** 16626 16627For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 16628 16629| ID| Error Message | 16630| -------- | ----------------------- | 16631| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 16632 16633**Example** 16634 16635```ts 16636// xxx.ets 16637import { webview } from '@kit.ArkWeb'; 16638 16639// This example demonstrates how to click a button to add an array of domain names to the disallowed list. 16640@Entry 16641@Component 16642struct WebComponent { 16643 main_url: string = 'https://www.example.com'; 16644 text_input_controller: TextInputController = new TextInputController(); 16645 controller: webview.WebviewController = new webview.WebviewController(); 16646 @State input_text: string = 'https://www.example.com'; 16647 16648 build() { 16649 Column() { 16650 Row() { 16651 Flex() { 16652 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 16653 .id("input_url") 16654 .height(40) 16655 .margin(5) 16656 .borderColor(Color.Blue) 16657 .onChange((value: string) => { 16658 this.input_text = value; 16659 }) 16660 16661 Button({type: ButtonType.Capsule}) { Text("Go") } 16662 .onClick(() => { 16663 this.controller.loadUrl(this.input_text); 16664 }) 16665 16666 Button({type: ButtonType.Capsule}) { Text("addAdsBlockDisallowedList") } 16667 .onClick(() => { 16668 let arrDomainSuffixes = new Array<string>(); 16669 arrDomainSuffixes.push('example.com'); 16670 arrDomainSuffixes.push('abcdefg.cn'); 16671 webview.AdsBlockManager.addAdsBlockDisallowedList(arrDomainSuffixes); 16672 }) 16673 } 16674 } 16675 Web({ src: this.main_url, controller: this.controller }) 16676 .onControllerAttached(()=>{ 16677 this.controller.enableAdsBlock(true); 16678 }) 16679 } 16680 } 16681} 16682``` 16683 16684### removeAdsBlockDisallowedList<sup>12+</sup> 16685 16686static removeAdsBlockDisallowedList(domainSuffixes: Array\<string\>): void 16687 16688Removes an array of domain names from the disallowed list of this **AdsBlockManager** object. 16689 16690> **NOTE** 16691> 16692> 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. 16693 16694**System capability**: SystemCapability.Web.Webview.Core 16695 16696**Parameters** 16697 16698| Name | Type | Mandatory| Description | 16699| ---------- | ------ | ---- | -------------------------------- | 16700| domainSuffixes | Array\<string\> | Yes | Array of domain names, for example, ['example.com', 'abcd.efg.com'].| 16701 16702**Error codes** 16703 16704For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 16705 16706| ID| Error Message | 16707| -------- | ----------------------- | 16708| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 16709 16710**Example** 16711 16712```ts 16713// xxx.ets 16714import { webview } from '@kit.ArkWeb'; 16715 16716// This example demonstrates how to click a button to remove an array of domain names from the disallowed list. 16717@Entry 16718@Component 16719struct WebComponent { 16720 main_url: string = 'https://www.example.com'; 16721 text_input_controller: TextInputController = new TextInputController(); 16722 controller: webview.WebviewController = new webview.WebviewController(); 16723 @State input_text: string = 'https://www.example.com'; 16724 16725 build() { 16726 Column() { 16727 Row() { 16728 Flex() { 16729 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 16730 .id("input_url") 16731 .height(40) 16732 .margin(5) 16733 .borderColor(Color.Blue) 16734 .onChange((value: string) => { 16735 this.input_text = value; 16736 }) 16737 16738 Button({type: ButtonType.Capsule}) { Text("Go") } 16739 .onClick(() => { 16740 this.controller.loadUrl(this.input_text); 16741 }) 16742 16743 Button({type: ButtonType.Capsule}) { Text("removeAdsBlockDisallowedList") } 16744 .onClick(() => { 16745 let arrDomainSuffixes = new Array<string>(); 16746 arrDomainSuffixes.push('example.com'); 16747 arrDomainSuffixes.push('abcdefg.cn'); 16748 webview.AdsBlockManager.removeAdsBlockDisallowedList(arrDomainSuffixes); 16749 }) 16750 } 16751 } 16752 Web({ src: this.main_url, controller: this.controller }) 16753 .onControllerAttached(()=>{ 16754 this.controller.enableAdsBlock(true); 16755 }) 16756 } 16757 } 16758} 16759``` 16760 16761### clearAdsBlockDisallowedList<sup>12+</sup> 16762 16763static clearAdsBlockDisallowedList(): void 16764 16765Clears the disallowed list of this **AdsBlockManager** object. 16766 16767**System capability**: SystemCapability.Web.Webview.Core 16768 16769**Example** 16770 16771```ts 16772// xxx.ets 16773import { webview } from '@kit.ArkWeb'; 16774 16775@Entry 16776@Component 16777struct WebComponent { 16778 main_url: string = 'https://www.example.com'; 16779 text_input_controller: TextInputController = new TextInputController(); 16780 controller: webview.WebviewController = new webview.WebviewController(); 16781 @State input_text: string = 'https://www.example.com'; 16782 16783 build() { 16784 Column() { 16785 Row() { 16786 Flex() { 16787 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 16788 .id("input_url") 16789 .height(40) 16790 .margin(5) 16791 .borderColor(Color.Blue) 16792 .onChange((value: string) => { 16793 this.input_text = value; 16794 }) 16795 16796 Button({type: ButtonType.Capsule}) { Text("Go") } 16797 .onClick(() => { 16798 this.controller.loadUrl(this.input_text); 16799 }) 16800 16801 Button({type: ButtonType.Capsule}) { Text("clearAdsBlockDisallowedList") } 16802 .onClick(() => { 16803 webview.AdsBlockManager.clearAdsBlockDisallowedList(); 16804 }) 16805 } 16806 } 16807 Web({ src: this.main_url, controller: this.controller }) 16808 .onControllerAttached(()=>{ 16809 this.controller.enableAdsBlock(true); 16810 }) 16811 } 16812 } 16813} 16814``` 16815 16816### addAdsBlockAllowedList<sup>12+</sup> 16817 16818static addAdsBlockAllowedList(domainSuffixes: Array\<string\>): void 16819 16820Adds 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. 16821 16822> **NOTE** 16823> 16824> The domain name set by this API is not persistent; they need to be set again after the application is restarted. 16825> 16826> 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. 16827 16828**System capability**: SystemCapability.Web.Webview.Core 16829 16830**Parameters** 16831 16832| Name | Type | Mandatory| Description | 16833| ---------- | ------ | ---- | -------------------------------- | 16834| domainSuffixes | Array\<string\> | Yes | Array of domain names, for example, ['example.com', 'abcd.efg.com'].| 16835 16836**Error codes** 16837 16838For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 16839 16840| ID| Error Message | 16841| -------- | ----------------------- | 16842| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 16843 16844**Example** 16845 16846```ts 16847// xxx.ets 16848import { webview } from '@kit.ArkWeb'; 16849 16850// This example demonstrates how to click a button to add an array of domain names to the disallowed list. 16851@Entry 16852@Component 16853struct WebComponent { 16854 main_url: string = 'https://www.example.com'; 16855 text_input_controller: TextInputController = new TextInputController(); 16856 controller: webview.WebviewController = new webview.WebviewController(); 16857 @State input_text: string = 'https://www.example.com'; 16858 16859 build() { 16860 Column() { 16861 Row() { 16862 Flex() { 16863 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 16864 .id("input_url") 16865 .height(40) 16866 .margin(5) 16867 .borderColor(Color.Blue) 16868 .onChange((value: string) => { 16869 this.input_text = value; 16870 }) 16871 16872 Button({type: ButtonType.Capsule}) { Text("Go") } 16873 .onClick(() => { 16874 this.controller.loadUrl(this.input_text); 16875 }) 16876 16877 Button({type: ButtonType.Capsule}) { Text("addAdsBlockAllowedList") } 16878 .onClick(() => { 16879 let arrDisallowDomainSuffixes = new Array<string>(); 16880 arrDisallowDomainSuffixes.push('example.com'); 16881 webview.AdsBlockManager.addAdsBlockDisallowedList(arrDisallowDomainSuffixes); 16882 16883 let arrAllowedDomainSuffixes = new Array<string>(); 16884 arrAllowedDomainSuffixes.push('news.example.com'); 16885 webview.AdsBlockManager.addAdsBlockAllowedList(arrAllowedDomainSuffixes); 16886 }) 16887 } 16888 } 16889 Web({ src: this.main_url, controller: this.controller }) 16890 .onControllerAttached(()=>{ 16891 this.controller.enableAdsBlock(true) 16892 }) 16893 } 16894 } 16895} 16896``` 16897 16898### removeAdsBlockAllowedList<sup>12+</sup> 16899 16900static removeAdsBlockAllowedList(domainSuffixes: Array\<string\>): void 16901 16902Removes an array of domain names from the allowed list of this **AdsBlockManager** object. 16903 16904> **NOTE** 16905> 16906> 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. 16907 16908**System capability**: SystemCapability.Web.Webview.Core 16909 16910**Parameters** 16911 16912| Name | Type | Mandatory| Description | 16913| ---------- | ------ | ---- | -------------------------------- | 16914| domainSuffixes | Array\<string\> | Yes | Array of domain names, for example, ['example.com', 'abcd.efg.com'].| 16915 16916**Error codes** 16917 16918For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 16919 16920| ID| Error Message | 16921| -------- | ----------------------- | 16922| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 16923 16924**Example** 16925 16926```ts 16927// xxx.ets 16928import { webview } from '@kit.ArkWeb'; 16929 16930// This example demonstrates how to click a button to remove an array of domain names from the disallowed list. 16931@Entry 16932@Component 16933struct WebComponent { 16934 main_url: string = 'https://www.example.com'; 16935 text_input_controller: TextInputController = new TextInputController(); 16936 controller: webview.WebviewController = new webview.WebviewController(); 16937 @State input_text: string = 'https://www.example.com'; 16938 16939 build() { 16940 Column() { 16941 Row() { 16942 Flex() { 16943 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 16944 .id("input_url") 16945 .height(40) 16946 .margin(5) 16947 .borderColor(Color.Blue) 16948 .onChange((value: string) => { 16949 this.input_text = value; 16950 }) 16951 16952 Button({type: ButtonType.Capsule}) { Text("Go") } 16953 .onClick(() => { 16954 this.controller.loadUrl(this.input_text); 16955 }) 16956 16957 Button({type: ButtonType.Capsule}) { Text("removeAdsBlockAllowedList") } 16958 .onClick(() => { 16959 let arrDomainSuffixes = new Array<string>(); 16960 arrDomainSuffixes.push('example.com'); 16961 arrDomainSuffixes.push('abcdefg.cn'); 16962 webview.AdsBlockManager.removeAdsBlockAllowedList(arrDomainSuffixes); 16963 }) 16964 } 16965 } 16966 Web({ src: this.main_url, controller: this.controller }) 16967 .onControllerAttached(()=>{ 16968 this.controller.enableAdsBlock(true); 16969 }) 16970 } 16971 } 16972} 16973``` 16974 16975### clearAdsBlockAllowedList<sup>12+</sup> 16976 16977static clearAdsBlockAllowedList(): void 16978 16979Clears the allowed list of this **AdsBlockManager** object. 16980 16981**System capability**: SystemCapability.Web.Webview.Core 16982 16983**Example** 16984 16985```ts 16986// xxx.ets 16987import { webview } from '@kit.ArkWeb'; 16988 16989@Entry 16990@Component 16991struct WebComponent { 16992 main_url: string = 'https://www.example.com'; 16993 text_input_controller: TextInputController = new TextInputController(); 16994 controller: webview.WebviewController = new webview.WebviewController(); 16995 @State input_text: string = 'https://www.example.com'; 16996 16997 16998 build() { 16999 Column() { 17000 Row() { 17001 Flex() { 17002 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 17003 .id("input_url") 17004 .height(40) 17005 .margin(5) 17006 .borderColor(Color.Blue) 17007 .onChange((value: string) => { 17008 this.input_text = value; 17009 }) 17010 17011 Button({type: ButtonType.Capsule}) { Text("Go") } 17012 .onClick(() => { 17013 this.controller.loadUrl(this.input_text); 17014 }) 17015 17016 Button({type: ButtonType.Capsule}) { Text("clearAdsBlockAllowedList") } 17017 .onClick(() => { 17018 webview.AdsBlockManager.clearAdsBlockAllowedList(); 17019 }) 17020 } 17021 } 17022 Web({ src: this.main_url, controller: this.controller }) 17023 .onControllerAttached(()=>{ 17024 this.controller.enableAdsBlock(true); 17025 }) 17026 } 17027 } 17028} 17029``` 17030 17031## SnapshotInfo<sup>12+</sup> 17032 17033Provides information used to obtain a full drawing result. 17034 17035**System capability**: SystemCapability.Web.Webview.Core 17036 17037| Name| Type| Mandatory| Description| 17038|------|------|------|------| 17039| id | string | No| Snapshot ID.| 17040| 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.| 17041 17042## SnapshotResult<sup>12+</sup> 17043 17044Represents a full drawing result. 17045 17046**System capability**: SystemCapability.Web.Webview.Core 17047 17048| Name| Type| Mandatory| Description| 17049|------|------|--|---------| 17050| id | string | No| Snapshot ID.| 17051| 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.| 17052| 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.| 17053| imagePixelMap | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | No| Full drawing result in image.pixelMap format.| 17054 17055> **NOTE** 17056> 17057> Only static images and texts in the rendering process can be captured. 17058> 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. 17059 17060## ScrollType<sup>12+</sup> 17061 17062Represents a scroll type, which is used in [setScrollable](#setscrollable12). 17063 17064**System capability**: SystemCapability.Web.Webview.Core 17065 17066| Name | Value| Description | 17067| ------------ | -- |--------------------------------- | 17068| EVENT | 0 | Scrolling event, indicating that a web page is scrolled by using a touchscreen, a touchpad, or a mouse.| 17069 17070## PressureLevel<sup>14+</sup> 17071 17072Represents 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. 17073 17074**System capability**: SystemCapability.Web.Webview.Core 17075 17076| Name| Value| Description| 17077| ------------------------------- | - | ---------- | 17078| 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.| 17079| MEMORY_PRESSURE_LEVEL_CRITICAL | 2 | Critical memory pressure level. At this level, the **Web** kernel attempts to release all possible memory caches.| 17080 17081## PdfConfiguration<sup>14+</sup> 17082 17083Specifies the input parameters of **createPdf()**. 17084 17085> **NOTE** 17086> 17087> The number of pixels is calculated as follows: Number of pixels = 96 x Number of inches. 17088 17089**System capability**: SystemCapability.Web.Webview.Core 17090 17091| Name | Type | Mandatory| Description | 17092| --------------------- | ------- | ---- | ------------------------------------------------------------ | 17093| width | number | Yes | Page width, in inches.<br>Recommended value: 8.27 inches of A4 paper width. | 17094| height | number | Yes | Page height, in inches.<br>Recommended value: 11.69 inches of A4 paper height. | 17095| 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**| 17096| 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.| 17097| 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.| 17098| 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.| 17099| 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.| 17100| shouldPrintBackground | boolean | No | Whether to print the background color. The default value is **false**. | 17101 17102## PdfData<sup>14+</sup> 17103 17104Represents the output data stream class of **createPdf()**. 17105 17106> **NOTE** 17107> 17108> When a PDF file is generated on a web page, a data stream is returned, which is encapsulated by the **PdfData** class. 17109 17110### pdfArrayBuffer<sup>14+</sup> 17111 17112pdfArrayBuffer(): Uint8Array 17113 17114Obtains the data stream generated by a web page. For details, see [createPdf](#createpdf14). 17115 17116**System capability**: SystemCapability.Web.Webview.Core 17117 17118**Return value** 17119 17120| Type | Description | 17121| ---------- | -------- | 17122| Uint8Array | Data stream.| 17123 17124## ScrollOffset<sup>13+</sup> 17125 17126Represents the current scrolling offset of a web page. 17127 17128**System capability**: SystemCapability.Web.Webview.Core 17129 17130| Name| Type | Readable| Writable| Description | 17131| ---- | ------ | ---- | ---- | ------------------------------------------------------------ | 17132| 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.| 17133| 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.| 17134