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 this.controller.registerJavaScriptProxy(this.testObjtest, "objName", ["test", "toString", "testNumber"], ["asyncTestBool"]); 1703 this.controller.registerJavaScriptProxy(this.webTestObj, "objTestName", ["webTest", "webString"]); 1704 this.controller.registerJavaScriptProxy(this.asyncTestObj, "objAsyncName", [], ["asyncTest", "asyncString"]); 1705 } catch (error) { 1706 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1707 } 1708 }) 1709 Button('deleteJavaScriptRegister') 1710 .onClick(() => { 1711 try { 1712 this.controller.deleteJavaScriptRegister("objName"); 1713 this.controller.deleteJavaScriptRegister("objTestName"); 1714 this.controller.deleteJavaScriptRegister("objAsyncName"); 1715 } catch (error) { 1716 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1717 } 1718 }) 1719 Web({ src: $rawfile('index.html'), controller: this.controller }) 1720 .javaScriptAccess(true) 1721 } 1722 } 1723} 1724``` 1725 1726HTML file to be loaded: 1727```html 1728<!-- index.html --> 1729<!DOCTYPE html> 1730<html> 1731 <meta charset="utf-8"> 1732 <body> 1733 <button type="button" onclick="htmlTest()">Click Me!</button> 1734 <p id="demo"></p> 1735 <p id="webDemo"></p> 1736 <p id="asyncDemo"></p> 1737 </body> 1738 <script type="text/javascript"> 1739 function htmlTest() { 1740 // This function call expects to return "ArkUI Web Component" 1741 let str=objName.test("webtest data"); 1742 objName.testNumber(1); 1743 objName.asyncTestBool(true); 1744 document.getElementById("demo").innerHTML=str; 1745 console.log('objName.test result:'+ str) 1746 1747 // This function call expects to return "Web test" 1748 let webStr = objTestName.webTest(); 1749 document.getElementById("webDemo").innerHTML=webStr; 1750 console.log('objTestName.webTest result:'+ webStr) 1751 1752 objAsyncName.asyncTest(); 1753 objAsyncName.asyncString("async test data"); 1754 } 1755</script> 1756</html> 1757``` 1758For more examples, see [Invoking Application Functions on the Frontend Page](../../web/web-in-page-app-function-invoking.md). 1759 1760### runJavaScript 1761 1762runJavaScript(script: string, callback : AsyncCallback\<string>): void 1763 1764Executes 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**. 1765 1766> **NOTE** 1767> 1768> The offscreen component does not trigger **runJavaScript()**. 1769 1770**System capability**: SystemCapability.Web.Webview.Core 1771 1772**Parameters** 1773 1774| Name | Type | Mandatory| Description | 1775| -------- | -------------------- | ---- | ---------------------------- | 1776| script | string | Yes | JavaScript script. | 1777| 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.| 1778 1779**Error codes** 1780 1781For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1782 1783| ID| Error Message | 1784| -------- | ------------------------------------------------------------ | 1785| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1786| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1787 1788**Example** 1789 1790```ts 1791import { webview } from '@kit.ArkWeb'; 1792import { BusinessError } from '@kit.BasicServicesKit'; 1793 1794@Entry 1795@Component 1796struct WebComponent { 1797 controller: webview.WebviewController = new webview.WebviewController(); 1798 @State webResult: string = ''; 1799 1800 build() { 1801 Column() { 1802 Text(this.webResult).fontSize(20) 1803 Web({ src: $rawfile('index.html'), controller: this.controller }) 1804 .javaScriptAccess(true) 1805 .onPageEnd(e => { 1806 try { 1807 this.controller.runJavaScript( 1808 'test()', 1809 (error, result) => { 1810 if (error) { 1811 console.error(`run JavaScript error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1812 return; 1813 } 1814 if (result) { 1815 this.webResult = result; 1816 console.info(`The test() return value is: ${result}`); 1817 } 1818 }); 1819 if (e) { 1820 console.info('url: ', e.url); 1821 } 1822 } catch (error) { 1823 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1824 } 1825 }) 1826 } 1827 } 1828} 1829``` 1830 1831HTML file to be loaded: 1832```html 1833<!-- index.html --> 1834<!DOCTYPE html> 1835<html> 1836 <meta charset="utf-8"> 1837 <body> 1838 Hello world! 1839 </body> 1840 <script type="text/javascript"> 1841 function test() { 1842 console.log('Ark WebComponent') 1843 return "This value is from index.html" 1844 } 1845 </script> 1846</html> 1847``` 1848 1849### runJavaScript 1850 1851runJavaScript(script: string): Promise\<string> 1852 1853Executes 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**. 1854 1855**System capability**: SystemCapability.Web.Webview.Core 1856 1857**Parameters** 1858 1859| Name| Type| Mandatory| Description | 1860| ------ | -------- | ---- | ---------------- | 1861| script | string | Yes | JavaScript script.| 1862 1863**Return value** 1864 1865| Type | Description | 1866| --------------- | --------------------------------------------------- | 1867| Promise\<string> | Promise used to return the result if the operation is successful and null otherwise.| 1868 1869**Error codes** 1870 1871For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1872 1873| ID| Error Message | 1874| -------- | ------------------------------------------------------------ | 1875| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1876| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1877 1878**Example** 1879 1880```ts 1881// xxx.ets 1882import { webview } from '@kit.ArkWeb'; 1883import { BusinessError } from '@kit.BasicServicesKit'; 1884 1885@Entry 1886@Component 1887struct WebComponent { 1888 controller: webview.WebviewController = new webview.WebviewController(); 1889 1890 build() { 1891 Column() { 1892 Web({ src: $rawfile('index.html'), controller: this.controller }) 1893 .javaScriptAccess(true) 1894 .onPageEnd(e => { 1895 try { 1896 this.controller.runJavaScript('test()') 1897 .then((result) => { 1898 console.log('result: ' + result); 1899 }) 1900 .catch((error: BusinessError) => { 1901 console.error("error: " + error); 1902 }) 1903 if (e) { 1904 console.info('url: ', e.url); 1905 } 1906 } catch (error) { 1907 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 1908 } 1909 }) 1910 } 1911 } 1912} 1913``` 1914 1915HTML file to be loaded: 1916```html 1917<!-- index.html --> 1918<!DOCTYPE html> 1919<html> 1920 <meta charset="utf-8"> 1921 <body> 1922 Hello world! 1923 </body> 1924 <script type="text/javascript"> 1925 function test() { 1926 console.log('Ark WebComponent') 1927 return "This value is from index.html" 1928 } 1929 </script> 1930</html> 1931``` 1932 1933### runJavaScriptExt<sup>10+</sup> 1934 1935runJavaScriptExt(script: string | ArrayBuffer, callback : AsyncCallback\<JsMessageExt>): void 1936 1937Executes 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**. 1938 1939**System capability**: SystemCapability.Web.Webview.Core 1940 1941**Parameters** 1942 1943| Name | Type | Mandatory| Description | 1944| -------- | -------------------- | ---- | ---------------------------- | 1945| script | string \| ArrayBuffer<sup>12+</sup> | Yes | JavaScript script.| 1946| callback | AsyncCallback\<[JsMessageExt](#jsmessageext10)\> | Yes | Callback used to return the result.| 1947 1948**Error codes** 1949 1950For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 1951 1952| ID| Error Message | 1953| -------- | ------------------------------------------------------------ | 1954| 17100001 | Init error. The WebviewController must be associated with a Web component. | 1955| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1956 1957**Example** 1958 1959```ts 1960import { webview } from '@kit.ArkWeb'; 1961import { BusinessError } from '@kit.BasicServicesKit'; 1962 1963@Entry 1964@Component 1965struct WebComponent { 1966 controller: webview.WebviewController = new webview.WebviewController(); 1967 @State msg1: string = ''; 1968 @State msg2: string = ''; 1969 1970 build() { 1971 Column() { 1972 Text(this.msg1).fontSize(20) 1973 Text(this.msg2).fontSize(20) 1974 Web({ src: $rawfile('index.html'), controller: this.controller }) 1975 .javaScriptAccess(true) 1976 .onPageEnd(e => { 1977 try { 1978 this.controller.runJavaScriptExt( 1979 'test()', 1980 (error, result) => { 1981 if (error) { 1982 console.error(`run JavaScript error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`) 1983 return; 1984 } 1985 if (result) { 1986 try { 1987 let type = result.getType(); 1988 switch (type) { 1989 case webview.JsMessageType.STRING: { 1990 this.msg1 = "result type:" + typeof (result.getString()); 1991 this.msg2 = "result getString:" + ((result.getString())); 1992 break; 1993 } 1994 case webview.JsMessageType.NUMBER: { 1995 this.msg1 = "result type:" + typeof (result.getNumber()); 1996 this.msg2 = "result getNumber:" + ((result.getNumber())); 1997 break; 1998 } 1999 case webview.JsMessageType.BOOLEAN: { 2000 this.msg1 = "result type:" + typeof (result.getBoolean()); 2001 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 2002 break; 2003 } 2004 case webview.JsMessageType.ARRAY_BUFFER: { 2005 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 2006 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 2007 break; 2008 } 2009 case webview.JsMessageType.ARRAY: { 2010 this.msg1 = "result type:" + typeof (result.getArray()); 2011 this.msg2 = "result getArray:" + result.getArray(); 2012 break; 2013 } 2014 default: { 2015 this.msg1 = "default break, type:" + type; 2016 break; 2017 } 2018 } 2019 } 2020 catch (resError) { 2021 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2022 } 2023 } 2024 }); 2025 if (e) { 2026 console.info('url: ', e.url); 2027 } 2028 } catch (error) { 2029 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2030 } 2031 }) 2032 } 2033 } 2034} 2035``` 2036 2037```ts 2038// Use the ArrayBuffer input parameter to obtain the JavaScript script data from the file. 2039import { webview } from '@kit.ArkWeb'; 2040import { BusinessError } from '@kit.BasicServicesKit'; 2041import { fileIo } from '@kit.CoreFileKit'; 2042import { common } from '@kit.AbilityKit'; 2043 2044@Entry 2045@Component 2046struct WebComponent { 2047 controller: webview.WebviewController = new webview.WebviewController(); 2048 @State msg1: string = '' 2049 @State msg2: string = '' 2050 2051 build() { 2052 Column() { 2053 Text(this.msg1).fontSize(20) 2054 Text(this.msg2).fontSize(20) 2055 Button('runJavaScriptExt') 2056 .onClick(() => { 2057 try { 2058 let context = getContext(this) as common.UIAbilityContext; 2059 let filePath = context.filesDir + 'test.txt'; 2060 // Create a file and open it. 2061 let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); 2062 // Write data to the file. 2063 fileIo.writeSync(file.fd, "test()"); 2064 // Read data from the file. 2065 let arrayBuffer: ArrayBuffer = new ArrayBuffer(6); 2066 fileIo.readSync(file.fd, arrayBuffer, { offset: 0, length: arrayBuffer.byteLength }); 2067 // Close the file. 2068 fileIo.closeSync(file); 2069 this.controller.runJavaScriptExt( 2070 arrayBuffer, 2071 (error, result) => { 2072 if (error) { 2073 console.error(`run JavaScript error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`) 2074 return; 2075 } 2076 if (result) { 2077 try { 2078 let type = result.getType(); 2079 switch (type) { 2080 case webview.JsMessageType.STRING: { 2081 this.msg1 = "result type:" + typeof (result.getString()); 2082 this.msg2 = "result getString:" + ((result.getString())); 2083 break; 2084 } 2085 case webview.JsMessageType.NUMBER: { 2086 this.msg1 = "result type:" + typeof (result.getNumber()); 2087 this.msg2 = "result getNumber:" + ((result.getNumber())); 2088 break; 2089 } 2090 case webview.JsMessageType.BOOLEAN: { 2091 this.msg1 = "result type:" + typeof (result.getBoolean()); 2092 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 2093 break; 2094 } 2095 case webview.JsMessageType.ARRAY_BUFFER: { 2096 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 2097 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 2098 break; 2099 } 2100 case webview.JsMessageType.ARRAY: { 2101 this.msg1 = "result type:" + typeof (result.getArray()); 2102 this.msg2 = "result getArray:" + result.getArray(); 2103 break; 2104 } 2105 default: { 2106 this.msg1 = "default break, type:" + type; 2107 break; 2108 } 2109 } 2110 } 2111 catch (resError) { 2112 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2113 } 2114 } 2115 }); 2116 } catch (error) { 2117 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2118 } 2119 }) 2120 Web({ src: $rawfile('index.html'), controller: this.controller }) 2121 .javaScriptAccess(true) 2122 } 2123 } 2124} 2125``` 2126 2127HTML file to be loaded: 2128```html 2129<!-- index.html --> 2130<!DOCTYPE html> 2131<html lang="en-gb"> 2132<body> 2133<h1>run JavaScript Ext demo</h1> 2134</body> 2135<script type="text/javascript"> 2136function test() { 2137 return "hello, world"; 2138} 2139</script> 2140</html> 2141``` 2142 2143### runJavaScriptExt<sup>10+</sup> 2144 2145runJavaScriptExt(script: string | ArrayBuffer): Promise\<JsMessageExt> 2146 2147Executes 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**. 2148 2149**System capability**: SystemCapability.Web.Webview.Core 2150 2151**Parameters** 2152 2153| Name| Type| Mandatory| Description | 2154| ------ | -------- | ---- | ---------------- | 2155| script | string \| ArrayBuffer<sup>12+</sup> | Yes | JavaScript script.| 2156 2157**Return value** 2158 2159| Type | Description | 2160| --------------- | --------------------------------------------------- | 2161| Promise\<[JsMessageExt](#jsmessageext10)> | Promise used to return the script execution result.| 2162 2163**Error codes** 2164 2165For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2166 2167| ID| Error Message | 2168| -------- | ------------------------------------------------------------ | 2169| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2170| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2171 2172**Example** 2173 2174```ts 2175// xxx.ets 2176import { webview } from '@kit.ArkWeb'; 2177import { BusinessError } from '@kit.BasicServicesKit'; 2178 2179@Entry 2180@Component 2181struct WebComponent { 2182 controller: webview.WebviewController = new webview.WebviewController(); 2183 @State webResult: string = ''; 2184 @State msg1: string = ''; 2185 @State msg2: string = ''; 2186 2187 build() { 2188 Column() { 2189 Text(this.webResult).fontSize(20) 2190 Text(this.msg1).fontSize(20) 2191 Text(this.msg2).fontSize(20) 2192 Web({ src: $rawfile('index.html'), controller: this.controller }) 2193 .javaScriptAccess(true) 2194 .onPageEnd(() => { 2195 this.controller.runJavaScriptExt('test()') 2196 .then((result) => { 2197 try { 2198 let type = result.getType(); 2199 switch (type) { 2200 case webview.JsMessageType.STRING: { 2201 this.msg1 = "result type:" + typeof (result.getString()); 2202 this.msg2 = "result getString:" + ((result.getString())); 2203 break; 2204 } 2205 case webview.JsMessageType.NUMBER: { 2206 this.msg1 = "result type:" + typeof (result.getNumber()); 2207 this.msg2 = "result getNumber:" + ((result.getNumber())); 2208 break; 2209 } 2210 case webview.JsMessageType.BOOLEAN: { 2211 this.msg1 = "result type:" + typeof (result.getBoolean()); 2212 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 2213 break; 2214 } 2215 case webview.JsMessageType.ARRAY_BUFFER: { 2216 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 2217 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 2218 break; 2219 } 2220 case webview.JsMessageType.ARRAY: { 2221 this.msg1 = "result type:" + typeof (result.getArray()); 2222 this.msg2 = "result getArray:" + result.getArray(); 2223 break; 2224 } 2225 default: { 2226 this.msg1 = "default break, type:" + type; 2227 break; 2228 } 2229 } 2230 } 2231 catch (resError) { 2232 console.error(`ErrorCode: ${(resError as BusinessError).code}, Message: ${(resError as BusinessError).message}`); 2233 } 2234 }).catch((error: BusinessError) => { 2235 console.error("error: " + error); 2236 }) 2237 }) 2238 } 2239 } 2240} 2241``` 2242 2243```ts 2244// Use the ArrayBuffer input parameter to obtain the JavaScript script data from the file. 2245import { webview } from '@kit.ArkWeb'; 2246import { BusinessError } from '@kit.BasicServicesKit'; 2247import { fileIo } from '@kit.CoreFileKit'; 2248import { common } from '@kit.AbilityKit'; 2249 2250@Entry 2251@Component 2252struct WebComponent { 2253 controller: webview.WebviewController = new webview.WebviewController(); 2254 @State msg1: string = ''; 2255 @State msg2: string = ''; 2256 2257 build() { 2258 Column() { 2259 Text(this.msg1).fontSize(20) 2260 Text(this.msg2).fontSize(20) 2261 Button('runJavaScriptExt') 2262 .onClick(() => { 2263 try { 2264 let context = getContext(this) as common.UIAbilityContext; 2265 let filePath = context.filesDir + 'test.txt'; 2266 // Create a file and open it. 2267 let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); 2268 // Write data to the file. 2269 fileIo.writeSync(file.fd, "test()"); 2270 // Read data from the file. 2271 let arrayBuffer: ArrayBuffer = new ArrayBuffer(6); 2272 fileIo.readSync(file.fd, arrayBuffer, { offset: 0, length: arrayBuffer.byteLength }); 2273 // Close the file. 2274 fileIo.closeSync(file); 2275 this.controller.runJavaScriptExt(arrayBuffer) 2276 .then((result) => { 2277 try { 2278 let type = result.getType(); 2279 switch (type) { 2280 case webview.JsMessageType.STRING: { 2281 this.msg1 = "result type:" + typeof (result.getString()); 2282 this.msg2 = "result getString:" + ((result.getString())); 2283 break; 2284 } 2285 case webview.JsMessageType.NUMBER: { 2286 this.msg1 = "result type:" + typeof (result.getNumber()); 2287 this.msg2 = "result getNumber:" + ((result.getNumber())); 2288 break; 2289 } 2290 case webview.JsMessageType.BOOLEAN: { 2291 this.msg1 = "result type:" + typeof (result.getBoolean()); 2292 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 2293 break; 2294 } 2295 case webview.JsMessageType.ARRAY_BUFFER: { 2296 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 2297 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 2298 break; 2299 } 2300 case webview.JsMessageType.ARRAY: { 2301 this.msg1 = "result type:" + typeof (result.getArray()); 2302 this.msg2 = "result getArray:" + result.getArray(); 2303 break; 2304 } 2305 default: { 2306 this.msg1 = "default break, type:" + type; 2307 break; 2308 } 2309 } 2310 } 2311 catch (resError) { 2312 console.error(`ErrorCode: ${(resError as BusinessError).code}, Message: ${(resError as BusinessError).message}`); 2313 } 2314 }) 2315 .catch((error: BusinessError) => { 2316 console.error("error: " + error); 2317 }) 2318 } catch (error) { 2319 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2320 } 2321 }) 2322 Web({ src: $rawfile('index.html'), controller: this.controller }) 2323 .javaScriptAccess(true) 2324 } 2325 } 2326} 2327``` 2328 2329HTML file to be loaded: 2330```html 2331<!-- index.html --> 2332<!DOCTYPE html> 2333<html lang="en-gb"> 2334<body> 2335<h1>run JavaScript Ext demo</h1> 2336</body> 2337<script type="text/javascript"> 2338function test() { 2339 return "hello, world"; 2340} 2341</script> 2342</html> 2343``` 2344 2345### deleteJavaScriptRegister 2346 2347deleteJavaScriptRegister(name: string): void 2348 2349Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. After the deletion, the [refresh](#refresh) API must be called. 2350 2351**System capability**: SystemCapability.Web.Webview.Core 2352 2353**Parameters** 2354 2355| Name| Type| Mandatory| Description | 2356| ------ | -------- | ---- | ---- | 2357| 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.| 2358 2359**Error codes** 2360 2361For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2362 2363| ID| Error Message | 2364| -------- | ------------------------------------------------------------ | 2365| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2366| 17100008 | Failed to delete JavaScriptProxy because it does not exist. | 2367| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2368 2369**Example** 2370 2371```ts 2372// xxx.ets 2373import { webview } from '@kit.ArkWeb'; 2374import { BusinessError } from '@kit.BasicServicesKit'; 2375 2376class TestObj { 2377 constructor() { 2378 } 2379 2380 test(): string { 2381 return "ArkUI Web Component"; 2382 } 2383 2384 toString(): void { 2385 console.log('Web Component toString'); 2386 } 2387} 2388 2389@Entry 2390@Component 2391struct WebComponent { 2392 controller: webview.WebviewController = new webview.WebviewController(); 2393 @State testObjtest: TestObj = new TestObj(); 2394 @State name: string = 'objName'; 2395 build() { 2396 Column() { 2397 Button('refresh') 2398 .onClick(() => { 2399 try { 2400 this.controller.refresh(); 2401 } catch (error) { 2402 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2403 } 2404 }) 2405 Button('Register JavaScript To Window') 2406 .onClick(() => { 2407 try { 2408 this.controller.registerJavaScriptProxy(this.testObjtest, this.name, ["test", "toString"]); 2409 } catch (error) { 2410 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2411 } 2412 }) 2413 Button('deleteJavaScriptRegister') 2414 .onClick(() => { 2415 try { 2416 this.controller.deleteJavaScriptRegister(this.name); 2417 } catch (error) { 2418 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2419 } 2420 }) 2421 Web({ src: $rawfile('index.html'), controller: this.controller }) 2422 .javaScriptAccess(true) 2423 } 2424 } 2425} 2426``` 2427 2428HTML file to be loaded: 2429```html 2430<!-- index.html --> 2431<!DOCTYPE html> 2432<html> 2433 <meta charset="utf-8"> 2434 <body> 2435 <button type="button" onclick="htmlTest()">Click Me!</button> 2436 <p id="demo"></p> 2437 </body> 2438 <script type="text/javascript"> 2439 function htmlTest() { 2440 let str=objName.test(); 2441 document.getElementById("demo").innerHTML=str; 2442 console.log('objName.test result:'+ str) 2443 } 2444</script> 2445</html> 2446``` 2447 2448### zoom 2449 2450zoom(factor: number): void 2451 2452Zooms in or out of this web page. This API is effective only when [zoomAccess](ts-basic-components-web.md#zoomaccess) is **true**. 2453 2454**System capability**: SystemCapability.Web.Webview.Core 2455 2456**Parameters** 2457 2458| Name| Type| Mandatory| Description| 2459| ------ | -------- | ---- | ------------------------------------------------------------ | 2460| 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.| 2461 2462**Error codes** 2463 2464For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2465 2466| ID| Error Message | 2467| -------- | ------------------------------------------------------------ | 2468| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2469| 17100004 | Function not enabled. | 2470| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2471 2472**Example** 2473 2474```ts 2475// xxx.ets 2476import { webview } from '@kit.ArkWeb'; 2477import { BusinessError } from '@kit.BasicServicesKit'; 2478 2479@Entry 2480@Component 2481struct WebComponent { 2482 controller: webview.WebviewController = new webview.WebviewController(); 2483 @State factor: number = 1; 2484 2485 build() { 2486 Column() { 2487 Button('zoom') 2488 .onClick(() => { 2489 try { 2490 this.controller.zoom(this.factor); 2491 } catch (error) { 2492 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2493 } 2494 }) 2495 Web({ src: 'www.example.com', controller: this.controller }) 2496 .zoomAccess(true) 2497 } 2498 } 2499} 2500``` 2501 2502### searchAllAsync 2503 2504searchAllAsync(searchString: string): void 2505 2506Searches 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). 2507 2508**System capability**: SystemCapability.Web.Webview.Core 2509 2510**Parameters** 2511 2512| Name | Type| Mandatory| Description | 2513| ------------ | -------- | ---- | -------------- | 2514| searchString | string | Yes | Search keyword.| 2515 2516**Error codes** 2517 2518For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2519 2520| ID| Error Message | 2521| -------- | ------------------------------------------------------------ | 2522| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2523| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2524 2525**Example** 2526 2527```ts 2528// xxx.ets 2529import { webview } from '@kit.ArkWeb'; 2530import { BusinessError } from '@kit.BasicServicesKit'; 2531 2532@Entry 2533@Component 2534struct WebComponent { 2535 controller: webview.WebviewController = new webview.WebviewController(); 2536 @State searchString: string = "Hello World"; 2537 2538 build() { 2539 Column() { 2540 Button('searchString') 2541 .onClick(() => { 2542 try { 2543 this.controller.searchAllAsync(this.searchString); 2544 } catch (error) { 2545 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2546 } 2547 }) 2548 Web({ src: $rawfile('index.html'), controller: this.controller }) 2549 .onSearchResultReceive(ret => { 2550 if (ret) { 2551 console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal + 2552 "[total]" + ret.numberOfMatches + "[isDone]" + ret.isDoneCounting); 2553 } 2554 }) 2555 } 2556 } 2557} 2558``` 2559 2560HTML file to be loaded: 2561```html 2562<!-- index.html --> 2563<!DOCTYPE html> 2564<html> 2565 <body> 2566 <p>Hello World Highlight Hello World</p> 2567 </body> 2568</html> 2569``` 2570 2571### clearMatches 2572 2573clearMatches(): void 2574 2575Clears the matches found through [searchAllAsync](#searchallasync). 2576 2577**System capability**: SystemCapability.Web.Webview.Core 2578 2579**Error codes** 2580 2581For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2582 2583| ID| Error Message | 2584| -------- | ------------------------------------------------------------ | 2585| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2586 2587**Example** 2588 2589```ts 2590// xxx.ets 2591import { webview } from '@kit.ArkWeb'; 2592import { BusinessError } from '@kit.BasicServicesKit'; 2593 2594@Entry 2595@Component 2596struct WebComponent { 2597 controller: webview.WebviewController = new webview.WebviewController(); 2598 2599 build() { 2600 Column() { 2601 Button('clearMatches') 2602 .onClick(() => { 2603 try { 2604 this.controller.clearMatches(); 2605 } catch (error) { 2606 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2607 } 2608 }) 2609 Web({ src: $rawfile('index.html'), controller: this.controller }) 2610 } 2611 } 2612} 2613``` 2614 2615For details about the HTML file loaded, see the HMTL file loaded using [searchAllAsync](#searchallasync). 2616 2617### searchNext 2618 2619searchNext(forward: boolean): void 2620 2621Searches for and highlights the next match. 2622 2623**System capability**: SystemCapability.Web.Webview.Core 2624 2625**Parameters** 2626 2627| Name | Type| Mandatory| Description | 2628| ------- | -------- | ---- | ---------------------- | 2629| forward | boolean | Yes | Whether to search forward.| 2630 2631**Error codes** 2632 2633For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2634 2635| ID| Error Message | 2636| -------- | ------------------------------------------------------------ | 2637| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2638| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2639 2640**Example** 2641 2642```ts 2643// xxx.ets 2644import { webview } from '@kit.ArkWeb'; 2645import { BusinessError } from '@kit.BasicServicesKit'; 2646 2647@Entry 2648@Component 2649struct WebComponent { 2650 controller: webview.WebviewController = new webview.WebviewController(); 2651 2652 build() { 2653 Column() { 2654 Button('searchNext') 2655 .onClick(() => { 2656 try { 2657 this.controller.searchNext(true); 2658 } catch (error) { 2659 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2660 } 2661 }) 2662 Web({ src: $rawfile('index.html'), controller: this.controller }) 2663 } 2664 } 2665} 2666``` 2667 2668For details about the HTML file loaded, see the HMTL file loaded using [searchAllAsync](#searchallasync). 2669 2670### clearSslCache 2671 2672clearSslCache(): void 2673 2674Clears the user operation corresponding to the SSL certificate error event recorded by the **Web** component. 2675 2676**System capability**: SystemCapability.Web.Webview.Core 2677 2678**Error codes** 2679 2680For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2681 2682| ID| Error Message | 2683| -------- | ------------------------------------------------------------ | 2684| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2685 2686**Example** 2687 2688```ts 2689// xxx.ets 2690import { webview } from '@kit.ArkWeb'; 2691import { BusinessError } from '@kit.BasicServicesKit'; 2692 2693@Entry 2694@Component 2695struct WebComponent { 2696 controller: webview.WebviewController = new webview.WebviewController(); 2697 2698 build() { 2699 Column() { 2700 Button('clearSslCache') 2701 .onClick(() => { 2702 try { 2703 this.controller.clearSslCache(); 2704 } catch (error) { 2705 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2706 } 2707 }) 2708 Web({ src: 'www.example.com', controller: this.controller }) 2709 } 2710 } 2711} 2712``` 2713 2714### clearClientAuthenticationCache 2715 2716clearClientAuthenticationCache(): void 2717 2718Clears the user operation corresponding to the client certificate request event recorded by the **Web** component. 2719 2720**System capability**: SystemCapability.Web.Webview.Core 2721 2722**Error codes** 2723 2724For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2725 2726| ID| Error Message | 2727| -------- | ------------------------------------------------------------ | 2728| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2729 2730**Example** 2731 2732```ts 2733// xxx.ets 2734import { webview } from '@kit.ArkWeb'; 2735import { BusinessError } from '@kit.BasicServicesKit'; 2736 2737@Entry 2738@Component 2739struct WebComponent { 2740 controller: webview.WebviewController = new webview.WebviewController(); 2741 2742 build() { 2743 Column() { 2744 Button('clearClientAuthenticationCache') 2745 .onClick(() => { 2746 try { 2747 this.controller.clearClientAuthenticationCache(); 2748 } catch (error) { 2749 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2750 } 2751 }) 2752 Web({ src: 'www.example.com', controller: this.controller }) 2753 } 2754 } 2755} 2756``` 2757 2758### createWebMessagePorts 2759 2760createWebMessagePorts(isExtentionType?: boolean): Array\<WebMessagePort> 2761 2762Creates web message ports. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 2763 2764**System capability**: SystemCapability.Web.Webview.Core 2765 2766**Parameters** 2767 2768| Name| Type | Mandatory| Description | 2769| ------ | ---------------------- | ---- | :------------------------------| 2770| 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.| 2771 2772**Return value** 2773 2774| Type | Description | 2775| ---------------------- | ----------------- | 2776| Array\<[WebMessagePort](#webmessageport)> | List of web message ports.| 2777 2778**Error codes** 2779 2780For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2781 2782| ID| Error Message | 2783| -------- | ------------------------------------------------------------ | 2784| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2785| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2786 2787**Example** 2788 2789```ts 2790// xxx.ets 2791import { webview } from '@kit.ArkWeb'; 2792import { BusinessError } from '@kit.BasicServicesKit'; 2793 2794@Entry 2795@Component 2796struct WebComponent { 2797 controller: webview.WebviewController = new webview.WebviewController(); 2798 ports: webview.WebMessagePort[] = []; 2799 2800 build() { 2801 Column() { 2802 Button('createWebMessagePorts') 2803 .onClick(() => { 2804 try { 2805 this.ports = this.controller.createWebMessagePorts(); 2806 console.log("createWebMessagePorts size:" + this.ports.length); 2807 } catch (error) { 2808 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2809 } 2810 }) 2811 Web({ src: 'www.example.com', controller: this.controller }) 2812 } 2813 } 2814} 2815``` 2816 2817### postMessage 2818 2819postMessage(name: string, ports: Array\<WebMessagePort>, uri: string): void 2820 2821Sends a web message to an HTML window. 2822 2823**System capability**: SystemCapability.Web.Webview.Core 2824 2825**Parameters** 2826 2827| Name| Type | Mandatory| Description | 2828| ------ | ---------------------- | ---- | :------------------------------- | 2829| name | string | Yes | Name of the message to send. | 2830| ports | Array\<[WebMessagePort](#webmessageport)> | Yes | Message ports for sending the message. | 2831| uri | string | Yes | URI for receiving the message. | 2832 2833**Error codes** 2834 2835For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2836 2837| ID| Error Message | 2838| -------- | ------------------------------------------------------------ | 2839| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2840| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2841 2842**Example** 2843 2844```ts 2845// xxx.ets 2846import { webview } from '@kit.ArkWeb'; 2847import { BusinessError } from '@kit.BasicServicesKit'; 2848 2849@Entry 2850@Component 2851struct WebComponent { 2852 controller: webview.WebviewController = new webview.WebviewController(); 2853 ports: webview.WebMessagePort[] = []; 2854 @State sendFromEts: string = 'Send this message from ets to HTML'; 2855 @State receivedFromHtml: string = 'Display received message send from HTML'; 2856 2857 build() { 2858 Column() { 2859 // Display the received HTML content. 2860 Text(this.receivedFromHtml) 2861 // Send the content in the text box to an HTML window. 2862 TextInput({ placeholder: 'Send this message from ets to HTML' }) 2863 .onChange((value: string) => { 2864 this.sendFromEts = value; 2865 }) 2866 2867 Button('postMessage') 2868 .onClick(() => { 2869 try { 2870 // 1. Create two message ports. 2871 this.ports = this.controller.createWebMessagePorts(); 2872 // 2. Register a callback on a message port (for example, port 1) on the application side. 2873 this.ports[1].onMessageEvent((result: webview.WebMessage) => { 2874 let msg = 'Got msg from HTML:'; 2875 if (typeof (result) == "string") { 2876 console.log("received string message from html5, string is:" + result); 2877 msg = msg + result; 2878 } else if (typeof (result) == "object") { 2879 if (result instanceof ArrayBuffer) { 2880 console.log("received arraybuffer from html5, length is:" + result.byteLength); 2881 msg = msg + "length is " + result.byteLength; 2882 } else { 2883 console.log("not support"); 2884 } 2885 } else { 2886 console.log("not support"); 2887 } 2888 this.receivedFromHtml = msg; 2889 }) 2890 // 3. Send another message port (for example, port 0) to the HTML side, which can then save the port for future use. 2891 this.controller.postMessage('__init_port__', [this.ports[0]], '*'); 2892 } catch (error) { 2893 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2894 } 2895 }) 2896 2897 // 4. Use the port on the application side to send messages to the port that has been sent to the HTML side. 2898 Button('SendDataToHTML') 2899 .onClick(() => { 2900 try { 2901 if (this.ports && this.ports[1]) { 2902 this.ports[1].postMessageEvent(this.sendFromEts); 2903 } else { 2904 console.error(`ports is null, Please initialize first`); 2905 } 2906 } catch (error) { 2907 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2908 } 2909 }) 2910 Web({ src: $rawfile('index.html'), controller: this.controller }) 2911 } 2912 } 2913} 2914``` 2915 2916HTML file to be loaded: 2917```html 2918<!--index.html--> 2919<!DOCTYPE html> 2920<html> 2921<head> 2922 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 2923 <title>WebView Message Port Demo</title> 2924</head> 2925 2926 <body> 2927 <h1>WebView Message Port Demo</h1> 2928 <div> 2929 <input type="button" value="SendToEts" onclick="PostMsgToEts(msgFromJS.value);"/><br/> 2930 <input id="msgFromJS" type="text" value="send this message from HTML to ets"/><br/> 2931 </div> 2932 <p class="output">display received message send from ets</p> 2933 </body> 2934 <script src="xxx.js"></script> 2935</html> 2936``` 2937 2938```js 2939//xxx.js 2940var h5Port; 2941var output = document.querySelector('.output'); 2942window.addEventListener('message', function (event) { 2943 if (event.data == '__init_port__') { 2944 if (event.ports[0] != null) { 2945 h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side. 2946 h5Port.onmessage = function (event) { 2947 // 2. Receive the message sent from the eTS side. 2948 var msg = 'Got message from ets:'; 2949 var result = event.data; 2950 if (typeof(result) == "string") { 2951 console.log("received string message from html5, string is:" + result); 2952 msg = msg + result; 2953 } else if (typeof(result) == "object") { 2954 if (result instanceof ArrayBuffer) { 2955 console.log("received arraybuffer from html5, length is:" + result.byteLength); 2956 msg = msg + "length is " + result.byteLength; 2957 } else { 2958 console.log("not support"); 2959 } 2960 } else { 2961 console.log("not support"); 2962 } 2963 output.innerHTML = msg; 2964 } 2965 } 2966 } 2967}) 2968 2969// 3. Use h5Port to send messages to the eTS side. 2970function PostMsgToEts(data) { 2971 if (h5Port) { 2972 h5Port.postMessage(data); 2973 } else { 2974 console.error("h5Port is null, Please initialize first"); 2975 } 2976} 2977``` 2978 2979### requestFocus 2980 2981requestFocus(): void 2982 2983Requests focus for this web page. 2984 2985**System capability**: SystemCapability.Web.Webview.Core 2986 2987**Error codes** 2988 2989For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 2990 2991| ID| Error Message | 2992| -------- | ------------------------------------------------------------ | 2993| 17100001 | Init error. The WebviewController must be associated with a Web component. | 2994 2995**Example** 2996 2997```ts 2998// xxx.ets 2999import { webview } from '@kit.ArkWeb'; 3000import { BusinessError } from '@kit.BasicServicesKit'; 3001 3002@Entry 3003@Component 3004struct WebComponent { 3005 controller: webview.WebviewController = new webview.WebviewController(); 3006 3007 build() { 3008 Column() { 3009 Button('requestFocus') 3010 .onClick(() => { 3011 try { 3012 this.controller.requestFocus(); 3013 } catch (error) { 3014 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3015 } 3016 }); 3017 Web({ src: 'www.example.com', controller: this.controller }) 3018 } 3019 } 3020} 3021``` 3022 3023### zoomIn 3024 3025zoomIn(): void 3026 3027Zooms in on this web page by 20%. 3028 3029**System capability**: SystemCapability.Web.Webview.Core 3030 3031**Error codes** 3032 3033For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3034 3035| ID| Error Message | 3036| -------- | ------------------------------------------------------------ | 3037| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3038| 17100004 | Function not enabled. | 3039 3040**Example** 3041 3042```ts 3043// xxx.ets 3044import { webview } from '@kit.ArkWeb'; 3045import { BusinessError } from '@kit.BasicServicesKit'; 3046 3047@Entry 3048@Component 3049struct WebComponent { 3050 controller: webview.WebviewController = new webview.WebviewController(); 3051 3052 build() { 3053 Column() { 3054 Button('zoomIn') 3055 .onClick(() => { 3056 try { 3057 this.controller.zoomIn(); 3058 } catch (error) { 3059 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3060 } 3061 }) 3062 Web({ src: 'www.example.com', controller: this.controller }) 3063 } 3064 } 3065} 3066``` 3067 3068### zoomOut 3069 3070zoomOut(): void 3071 3072Zooms out of this web page by 20%. 3073 3074**System capability**: SystemCapability.Web.Webview.Core 3075 3076**Error codes** 3077 3078For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3079 3080| ID| Error Message | 3081| -------- | ------------------------------------------------------------ | 3082| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3083| 17100004 | Function not enabled. | 3084 3085**Example** 3086 3087```ts 3088// xxx.ets 3089import { webview } from '@kit.ArkWeb'; 3090import { BusinessError } from '@kit.BasicServicesKit'; 3091 3092@Entry 3093@Component 3094struct WebComponent { 3095 controller: webview.WebviewController = new webview.WebviewController(); 3096 3097 build() { 3098 Column() { 3099 Button('zoomOut') 3100 .onClick(() => { 3101 try { 3102 this.controller.zoomOut(); 3103 } catch (error) { 3104 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3105 } 3106 }) 3107 Web({ src: 'www.example.com', controller: this.controller }) 3108 } 3109 } 3110} 3111``` 3112 3113### getHitTestValue 3114 3115getHitTestValue(): HitTestValue 3116 3117Obtains the element information of the area being clicked. 3118 3119**System capability**: SystemCapability.Web.Webview.Core 3120 3121**Return value** 3122 3123| Type | Description | 3124| ------------ | -------------------- | 3125| [HitTestValue](#hittestvalue) | Element information of the area being clicked.| 3126 3127**Error codes** 3128 3129For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3130 3131| ID| Error Message | 3132| -------- | ------------------------------------------------------------ | 3133| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3134 3135**Example** 3136 3137```ts 3138// xxx.ets 3139import { webview } from '@kit.ArkWeb'; 3140import { BusinessError } from '@kit.BasicServicesKit'; 3141 3142@Entry 3143@Component 3144struct WebComponent { 3145 controller: webview.WebviewController = new webview.WebviewController(); 3146 3147 build() { 3148 Column() { 3149 Button('getHitTestValue') 3150 .onClick(() => { 3151 try { 3152 let hitValue = this.controller.getHitTestValue(); 3153 console.log("hitType: " + hitValue.type); 3154 console.log("extra: " + hitValue.extra); 3155 } catch (error) { 3156 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3157 } 3158 }) 3159 Web({ src: 'www.example.com', controller: this.controller }) 3160 } 3161 } 3162} 3163``` 3164 3165### getWebId 3166 3167getWebId(): number 3168 3169Obtains the index value of this **Web** component, which can be used for **Web** component management. 3170 3171**System capability**: SystemCapability.Web.Webview.Core 3172 3173**Return value** 3174 3175| Type | Description | 3176| ------ | --------------------- | 3177| number | Index value of the current **Web** component.| 3178 3179**Error codes** 3180 3181For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3182 3183| ID| Error Message | 3184| -------- | ------------------------------------------------------------ | 3185| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3186 3187**Example** 3188 3189```ts 3190// xxx.ets 3191import { webview } from '@kit.ArkWeb'; 3192import { BusinessError } from '@kit.BasicServicesKit'; 3193 3194@Entry 3195@Component 3196struct WebComponent { 3197 controller: webview.WebviewController = new webview.WebviewController(); 3198 3199 build() { 3200 Column() { 3201 Button('getWebId') 3202 .onClick(() => { 3203 try { 3204 let id = this.controller.getWebId(); 3205 console.log("id: " + id); 3206 } catch (error) { 3207 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3208 } 3209 }) 3210 Web({ src: 'www.example.com', controller: this.controller }) 3211 } 3212 } 3213} 3214``` 3215 3216### getUserAgent 3217 3218getUserAgent(): string 3219 3220Obtains the default user agent of this web page. 3221 3222For details about the default **UserAgent**, see [Default User Agent String](../../web/web-default-userAgent.md). 3223 3224**System capability**: SystemCapability.Web.Webview.Core 3225 3226**Return value** 3227 3228| Type | Description | 3229| ------ | -------------- | 3230| string | Default user agent.| 3231 3232**Error codes** 3233 3234For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3235 3236| ID| Error Message | 3237| -------- | ------------------------------------------------------------ | 3238| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3239 3240**Example** 3241 3242```ts 3243// xxx.ets 3244import { webview } from '@kit.ArkWeb'; 3245import { BusinessError } from '@kit.BasicServicesKit'; 3246 3247@Entry 3248@Component 3249struct WebComponent { 3250 controller: webview.WebviewController = new webview.WebviewController(); 3251 3252 build() { 3253 Column() { 3254 Button('getUserAgent') 3255 .onClick(() => { 3256 try { 3257 let userAgent = this.controller.getUserAgent(); 3258 console.log("userAgent: " + userAgent); 3259 } catch (error) { 3260 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3261 } 3262 }) 3263 Web({ src: 'www.example.com', controller: this.controller }) 3264 } 3265 } 3266} 3267``` 3268 3269You can define a custom user agent based on the default user agent. 3270```ts 3271// xxx.ets 3272import { webview } from '@kit.ArkWeb'; 3273import { BusinessError } from '@kit.BasicServicesKit'; 3274 3275@Entry 3276@Component 3277struct WebComponent { 3278 controller: webview.WebviewController = new webview.WebviewController(); 3279 @State ua: string = ""; 3280 3281 aboutToAppear(): void { 3282 webview.once('webInited', () => { 3283 try { 3284 // Define a custom user agent on the application side. 3285 this.ua = this.controller.getUserAgent() + 'xxx'; 3286 this.controller.setCustomUserAgent(this.ua); 3287 } catch (error) { 3288 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3289 } 3290 }) 3291 } 3292 3293 build() { 3294 Column() { 3295 Web({ src: 'www.example.com', controller: this.controller }) 3296 } 3297 } 3298} 3299``` 3300 3301### getTitle 3302 3303getTitle(): string 3304 3305Obtains the title of the current web page. 3306 3307**System capability**: SystemCapability.Web.Webview.Core 3308 3309**Return value** 3310 3311| Type | Description | 3312| ------ | -------------------- | 3313| string | Title of the current web page.| 3314 3315**Error codes** 3316 3317For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3318 3319| ID| Error Message | 3320| -------- | ------------------------------------------------------------ | 3321| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3322 3323**Example** 3324 3325```ts 3326// xxx.ets 3327import { webview } from '@kit.ArkWeb'; 3328import { BusinessError } from '@kit.BasicServicesKit'; 3329 3330@Entry 3331@Component 3332struct WebComponent { 3333 controller: webview.WebviewController = new webview.WebviewController(); 3334 3335 build() { 3336 Column() { 3337 Button('getTitle') 3338 .onClick(() => { 3339 try { 3340 let title = this.controller.getTitle(); 3341 console.log("title: " + title); 3342 } catch (error) { 3343 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3344 } 3345 }) 3346 Web({ src: 'www.example.com', controller: this.controller }) 3347 } 3348 } 3349} 3350``` 3351 3352### getPageHeight 3353 3354getPageHeight(): number 3355 3356Obtains the height of this web page. 3357 3358**System capability**: SystemCapability.Web.Webview.Core 3359 3360**Return value** 3361 3362| Type | Description | 3363| ------ | -------------------- | 3364| number | Height of the current web page. Unit: vp| 3365 3366**Error codes** 3367 3368For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3369 3370| ID| Error Message | 3371| -------- | ------------------------------------------------------------ | 3372| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3373 3374**Example** 3375 3376```ts 3377// xxx.ets 3378import { webview } from '@kit.ArkWeb'; 3379import { BusinessError } from '@kit.BasicServicesKit'; 3380 3381@Entry 3382@Component 3383struct WebComponent { 3384 controller: webview.WebviewController = new webview.WebviewController(); 3385 3386 build() { 3387 Column() { 3388 Button('getPageHeight') 3389 .onClick(() => { 3390 try { 3391 let pageHeight = this.controller.getPageHeight(); 3392 console.log("pageHeight : " + pageHeight); 3393 } catch (error) { 3394 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3395 } 3396 }) 3397 Web({ src: 'www.example.com', controller: this.controller }) 3398 } 3399 } 3400} 3401``` 3402 3403### storeWebArchive 3404 3405storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback\<string>): void 3406 3407Stores this web page. This API uses an asynchronous callback to return the result. 3408 3409**System capability**: SystemCapability.Web.Webview.Core 3410 3411**Parameters** 3412 3413| Name | Type | Mandatory| Description | 3414| -------- | --------------------- | ---- | ------------------------------------------------------------ | 3415| baseName | string | Yes | Save path of the web page. The value cannot be null. | 3416| 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.| 3417| callback | AsyncCallback\<string> | Yes | Callback used to return the save path if the operation is successful and null otherwise. | 3418 3419**Error codes** 3420 3421For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3422 3423| ID| Error Message | 3424| -------- | ------------------------------------------------------------ | 3425| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3426| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3427| 17100003 | Invalid resource path or file type. | 3428 3429**Example** 3430 3431```ts 3432// xxx.ets 3433import { webview } from '@kit.ArkWeb'; 3434import { BusinessError } from '@kit.BasicServicesKit'; 3435 3436@Entry 3437@Component 3438struct WebComponent { 3439 controller: webview.WebviewController = new webview.WebviewController(); 3440 3441 build() { 3442 Column() { 3443 Button('storeWebArchive') 3444 .onClick(() => { 3445 try { 3446 this.controller.storeWebArchive("/data/storage/el2/base/", true, (error, filename) => { 3447 if (error) { 3448 console.error(`save web archive error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3449 return; 3450 } 3451 if (filename != null) { 3452 console.info(`save web archive success: ${filename}`); 3453 } 3454 }); 3455 } catch (error) { 3456 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3457 } 3458 }) 3459 Web({ src: 'www.example.com', controller: this.controller }) 3460 } 3461 } 3462} 3463``` 3464 3465### storeWebArchive 3466 3467storeWebArchive(baseName: string, autoName: boolean): Promise\<string> 3468 3469Stores this web page. This API uses a promise to return the result. 3470 3471**System capability**: SystemCapability.Web.Webview.Core 3472 3473**Parameters** 3474 3475| Name | Type| Mandatory| Description | 3476| -------- | -------- | ---- | ------------------------------------------------------------ | 3477| baseName | string | Yes | Save path of the web page. The value cannot be null. | 3478| 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.| 3479 3480**Return value** 3481 3482| Type | Description | 3483| --------------- | ----------------------------------------------------- | 3484| Promise\<string> | Promise used to return the save path if the operation is successful and null otherwise.| 3485 3486**Error codes** 3487 3488For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3489 3490| ID| Error Message | 3491| -------- | ------------------------------------------------------------ | 3492| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 3493| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3494| 17100003 | Invalid resource path or file type. | 3495 3496**Example** 3497 3498```ts 3499// xxx.ets 3500import { webview } from '@kit.ArkWeb'; 3501import { BusinessError } from '@kit.BasicServicesKit'; 3502 3503@Entry 3504@Component 3505struct WebComponent { 3506 controller: webview.WebviewController = new webview.WebviewController(); 3507 3508 build() { 3509 Column() { 3510 Button('storeWebArchive') 3511 .onClick(() => { 3512 try { 3513 this.controller.storeWebArchive("/data/storage/el2/base/", true) 3514 .then(filename => { 3515 if (filename != null) { 3516 console.info(`save web archive success: ${filename}`) 3517 } 3518 }) 3519 .catch((error: BusinessError) => { 3520 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 3521 }) 3522 } catch (error) { 3523 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3524 } 3525 }) 3526 Web({ src: 'www.example.com', controller: this.controller }) 3527 } 3528 } 3529} 3530``` 3531 3532### getUrl 3533 3534getUrl(): string 3535 3536Obtains the URL of this page. 3537 3538**System capability**: SystemCapability.Web.Webview.Core 3539 3540**Return value** 3541 3542| Type | Description | 3543| ------ | ------------------- | 3544| string | URL of the current page.| 3545 3546**Error codes** 3547 3548For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3549 3550| ID| Error Message | 3551| -------- | ------------------------------------------------------------ | 3552| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3553 3554**Example** 3555 3556```ts 3557// xxx.ets 3558import { webview } from '@kit.ArkWeb'; 3559import { BusinessError } from '@kit.BasicServicesKit'; 3560 3561@Entry 3562@Component 3563struct WebComponent { 3564 controller: webview.WebviewController = new webview.WebviewController(); 3565 3566 build() { 3567 Column() { 3568 Button('getUrl') 3569 .onClick(() => { 3570 try { 3571 let url = this.controller.getUrl(); 3572 console.log("url: " + url); 3573 } catch (error) { 3574 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3575 } 3576 }) 3577 Web({ src: 'www.example.com', controller: this.controller }) 3578 } 3579 } 3580} 3581``` 3582 3583### stop 3584 3585stop(): void 3586 3587Stops page loading. 3588 3589**System capability**: SystemCapability.Web.Webview.Core 3590 3591**Error codes** 3592 3593For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3594 3595| ID| Error Message | 3596| -------- | ------------------------------------------------------------ | 3597| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3598 3599**Example** 3600 3601```ts 3602// xxx.ets 3603import { webview } from '@kit.ArkWeb'; 3604import { BusinessError } from '@kit.BasicServicesKit'; 3605 3606@Entry 3607@Component 3608struct WebComponent { 3609 controller: webview.WebviewController = new webview.WebviewController(); 3610 3611 build() { 3612 Column() { 3613 Button('stop') 3614 .onClick(() => { 3615 try { 3616 this.controller.stop(); 3617 } catch (error) { 3618 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3619 } 3620 }); 3621 Web({ src: 'www.example.com', controller: this.controller }) 3622 } 3623 } 3624} 3625``` 3626 3627### backOrForward 3628 3629backOrForward(step: number): void 3630 3631Performs 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. 3632 3633Because the previously loaded web pages are used for the operation, no page reloading is involved. 3634 3635**System capability**: SystemCapability.Web.Webview.Core 3636 3637**Parameters** 3638 3639| Name| Type| Mandatory| Description | 3640| ------ | -------- | ---- | ---------------------- | 3641| step | number | Yes | Number of the steps to take.| 3642 3643**Error codes** 3644 3645For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3646 3647| ID| Error Message | 3648| -------- | ------------------------------------------------------------ | 3649| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3650| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3651 3652**Example** 3653 3654```ts 3655// xxx.ets 3656import { webview } from '@kit.ArkWeb'; 3657import { BusinessError } from '@kit.BasicServicesKit'; 3658 3659@Entry 3660@Component 3661struct WebComponent { 3662 controller: webview.WebviewController = new webview.WebviewController(); 3663 @State step: number = -2; 3664 3665 build() { 3666 Column() { 3667 Button('backOrForward') 3668 .onClick(() => { 3669 try { 3670 this.controller.backOrForward(this.step); 3671 } catch (error) { 3672 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3673 } 3674 }) 3675 Web({ src: 'www.example.com', controller: this.controller }) 3676 } 3677 } 3678} 3679``` 3680 3681### scrollTo 3682 3683scrollTo(x:number, y:number, duration?:number): void 3684 3685Scrolls the page to the specified absolute position within a specified period. 3686 3687**System capability**: SystemCapability.Web.Webview.Core 3688 3689**Parameters** 3690 3691| Name| Type| Mandatory| Description | 3692| ------ | -------- | ---- | ---------------------- | 3693| x | number | Yes | X coordinate of the absolute position. If the value is a negative number, the value 0 is used. Unit: vp| 3694| y | number | Yes | Y coordinate of the absolute position. If the value is a negative number, the value 0 is used. Unit: vp| 3695| 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.| 3696 3697**Error codes** 3698 3699For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3700 3701| ID| Error Message | 3702| -------- | ------------------------------------------------------------ | 3703| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3704| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3705 3706**Example** 3707 3708```ts 3709// xxx.ets 3710import { webview } from '@kit.ArkWeb'; 3711import { BusinessError } from '@kit.BasicServicesKit'; 3712 3713@Entry 3714@Component 3715struct WebComponent { 3716 controller: webview.WebviewController = new webview.WebviewController(); 3717 3718 build() { 3719 Column() { 3720 Button('scrollTo') 3721 .onClick(() => { 3722 try { 3723 this.controller.scrollTo(50, 50, 500); 3724 } catch (error) { 3725 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3726 } 3727 }) 3728 Button('stopScroll') 3729 .onClick(() => { 3730 try { 3731 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. 3732 } catch (error) { 3733 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3734 } 3735 }) 3736 Web({ src: $rawfile('index.html'), controller: this.controller }) 3737 } 3738 } 3739} 3740``` 3741 3742HTML file to be loaded: 3743```html 3744<!--index.html--> 3745<!DOCTYPE html> 3746<html> 3747<head> 3748 <title>Demo</title> 3749 <style> 3750 body { 3751 width:2000px; 3752 height:2000px; 3753 padding-right:170px; 3754 padding-left:170px; 3755 border:5px solid blueviolet 3756 } 3757 </style> 3758</head> 3759<body> 3760Scroll Test 3761</body> 3762</html> 3763``` 3764 3765### scrollBy 3766 3767scrollBy(deltaX:number, deltaY:number,duration?:number): void 3768 3769Scrolls the page by the specified amount within a specified period. 3770 3771**System capability**: SystemCapability.Web.Webview.Core 3772 3773**Parameters** 3774 3775| Name| Type| Mandatory| Description | 3776| ------ | -------- | ---- | ---------------------- | 3777| deltaX | number | Yes | Amount to scroll by along the x-axis. The positive direction is rightward. Unit: vp| 3778| deltaY | number | Yes | Amount to scroll by along the y-axis. The positive direction is downward. Unit: vp| 3779| 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.| 3780 3781**Error codes** 3782 3783For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3784 3785| ID| Error Message | 3786| -------- | ------------------------------------------------------------ | 3787| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3788| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3789 3790> **NOTE** 3791> 3792> Calling **scrollBy** does not trigger the nested scrolling of the parent component. 3793 3794**Example** 3795 3796```ts 3797// xxx.ets 3798import { webview } from '@kit.ArkWeb'; 3799import { BusinessError } from '@kit.BasicServicesKit'; 3800 3801@Entry 3802@Component 3803struct WebComponent { 3804 controller: webview.WebviewController = new webview.WebviewController(); 3805 3806 build() { 3807 Column() { 3808 Button('scrollBy') 3809 .onClick(() => { 3810 try { 3811 this.controller.scrollBy(50, 50, 500); 3812 } catch (error) { 3813 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3814 } 3815 }) 3816 Button('stopScroll') 3817 .onClick(() => { 3818 try { 3819 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. 3820 } catch (error) { 3821 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3822 } 3823 }) 3824 Web({ src: $rawfile('index.html'), controller: this.controller }) 3825 } 3826 } 3827} 3828``` 3829 3830HTML file to be loaded: 3831```html 3832<!--index.html--> 3833<!DOCTYPE html> 3834<html> 3835<head> 3836 <title>Demo</title> 3837 <style> 3838 body { 3839 width:2000px; 3840 height:2000px; 3841 padding-right:170px; 3842 padding-left:170px; 3843 border:5px solid blueviolet 3844 } 3845 </style> 3846</head> 3847<body> 3848Scroll Test 3849</body> 3850</html> 3851``` 3852### scrollByWithResult<sup>12+</sup> 3853 3854scrollByWithResult(deltaX: number, deltaY: number): boolean 3855 3856Scrolls the page by the specified amount and returns value to indicate whether the scrolling is successful. 3857 3858**System capability**: SystemCapability.Web.Webview.Core 3859 3860**Parameters** 3861 3862| Name| Type| Mandatory| Description | 3863| ------ | -------- | ---- | ---------------------- | 3864| deltaX | number | Yes | Amount to scroll by along the x-axis. The positive direction is rightward.| 3865| deltaY | number | Yes | Amount to scroll by along the y-axis. The positive direction is downward.| 3866 3867**Return value** 3868 3869| Type | Description | 3870| ------- | --------------------------------------- | 3871| boolean | Whether the current web page can be scrolled. The default value is **false**.| 3872 3873**Error codes** 3874 3875For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3876 3877| ID| Error Message | 3878| -------- | ------------------------------------------------------------ | 3879| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3880| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3881 3882> **NOTE** 3883> 3884> - If the web page is being touched, **false** is returned. Otherwise, **true** is returned. 3885> - If the rendering area at the same layer of the web page is being touched, **true** is returned. 3886> - Calling **scrollByWithResult** does not trigger the nested scrolling of the parent component. 3887> - This API does not support the high frame rate of scrolling performance. 3888 3889**Example** 3890 3891```ts 3892// xxx.ets 3893import { webview } from '@kit.ArkWeb'; 3894import { BusinessError } from '@kit.BasicServicesKit'; 3895 3896@Entry 3897@Component 3898struct WebComponent { 3899 controller: webview.WebviewController = new webview.WebviewController(); 3900 3901 build() { 3902 Column() { 3903 Button('scrollByWithResult') 3904 .onClick(() => { 3905 try { 3906 let result = this.controller.scrollByWithResult(50, 50); 3907 console.log("original result: " + result); 3908 } catch (error) { 3909 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3910 } 3911 }) 3912 Web({ src: $rawfile('index.html'), controller: this.controller }) 3913 } 3914 } 3915} 3916``` 3917 3918HTML file to be loaded: 3919```html 3920<!--index.html--> 3921<!DOCTYPE html> 3922<html> 3923<head> 3924 <title>Demo</title> 3925 <style> 3926 body { 3927 width:2000px; 3928 height:2000px; 3929 padding-right:170px; 3930 padding-left:170px; 3931 border:5px solid blueviolet 3932 } 3933 </style> 3934</head> 3935<body> 3936Scroll Test 3937</body> 3938</html> 3939``` 3940### slideScroll 3941 3942slideScroll(vx:number, vy:number): void 3943 3944Simulates a slide-to-scroll action on the page at the specified velocity. 3945 3946**System capability**: SystemCapability.Web.Webview.Core 3947 3948**Parameters** 3949 3950| Name| Type| Mandatory| Description | 3951| ------ | -------- | ---- | ---------------------- | 3952| vx | number | Yes | Horizontal velocity component of the slide-to-scroll action, where the positive direction is rightward. Unit: vp/ms.| 3953| vy | number | Yes | Vertical velocity component of the slide-to-scroll action, where the positive direction is downward. Unit: vp/ms.| 3954 3955**Error codes** 3956 3957For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 3958 3959| ID| Error Message | 3960| -------- | ------------------------------------------------------------ | 3961| 17100001 | Init error. The WebviewController must be associated with a Web component. | 3962| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3963 3964**Example** 3965 3966```ts 3967// xxx.ets 3968import { webview } from '@kit.ArkWeb'; 3969import { BusinessError } from '@kit.BasicServicesKit'; 3970 3971@Entry 3972@Component 3973struct WebComponent { 3974 controller: webview.WebviewController = new webview.WebviewController(); 3975 3976 build() { 3977 Column() { 3978 Button('slideScroll') 3979 .onClick(() => { 3980 try { 3981 this.controller.slideScroll(500, 500); 3982 } catch (error) { 3983 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3984 } 3985 }) 3986 Web({ src: $rawfile('index.html'), controller: this.controller }) 3987 } 3988 } 3989} 3990``` 3991 3992HTML file to be loaded: 3993```html 3994<!--index.html--> 3995<!DOCTYPE html> 3996<html> 3997<head> 3998 <title>Demo</title> 3999 <style> 4000 body { 4001 width:3000px; 4002 height:3000px; 4003 padding-right:170px; 4004 padding-left:170px; 4005 border:5px solid blueviolet 4006 } 4007 </style> 4008</head> 4009<body> 4010Scroll Test 4011</body> 4012</html> 4013``` 4014 4015### getOriginalUrl 4016 4017getOriginalUrl(): string 4018 4019Obtains the original URL of this page. 4020Risk warning: If you want to obtain the URL for JavaScriptProxy communication API authentication, use [getLastJavascriptProxyCallingFrameUrl<sup>12+</sup>](#getlastjavascriptproxycallingframeurl12). 4021 4022**System capability**: SystemCapability.Web.Webview.Core 4023 4024**Return value** 4025 4026| Type | Description | 4027| ------ | ----------------------- | 4028| string | Original URL of the current page.| 4029 4030**Error codes** 4031 4032For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4033 4034| ID| Error Message | 4035| -------- | ------------------------------------------------------------ | 4036| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4037 4038**Example** 4039 4040```ts 4041// xxx.ets 4042import { webview } from '@kit.ArkWeb'; 4043import { BusinessError } from '@kit.BasicServicesKit'; 4044 4045@Entry 4046@Component 4047struct WebComponent { 4048 controller: webview.WebviewController = new webview.WebviewController(); 4049 4050 build() { 4051 Column() { 4052 Button('getOrgUrl') 4053 .onClick(() => { 4054 try { 4055 let url = this.controller.getOriginalUrl(); 4056 console.log("original url: " + url); 4057 } catch (error) { 4058 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4059 } 4060 }) 4061 Web({ src: 'www.example.com', controller: this.controller }) 4062 } 4063 } 4064} 4065``` 4066 4067### getFavicon 4068 4069getFavicon(): image.PixelMap 4070 4071Obtains the favicon of this page. 4072 4073**System capability**: SystemCapability.Web.Webview.Core 4074 4075**Return value** 4076 4077| Type | Description | 4078| -------------------------------------- | ------------------------------- | 4079| [PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | **PixelMap** object of the favicon of the page.| 4080 4081**Error codes** 4082 4083For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4084 4085| ID| Error Message | 4086| -------- | ------------------------------------------------------------ | 4087| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4088 4089**Example** 4090 4091```ts 4092// xxx.ets 4093import { webview } from '@kit.ArkWeb'; 4094import { BusinessError } from '@kit.BasicServicesKit'; 4095import { image } from '@kit.ImageKit'; 4096 4097@Entry 4098@Component 4099struct WebComponent { 4100 controller: webview.WebviewController = new webview.WebviewController(); 4101 @State pixelmap: image.PixelMap | undefined = undefined; 4102 4103 build() { 4104 Column() { 4105 Button('getFavicon') 4106 .onClick(() => { 4107 try { 4108 this.pixelmap = this.controller.getFavicon(); 4109 } catch (error) { 4110 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4111 } 4112 }) 4113 Web({ src: 'www.example.com', controller: this.controller }) 4114 } 4115 } 4116} 4117``` 4118 4119### setNetworkAvailable 4120 4121setNetworkAvailable(enable: boolean): void 4122 4123Sets the **window.navigator.onLine** attribute in JavaScript. 4124 4125**System capability**: SystemCapability.Web.Webview.Core 4126 4127**Parameters** 4128 4129| Name| Type | Mandatory| Description | 4130| ------ | ------- | ---- | --------------------------------- | 4131| enable | boolean | Yes | Whether to enable **window.navigator.onLine**.| 4132 4133**Error codes** 4134 4135For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4136 4137| ID| Error Message | 4138| -------- | ------------------------------------------------------------ | 4139| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4140| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4141 4142**Example** 4143 4144```ts 4145// xxx.ets 4146import { webview } from '@kit.ArkWeb'; 4147import { BusinessError } from '@kit.BasicServicesKit'; 4148 4149@Entry 4150@Component 4151struct WebComponent { 4152 controller: webview.WebviewController = new webview.WebviewController(); 4153 4154 build() { 4155 Column() { 4156 Button('setNetworkAvailable') 4157 .onClick(() => { 4158 try { 4159 this.controller.setNetworkAvailable(true); 4160 } catch (error) { 4161 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4162 } 4163 }) 4164 Web({ src: $rawfile('index.html'), controller: this.controller }) 4165 } 4166 } 4167} 4168``` 4169 4170HTML file to be loaded: 4171```html 4172<!-- index.html --> 4173<!DOCTYPE html> 4174<html> 4175<body> 4176<h1>online attribute </h1> 4177<p id="demo"></p> 4178<button onclick="func()">click</button> 4179<script> 4180 let online = navigator.onLine; 4181 document.getElementById ("demo").innerHTML = "Browser online:" + online; 4182 4183 function func(){ 4184 var online = navigator.onLine; 4185 document.getElementById ("demo").innerHTML = "Browser online:" + online; 4186 } 4187</script> 4188</body> 4189</html> 4190``` 4191 4192### hasImage 4193 4194hasImage(callback: AsyncCallback\<boolean>): void 4195 4196Checks whether this page contains images. This API uses an asynchronous callback to return the result. 4197 4198**System capability**: SystemCapability.Web.Webview.Core 4199 4200**Parameters** 4201 4202| Name | Type | Mandatory| Description | 4203| -------- | ----------------------- | ---- | -------------------------- | 4204| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result.| 4205 4206**Error codes** 4207 4208For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4209 4210| ID| Error Message | 4211| -------- | ------------------------------------------------------------ | 4212| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4213| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4214 4215**Example** 4216 4217```ts 4218// xxx.ets 4219import { webview } from '@kit.ArkWeb'; 4220import { BusinessError } from '@kit.BasicServicesKit'; 4221 4222@Entry 4223@Component 4224struct WebComponent { 4225 controller: webview.WebviewController = new webview.WebviewController(); 4226 4227 build() { 4228 Column() { 4229 Button('hasImageCb') 4230 .onClick(() => { 4231 try { 4232 this.controller.hasImage((error, data) => { 4233 if (error) { 4234 console.error(`hasImage error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4235 return; 4236 } 4237 console.info("hasImage: " + data); 4238 }); 4239 } catch (error) { 4240 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4241 } 4242 }) 4243 Web({ src: 'www.example.com', controller: this.controller }) 4244 } 4245 } 4246} 4247``` 4248 4249### hasImage 4250 4251hasImage(): Promise\<boolean> 4252 4253Checks whether this page contains images. This API uses a promise to return the result. 4254 4255**System capability**: SystemCapability.Web.Webview.Core 4256 4257**Return value** 4258 4259| Type | Description | 4260| ----------------- | --------------------------------------- | 4261| Promise\<boolean> | Promise used to return the result.| 4262 4263**Error codes** 4264 4265For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4266 4267| ID| Error Message | 4268| -------- | ------------------------------------------------------------ | 4269| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4270| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 4271 4272**Example** 4273 4274```ts 4275// xxx.ets 4276import { webview } from '@kit.ArkWeb'; 4277import { BusinessError } from '@kit.BasicServicesKit'; 4278 4279@Entry 4280@Component 4281struct WebComponent { 4282 controller: webview.WebviewController = new webview.WebviewController(); 4283 4284 build() { 4285 Column() { 4286 Button('hasImagePm') 4287 .onClick(() => { 4288 try { 4289 this.controller.hasImage().then((data) => { 4290 console.info('hasImage: ' + data); 4291 }).catch((error: BusinessError) => { 4292 console.error("error: " + error); 4293 }) 4294 } catch (error) { 4295 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4296 } 4297 }) 4298 Web({ src: 'www.example.com', controller: this.controller }) 4299 } 4300 } 4301} 4302``` 4303 4304### removeCache 4305 4306removeCache(clearRom: boolean): void 4307 4308Clears the cache in the application. This API will clear the cache for all webviews in the same application. 4309 4310> **NOTE** 4311> 4312> You can view the Webview cache in the **data/storage/el2/base/cache/web/Cache** directory. 4313 4314**System capability**: SystemCapability.Web.Webview.Core 4315 4316**Parameters** 4317 4318| Name | Type | Mandatory| Description | 4319| -------- | ------- | ---- | -------------------------------------------------------- | 4320| 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.| 4321 4322**Error codes** 4323 4324For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4325 4326| ID| Error Message | 4327| -------- | ------------------------------------------------------------ | 4328| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4329| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4330 4331**Example** 4332 4333```ts 4334// xxx.ets 4335import { webview } from '@kit.ArkWeb'; 4336import { BusinessError } from '@kit.BasicServicesKit'; 4337 4338@Entry 4339@Component 4340struct WebComponent { 4341 controller: webview.WebviewController = new webview.WebviewController(); 4342 4343 build() { 4344 Column() { 4345 Button('removeCache') 4346 .onClick(() => { 4347 try { 4348 this.controller.removeCache(false); 4349 } catch (error) { 4350 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4351 } 4352 }) 4353 Web({ src: 'www.example.com', controller: this.controller }) 4354 } 4355 } 4356} 4357``` 4358 4359### pageUp 4360 4361pageUp(top: boolean): void 4362 4363Scrolls the page up by half the viewport or jumps to the top of the page. 4364 4365**System capability**: SystemCapability.Web.Webview.Core 4366 4367**Parameters** 4368 4369| Name| Type | Mandatory| Description | 4370| ------ | ------- | ---- | ------------------------------------------------------------ | 4371| 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.| 4372 4373**Error codes** 4374 4375For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4376 4377| ID| Error Message | 4378| -------- | ------------------------------------------------------------ | 4379| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4380| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4381 4382**Example** 4383 4384```ts 4385// xxx.ets 4386import { webview } from '@kit.ArkWeb'; 4387import { BusinessError } from '@kit.BasicServicesKit'; 4388 4389@Entry 4390@Component 4391struct WebComponent { 4392 controller: webview.WebviewController = new webview.WebviewController(); 4393 4394 build() { 4395 Column() { 4396 Button('pageUp') 4397 .onClick(() => { 4398 try { 4399 this.controller.pageUp(false); 4400 } catch (error) { 4401 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4402 } 4403 }) 4404 Web({ src: 'www.example.com', controller: this.controller }) 4405 } 4406 } 4407} 4408``` 4409 4410### pageDown 4411 4412pageDown(bottom: boolean): void 4413 4414Scrolls the page down by half the viewport or jumps to the bottom of the page. 4415 4416**System capability**: SystemCapability.Web.Webview.Core 4417 4418**Parameters** 4419 4420| Name| Type | Mandatory| Description | 4421| ------ | ------- | ---- | ------------------------------------------------------------ | 4422| 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.| 4423 4424**Error codes** 4425 4426For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4427 4428| ID| Error Message | 4429| -------- | ------------------------------------------------------------ | 4430| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4431| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4432 4433**Example** 4434 4435```ts 4436// xxx.ets 4437import { webview } from '@kit.ArkWeb'; 4438import { BusinessError } from '@kit.BasicServicesKit'; 4439 4440@Entry 4441@Component 4442struct WebComponent { 4443 controller: webview.WebviewController = new webview.WebviewController(); 4444 4445 build() { 4446 Column() { 4447 Button('pageDown') 4448 .onClick(() => { 4449 try { 4450 this.controller.pageDown(false); 4451 } catch (error) { 4452 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4453 } 4454 }) 4455 Web({ src: 'www.example.com', controller: this.controller }) 4456 } 4457 } 4458} 4459``` 4460 4461### getBackForwardEntries 4462 4463getBackForwardEntries(): BackForwardList 4464 4465Obtains the historical information list of the current webview. 4466 4467**System capability**: SystemCapability.Web.Webview.Core 4468 4469**Return value** 4470 4471| Type | Description | 4472| ----------------------------------- | --------------------------- | 4473| [BackForwardList](#backforwardlist) | The historical information list of the current webview.| 4474 4475**Error codes** 4476 4477For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4478 4479| ID| Error Message | 4480| -------- | ------------------------------------------------------------ | 4481| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4482 4483**Example** 4484 4485```ts 4486// xxx.ets 4487import { webview } from '@kit.ArkWeb'; 4488import { BusinessError } from '@kit.BasicServicesKit'; 4489 4490@Entry 4491@Component 4492struct WebComponent { 4493 controller: webview.WebviewController = new webview.WebviewController(); 4494 4495 build() { 4496 Column() { 4497 Button('getBackForwardEntries') 4498 .onClick(() => { 4499 try { 4500 let list = this.controller.getBackForwardEntries() 4501 } catch (error) { 4502 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4503 } 4504 }) 4505 Web({ src: 'www.example.com', controller: this.controller }) 4506 } 4507 } 4508} 4509``` 4510 4511### serializeWebState 4512 4513serializeWebState(): Uint8Array 4514 4515Serializes the page status history of the current Webview. 4516 4517**System capability**: SystemCapability.Web.Webview.Core 4518 4519**Return value** 4520 4521| Type | Description | 4522| ---------- | --------------------------------------------- | 4523| Uint8Array | Serialized data of the page status history of the current WebView.| 4524 4525**Error codes** 4526 4527For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4528 4529| ID| Error Message | 4530| -------- | ------------------------------------------------------------ | 4531| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4532 4533**Example** 4534 45351. 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). 4536```ts 4537// xxx.ets 4538import { webview } from '@kit.ArkWeb'; 4539import { BusinessError } from '@kit.BasicServicesKit'; 4540import { fileIo } from '@kit.CoreFileKit'; 4541 4542@Entry 4543@Component 4544struct WebComponent { 4545 controller: webview.WebviewController = new webview.WebviewController(); 4546 4547 build() { 4548 Column() { 4549 Button('serializeWebState') 4550 .onClick(() => { 4551 try { 4552 let state = this.controller.serializeWebState(); 4553 let path:string | undefined = AppStorage.get("cacheDir"); 4554 if (path) { 4555 path += '/WebState'; 4556 // Synchronously open a file. 4557 let file = fileIo.openSync(path, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); 4558 fileIo.writeSync(file.fd, state.buffer); 4559 fileIo.closeSync(file.fd); 4560 } 4561 } catch (error) { 4562 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4563 } 4564 }) 4565 Web({ src: 'www.example.com', controller: this.controller }) 4566 } 4567 } 4568} 4569``` 4570 45712. Modify the **EntryAbility.ets** file. 4572Obtain the path of the application cache file. 4573```ts 4574// xxx.ets 4575import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 4576 4577export default class EntryAbility extends UIAbility { 4578 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 4579 // Data synchronization between the UIAbility component and the page can be implemented by binding cacheDir to the AppStorage object. 4580 AppStorage.setOrCreate("cacheDir", this.context.cacheDir); 4581 } 4582} 4583``` 4584 4585### restoreWebState 4586 4587restoreWebState(state: Uint8Array): void 4588 4589Restores the page status history from the serialized data of the current WebView. 4590 4591If 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. 4592 4593**System capability**: SystemCapability.Web.Webview.Core 4594 4595**Parameters** 4596 4597| Name| Type | Mandatory| Description | 4598| ------ | ---------- | ---- | ---------------------------- | 4599| state | Uint8Array | Yes | Serialized data of the page status history.| 4600 4601**Error codes** 4602 4603For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4604 4605| ID| Error Message | 4606| -------- | ------------------------------------------------------------ | 4607| 17100001 | Init error. The WebviewController must be associated with a Web component. | 4608| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 4609 4610**Example** 4611 46121. 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). 4613```ts 4614// xxx.ets 4615import { webview } from '@kit.ArkWeb'; 4616import { BusinessError } from '@kit.BasicServicesKit'; 4617import { fileIo } from '@kit.CoreFileKit'; 4618 4619@Entry 4620@Component 4621struct WebComponent { 4622 controller: webview.WebviewController = new webview.WebviewController(); 4623 4624 build() { 4625 Column() { 4626 Button('RestoreWebState') 4627 .onClick(() => { 4628 try { 4629 let path: string | undefined = AppStorage.get("cacheDir"); 4630 if (path) { 4631 path += '/WebState'; 4632 // Synchronously open a file. 4633 let file = fileIo.openSync(path, fileIo.OpenMode.READ_WRITE); 4634 let stat = fileIo.statSync(path); 4635 let size = stat.size; 4636 let buf = new ArrayBuffer(size); 4637 fileIo.read(file.fd, buf, (err, readLen) => { 4638 if (err) { 4639 console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); 4640 } else { 4641 console.info("read file data succeed"); 4642 this.controller.restoreWebState(new Uint8Array(buf.slice(0, readLen))); 4643 fileIo.closeSync(file); 4644 } 4645 }); 4646 } 4647 } catch (error) { 4648 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4649 } 4650 }) 4651 Web({ src: 'www.example.com', controller: this.controller }) 4652 } 4653 } 4654} 4655``` 4656 46572. Modify the **EntryAbility.ets** file. 4658Obtain the path of the application cache file. 4659```ts 4660// xxx.ets 4661import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 4662 4663export default class EntryAbility extends UIAbility { 4664 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 4665 // Data synchronization between the UIAbility component and the page can be implemented by binding cacheDir to the AppStorage object. 4666 AppStorage.setOrCreate("cacheDir", this.context.cacheDir); 4667 } 4668} 4669``` 4670 4671### customizeSchemes 4672 4673static customizeSchemes(schemes: Array\<WebCustomScheme\>): void 4674 4675Grants 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. 4676 4677**System capability**: SystemCapability.Web.Webview.Core 4678 4679**Parameters** 4680 4681| Name | Type | Mandatory| Description | 4682| -------- | ------- | ---- | -------------------------------------- | 4683| schemes | Array\<[WebCustomScheme](#webcustomscheme)\> | Yes | Array of up to 10 custom schemes.| 4684 4685**Error codes** 4686 4687For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4688 4689| ID| Error Message | 4690| -------- | ------------------------------------------------------------ | 4691| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 4692| 17100020 | Failed to register custom schemes. | 4693 4694**Example** 4695 4696```ts 4697// xxx.ets 4698import { webview } from '@kit.ArkWeb'; 4699import { BusinessError } from '@kit.BasicServicesKit'; 4700 4701@Entry 4702@Component 4703struct WebComponent { 4704 controller: webview.WebviewController = new webview.WebviewController(); 4705 responseWeb: WebResourceResponse = new WebResourceResponse(); 4706 scheme1: webview.WebCustomScheme = { schemeName: "name1", isSupportCORS: true, isSupportFetch: true }; 4707 scheme2: webview.WebCustomScheme = { schemeName: "name2", isSupportCORS: true, isSupportFetch: true }; 4708 scheme3: webview.WebCustomScheme = { schemeName: "name3", isSupportCORS: true, isSupportFetch: true }; 4709 4710 aboutToAppear(): void { 4711 try { 4712 webview.WebviewController.customizeSchemes([this.scheme1, this.scheme2, this.scheme3]); 4713 } catch (error) { 4714 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 4715 } 4716 } 4717 4718 build() { 4719 Column() { 4720 Web({ src: 'www.example.com', controller: this.controller }) 4721 .onInterceptRequest((event) => { 4722 if (event) { 4723 console.log('url:' + event.request.getRequestUrl()); 4724 } 4725 return this.responseWeb; 4726 }) 4727 } 4728 } 4729} 4730``` 4731 4732### getCertificate<sup>10+</sup> 4733 4734getCertificate(): Promise<Array<cert.X509Cert>> 4735 4736Obtains 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. 4737 4738**System capability**: SystemCapability.Web.Webview.Core 4739 4740**Return value** 4741 4742| Type | Description | 4743| ---------- | --------------------------------------------- | 4744| Promise<Array<cert.X509Cert>> | Promise used to obtain the X.509 certificate array of the current HTTPS website.| 4745 4746**Error codes** 4747 4748For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4749 4750| ID| Error Message | 4751| -------- | ------------------------------------------------------------ | 4752| 17100001 | Init error. The WebviewController must be associated with a web component. | 4753 4754**Example** 4755 4756```ts 4757// xxx.ets 4758import { webview } from '@kit.ArkWeb'; 4759import { BusinessError } from '@kit.BasicServicesKit'; 4760import { cert } from '@kit.DeviceCertificateKit'; 4761 4762function Uint8ArrayToString(dataArray: Uint8Array) { 4763 let dataString = ''; 4764 for (let i = 0; i < dataArray.length; i++) { 4765 dataString += String.fromCharCode(dataArray[i]); 4766 } 4767 return dataString; 4768} 4769 4770function ParseX509CertInfo(x509CertArray: Array<cert.X509Cert>) { 4771 let res: string = 'getCertificate success: len = ' + x509CertArray.length; 4772 for (let i = 0; i < x509CertArray.length; i++) { 4773 res += ', index = ' + i + ', issuer name = ' 4774 + Uint8ArrayToString(x509CertArray[i].getIssuerName().data) + ', subject name = ' 4775 + Uint8ArrayToString(x509CertArray[i].getSubjectName().data) + ', valid start = ' 4776 + x509CertArray[i].getNotBeforeTime() 4777 + ', valid end = ' + x509CertArray[i].getNotAfterTime(); 4778 } 4779 return res; 4780} 4781 4782@Entry 4783@Component 4784struct Index { 4785 // outputStr displays debug information on the UI. 4786 @State outputStr: string = ''; 4787 webviewCtl: webview.WebviewController = new webview.WebviewController(); 4788 4789 build() { 4790 Row() { 4791 Column() { 4792 List({ space: 20, initialIndex: 0 }) { 4793 ListItem() { 4794 Button() { 4795 Text('load bad ssl') 4796 .fontSize(10) 4797 .fontWeight(FontWeight.Bold) 4798 } 4799 .type(ButtonType.Capsule) 4800 .onClick(() => { 4801 // Load an expired certificate website and view the obtained certificate information. 4802 this.webviewCtl.loadUrl('https://expired.badssl.com'); 4803 }) 4804 .height(50) 4805 } 4806 4807 ListItem() { 4808 Button() { 4809 Text('load example') 4810 .fontSize(10) 4811 .fontWeight(FontWeight.Bold) 4812 } 4813 .type(ButtonType.Capsule) 4814 .onClick(() => { 4815 // Load an HTTPS website and view the certificate information of the website. 4816 this.webviewCtl.loadUrl('https://www.example.com'); 4817 }) 4818 .height(50) 4819 } 4820 4821 ListItem() { 4822 Button() { 4823 Text('getCertificate Promise') 4824 .fontSize(10) 4825 .fontWeight(FontWeight.Bold) 4826 } 4827 .type(ButtonType.Capsule) 4828 .onClick(() => { 4829 try { 4830 this.webviewCtl.getCertificate().then((x509CertArray: Array<cert.X509Cert>) => { 4831 this.outputStr = ParseX509CertInfo(x509CertArray); 4832 }) 4833 } catch (error) { 4834 this.outputStr = 'getCertificate failed: ' + (error as BusinessError).code + ", errMsg: " + (error as BusinessError).message; 4835 } 4836 }) 4837 .height(50) 4838 } 4839 4840 ListItem() { 4841 Button() { 4842 Text('getCertificate AsyncCallback') 4843 .fontSize(10) 4844 .fontWeight(FontWeight.Bold) 4845 } 4846 .type(ButtonType.Capsule) 4847 .onClick(() => { 4848 try { 4849 this.webviewCtl.getCertificate((error: BusinessError, x509CertArray: Array<cert.X509Cert>) => { 4850 if (error) { 4851 this.outputStr = 'getCertificate failed: ' + error.code + ", errMsg: " + error.message; 4852 } else { 4853 this.outputStr = ParseX509CertInfo(x509CertArray); 4854 } 4855 }) 4856 } catch (error) { 4857 this.outputStr = 'getCertificate failed: ' + (error as BusinessError).code + ", errMsg: " + (error as BusinessError).message; 4858 } 4859 }) 4860 .height(50) 4861 } 4862 } 4863 .listDirection(Axis.Horizontal) 4864 .height('10%') 4865 4866 Text(this.outputStr) 4867 .width('100%') 4868 .fontSize(10) 4869 4870 Web({ src: 'https://www.example.com', controller: this.webviewCtl }) 4871 .fileAccess(true) 4872 .javaScriptAccess(true) 4873 .domStorageAccess(true) 4874 .onlineImageAccess(true) 4875 .onPageEnd((e) => { 4876 if (e) { 4877 this.outputStr = 'onPageEnd : url = ' + e.url; 4878 } 4879 }) 4880 .onSslErrorEventReceive((e) => { 4881 // Ignore SSL certificate errors to test websites whose certificates have expired, for example, https://expired.badssl.com. 4882 e.handler.handleConfirm(); 4883 }) 4884 .width('100%') 4885 .height('70%') 4886 } 4887 .height('100%') 4888 } 4889 } 4890} 4891``` 4892 4893### getCertificate<sup>10+</sup> 4894 4895getCertificate(callback: AsyncCallback<Array<cert.X509Cert>>): void 4896 4897Obtains 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. 4898 4899**System capability**: SystemCapability.Web.Webview.Core 4900 4901**Parameters** 4902 4903| Name | Type | Mandatory| Description | 4904| -------- | ---------------------------- | ---- | ---------------------------------------- | 4905| callback | AsyncCallback<Array<cert.X509Cert>> | Yes | Callback used to obtain the X.509 certificate array of the current website.| 4906 4907**Error codes** 4908 4909For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 4910 4911| ID| Error Message | 4912| -------- | ------------------------------------------------------------ | 4913| 17100001 | Init error. The WebviewController must be associated with a web component. | 4914| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 4915 4916**Example** 4917 4918```ts 4919// xxx.ets 4920import { webview } from '@kit.ArkWeb'; 4921import { BusinessError } from '@kit.BasicServicesKit'; 4922import { cert } from '@kit.DeviceCertificateKit'; 4923 4924function Uint8ArrayToString(dataArray: Uint8Array) { 4925 let dataString = ''; 4926 for (let i = 0; i < dataArray.length; i++) { 4927 dataString += String.fromCharCode(dataArray[i]); 4928 } 4929 return dataString; 4930} 4931 4932function ParseX509CertInfo(x509CertArray: Array<cert.X509Cert>) { 4933 let res: string = 'getCertificate success: len = ' + x509CertArray.length; 4934 for (let i = 0; i < x509CertArray.length; i++) { 4935 res += ', index = ' + i + ', issuer name = ' 4936 + Uint8ArrayToString(x509CertArray[i].getIssuerName().data) + ', subject name = ' 4937 + Uint8ArrayToString(x509CertArray[i].getSubjectName().data) + ', valid start = ' 4938 + x509CertArray[i].getNotBeforeTime() 4939 + ', valid end = ' + x509CertArray[i].getNotAfterTime(); 4940 } 4941 return res; 4942} 4943 4944@Entry 4945@Component 4946struct Index { 4947 // outputStr displays debug information on the UI. 4948 @State outputStr: string = ''; 4949 webviewCtl: webview.WebviewController = new webview.WebviewController(); 4950 4951 build() { 4952 Row() { 4953 Column() { 4954 List({ space: 20, initialIndex: 0 }) { 4955 ListItem() { 4956 Button() { 4957 Text('load bad ssl') 4958 .fontSize(10) 4959 .fontWeight(FontWeight.Bold) 4960 } 4961 .type(ButtonType.Capsule) 4962 .onClick(() => { 4963 // Load an expired certificate website and view the obtained certificate information. 4964 this.webviewCtl.loadUrl('https://expired.badssl.com'); 4965 }) 4966 .height(50) 4967 } 4968 4969 ListItem() { 4970 Button() { 4971 Text('load example') 4972 .fontSize(10) 4973 .fontWeight(FontWeight.Bold) 4974 } 4975 .type(ButtonType.Capsule) 4976 .onClick(() => { 4977 // Load an HTTPS website and view the certificate information of the website. 4978 this.webviewCtl.loadUrl('https://www.example.com'); 4979 }) 4980 .height(50) 4981 } 4982 4983 ListItem() { 4984 Button() { 4985 Text('getCertificate Promise') 4986 .fontSize(10) 4987 .fontWeight(FontWeight.Bold) 4988 } 4989 .type(ButtonType.Capsule) 4990 .onClick(() => { 4991 try { 4992 this.webviewCtl.getCertificate().then((x509CertArray: Array<cert.X509Cert>) => { 4993 this.outputStr = ParseX509CertInfo(x509CertArray); 4994 }) 4995 } catch (error) { 4996 this.outputStr = 'getCertificate failed: ' + (error as BusinessError).code + ", errMsg: " + (error as BusinessError).message; 4997 } 4998 }) 4999 .height(50) 5000 } 5001 5002 ListItem() { 5003 Button() { 5004 Text('getCertificate AsyncCallback') 5005 .fontSize(10) 5006 .fontWeight(FontWeight.Bold) 5007 } 5008 .type(ButtonType.Capsule) 5009 .onClick(() => { 5010 try { 5011 this.webviewCtl.getCertificate((error: BusinessError, x509CertArray: Array<cert.X509Cert>) => { 5012 if (error) { 5013 this.outputStr = 'getCertificate failed: ' + error.code + ", errMsg: " + error.message; 5014 } else { 5015 this.outputStr = ParseX509CertInfo(x509CertArray); 5016 } 5017 }) 5018 } catch (error) { 5019 this.outputStr = 'getCertificate failed: ' + (error as BusinessError).code + ", errMsg: " + (error as BusinessError).message; 5020 } 5021 }) 5022 .height(50) 5023 } 5024 } 5025 .listDirection(Axis.Horizontal) 5026 .height('10%') 5027 5028 Text(this.outputStr) 5029 .width('100%') 5030 .fontSize(10) 5031 5032 Web({ src: 'https://www.example.com', controller: this.webviewCtl }) 5033 .fileAccess(true) 5034 .javaScriptAccess(true) 5035 .domStorageAccess(true) 5036 .onlineImageAccess(true) 5037 .onPageEnd((e) => { 5038 if (e) { 5039 this.outputStr = 'onPageEnd : url = ' + e.url; 5040 } 5041 }) 5042 .onSslErrorEventReceive((e) => { 5043 // Ignore SSL certificate errors to test websites whose certificates have expired, for example, https://expired.badssl.com. 5044 e.handler.handleConfirm(); 5045 }) 5046 .width('100%') 5047 .height('70%') 5048 } 5049 .height('100%') 5050 } 5051 } 5052} 5053``` 5054 5055### setAudioMuted<sup>10+</sup> 5056 5057setAudioMuted(mute: boolean): void 5058 5059Mutes this web page. 5060 5061**System capability**: SystemCapability.Web.Webview.Core 5062 5063**Parameters** 5064 5065| Name | Type | Mandatory| Description | 5066| -------- | ------- | ---- | -------------------------------------- | 5067| mute | boolean | Yes | Whether to mute the web page. The value **true** means to mute the web page, and **false** means the opposite.| 5068 5069**Error codes** 5070 5071For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5072 5073| ID| Error Message | 5074| -------- | ------------------------------------------------------------ | 5075| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5076| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5077 5078**Example** 5079 5080```ts 5081// xxx.ets 5082import { webview } from '@kit.ArkWeb'; 5083 5084@Entry 5085@Component 5086struct WebComponent { 5087 controller: webview.WebviewController = new webview.WebviewController(); 5088 @State muted: boolean = false; 5089 5090 build() { 5091 Column() { 5092 Button("Toggle Mute") 5093 .onClick(event => { 5094 if (event) { 5095 this.muted = !this.muted; 5096 this.controller.setAudioMuted(this.muted); 5097 } 5098 }) 5099 Web({ src: 'www.example.com', controller: this.controller }) 5100 } 5101 } 5102} 5103``` 5104 5105### prefetchPage<sup>10+</sup> 5106 5107prefetchPage(url: string, additionalHeaders?: Array\<WebHeader>): void 5108 5109Prefetches 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. 5110 5111> **NOTE** 5112> 5113> The downloaded page resources are cached for about 5 minutes. After this period, the **Web** component automatically releases the resources. 5114 5115**System capability**: SystemCapability.Web.Webview.Core 5116 5117**Parameters** 5118 5119| Name | Type | Mandatory | Description | 5120| ------------------| --------------------------------| ---- | ------------- | 5121| url | string | Yes | URL to be preloaded.| 5122| additionalHeaders | Array\<[WebHeader](#webheader)> | No | Additional HTTP headers of the URL.| 5123 5124**Error codes** 5125 5126For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5127 5128| ID | Error Message | 5129| -------- | ------------------------------------------------------------ | 5130| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5131| 17100002 | Invalid url. | 5132 5133**Example** 5134 5135```ts 5136// xxx.ets 5137import { webview } from '@kit.ArkWeb'; 5138import { BusinessError } from '@kit.BasicServicesKit'; 5139 5140@Entry 5141@Component 5142struct WebComponent { 5143 controller: webview.WebviewController = new webview.WebviewController(); 5144 5145 build() { 5146 Column() { 5147 Button('prefetchPopularPage') 5148 .onClick(() => { 5149 try { 5150 // Replace 'https://www.example.com' with a real URL for the API to work. 5151 this.controller.prefetchPage('https://www.example.com'); 5152 } catch (error) { 5153 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5154 } 5155 }) 5156 // Replace ''www.example1.com' with a real URL for the API to work. 5157 Web({ src: 'www.example1.com', controller: this.controller }) 5158 } 5159 } 5160} 5161``` 5162 5163### prefetchResource<sup>12+</sup> 5164 5165static prefetchResource(request: RequestInfo, additionalHeaders?: Array\<WebHeader>, cacheKey?: string, cacheValidTime?: number): void 5166 5167Prefetches 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. 5168 5169**System capability**: SystemCapability.Web.Webview.Core 5170 5171**Parameters** 5172 5173| Name | Type | Mandatory | Description | 5174| ------------------| ------------------------------- | ---- | ------------------------------------------------------------------ | 5175| request | [RequestInfo](#requestinfo12) | Yes | Information about the prefetched request. | 5176| additionalHeaders | Array\<[WebHeader](#webheader)> | No | Additional HTTP request header of the prefetched request. | 5177| 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.| 5178| cacheValidTime | number | No | Validity period for caching prefetched resources. Value range: (0, 2147483647] Unit: second. Default value: **300s** | 5179 5180**Error codes** 5181 5182For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5183 5184| ID | Error Message | 5185| -------- | ------------------------------------------------------------ | 5186| 401 | Invalid input parameter.Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | 5187| 17100002 | Invalid url. | 5188 5189**Example** 5190 5191```ts 5192// xxx.ets 5193import { webview } from '@kit.ArkWeb'; 5194import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 5195 5196export default class EntryAbility extends UIAbility { 5197 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 5198 console.log("EntryAbility onCreate"); 5199 webview.WebviewController.initializeWebEngine(); 5200 // Replace "https://www.example1.com/post?e=f&g=h" with the actual website address to visit. 5201 webview.WebviewController.prefetchResource( 5202 {url:"https://www.example1.com/post?e=f&g=h", 5203 method:"POST", 5204 formData:"a=x&b=y",}, 5205 [{headerKey:"c", 5206 headerValue:"z",},], 5207 "KeyX", 500); 5208 AppStorage.setOrCreate("abilityWant", want); 5209 console.log("EntryAbility onCreate done"); 5210 } 5211} 5212``` 5213 5214### clearPrefetchedResource<sup>12+</sup> 5215 5216static clearPrefetchedResource(cacheKeyList: Array\<string>): void 5217 5218Clears 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). 5219 5220**System capability**: SystemCapability.Web.Webview.Core 5221 5222**Parameters** 5223 5224| Name | Type | Mandatory | Description | 5225| ------------------| ----------- | ---- | ------------------------------------------------------------------------- | 5226| 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.| 5227 5228**Example** 5229 5230```ts 5231// xxx.ets 5232import { webview } from '@kit.ArkWeb'; 5233 5234@Entry 5235@Component 5236struct WebComponent { 5237 controller: webview.WebviewController = new webview.WebviewController(); 5238 build() { 5239 Column() { 5240 Web({ src: "https://www.example.com/", controller: this.controller}) 5241 .onAppear(() => { 5242 // Replace "https://www.example1.com/post?e=f&g=h" with the actual website address to visit. 5243 webview.WebviewController.prefetchResource( 5244 {url:"https://www.example1.com/post?e=f&g=h", 5245 method:"POST", 5246 formData:"a=x&b=y",}, 5247 [{headerKey:"c", 5248 headerValue:"z",},], 5249 "KeyX", 500); 5250 }) 5251 .onPageEnd(() => { 5252 // Clear the prefetch cache that is no longer used. 5253 webview.WebviewController.clearPrefetchedResource(["KeyX",]); 5254 }) 5255 } 5256 } 5257} 5258``` 5259 5260### prepareForPageLoad<sup>10+</sup> 5261 5262static prepareForPageLoad(url: string, preconnectable: boolean, numSockets: number): void 5263 5264Preconnects 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. 5265 5266**System capability**: SystemCapability.Web.Webview.Core 5267 5268**Parameters** 5269 5270| Name | Type | Mandatory | Description | 5271| ---------------| ------- | ---- | ------------- | 5272| url | string | Yes | URL to be preconnected.| 5273| 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.| 5274| numSockets | number | Yes | Number of sockets to be preconnected. The value must be greater than 0. A maximum of six socket connections are allowed.| 5275 5276**Error codes** 5277 5278For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5279 5280| ID | Error Message | 5281| -------- | ------------------------------------------------------------ | 5282| 17100002 | Invalid url. | 5283| 171000013| The number of preconnect sockets is invalid. | 5284 5285**Example** 5286 5287```ts 5288// xxx.ets 5289import { webview } from '@kit.ArkWeb'; 5290import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 5291 5292export default class EntryAbility extends UIAbility { 5293 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 5294 console.log("EntryAbility onCreate"); 5295 webview.WebviewController.initializeWebEngine(); 5296 // Replace 'https://www.example.com' with a real URL for the API to work. 5297 webview.WebviewController.prepareForPageLoad("https://www.example.com", true, 2); 5298 AppStorage.setOrCreate("abilityWant", want); 5299 console.log("EntryAbility onCreate done"); 5300 } 5301} 5302``` 5303 5304### setCustomUserAgent<sup>10+</sup> 5305 5306setCustomUserAgent(userAgent: string): void 5307 5308Sets a custom user agent, which will overwrite the default user agent. 5309 5310When 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. 5311 5312When **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. 5313 5314For details about the default **UserAgent**, see [Default User Agent String](../../web/web-default-userAgent.md). 5315 5316> **NOTE** 5317> 5318>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. 5319 5320**System capability**: SystemCapability.Web.Webview.Core 5321 5322**Parameters** 5323 5324| Name | Type | Mandatory | Description | 5325| ---------------| ------- | ---- | ------------- | 5326| 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.| 5327 5328**Error codes** 5329 5330For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5331 5332| ID | Error Message | 5333| -------- | ------------------------------------------------------------ | 5334| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5335| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5336 5337**Example** 5338 5339```ts 5340// xxx.ets 5341import { webview } from '@kit.ArkWeb'; 5342import { BusinessError } from '@kit.BasicServicesKit'; 5343 5344@Entry 5345@Component 5346struct WebComponent { 5347 controller: webview.WebviewController = new webview.WebviewController(); 5348 @State customUserAgent: string = ' DemoApp'; 5349 5350 build() { 5351 Column() { 5352 Web({ src: 'www.example.com', controller: this.controller }) 5353 .onControllerAttached(() => { 5354 console.log("onControllerAttached"); 5355 try { 5356 let userAgent = this.controller.getUserAgent() + this.customUserAgent; 5357 this.controller.setCustomUserAgent(userAgent); 5358 } catch (error) { 5359 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5360 } 5361 }) 5362 } 5363 } 5364} 5365``` 5366 5367### setDownloadDelegate<sup>11+</sup> 5368 5369setDownloadDelegate(delegate: WebDownloadDelegate): void 5370 5371Sets a **WebDownloadDelegate** object to receive downloads and download progress triggered from a page. 5372 5373**System capability**: SystemCapability.Web.Webview.Core 5374 5375**Parameters** 5376 5377| Name | Type | Mandatory | Description | 5378| ---------------| ------- | ---- | ------------- | 5379| delegate | [WebDownloadDelegate](#webdownloaddelegate11) | Yes | Delegate used to receive the download progress.| 5380 5381**Error codes** 5382 5383For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5384 5385| ID | Error Message | 5386| -------- | ------------------------------------------------------------ | 5387| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5388 5389**Example** 5390 5391```ts 5392// xxx.ets 5393import { webview } from '@kit.ArkWeb'; 5394import { BusinessError } from '@kit.BasicServicesKit'; 5395 5396@Entry 5397@Component 5398struct WebComponent { 5399 controller: webview.WebviewController = new webview.WebviewController(); 5400 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 5401 5402 build() { 5403 Column() { 5404 Button('setDownloadDelegate') 5405 .onClick(() => { 5406 try { 5407 this.controller.setDownloadDelegate(this.delegate); 5408 } catch (error) { 5409 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5410 } 5411 }) 5412 Web({ src: 'www.example.com', controller: this.controller }) 5413 } 5414 } 5415} 5416``` 5417 5418### startDownload<sup>11+</sup> 5419 5420startDownload(url: string): void 5421 5422Downloads a file, such as an image, from the specified URL. 5423 5424**System capability**: SystemCapability.Web.Webview.Core 5425 5426**Parameters** 5427 5428| Name | Type | Mandatory | Description | 5429| ---------------| ------- | ---- | ------------- | 5430| url | string | Yes | Download URL.| 5431 5432**Error codes** 5433 5434For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5435 5436| ID | Error Message | 5437| -------- | ------------------------------------------------------------ | 5438| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5439| 17100002 | Invalid url. | 5440 5441**Example** 5442 5443```ts 5444// xxx.ets 5445import { webview } from '@kit.ArkWeb'; 5446import { BusinessError } from '@kit.BasicServicesKit'; 5447 5448@Entry 5449@Component 5450struct WebComponent { 5451 controller: webview.WebviewController = new webview.WebviewController(); 5452 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 5453 5454 build() { 5455 Column() { 5456 Button('setDownloadDelegate') 5457 .onClick(() => { 5458 try { 5459 this.controller.setDownloadDelegate(this.delegate); 5460 } catch (error) { 5461 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5462 } 5463 }) 5464 Button('startDownload') 5465 .onClick(() => { 5466 try { 5467 this.controller.startDownload('https://www.example.com'); 5468 } catch (error) { 5469 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5470 } 5471 }) 5472 Web({ src: 'www.example.com', controller: this.controller }) 5473 } 5474 } 5475} 5476``` 5477 5478### getCustomUserAgent<sup>10+</sup> 5479 5480getCustomUserAgent(): string 5481 5482Obtains a custom user agent. 5483 5484For details about the default **UserAgent**, see [Default User Agent String](../../web/web-default-userAgent.md). 5485 5486**System capability**: SystemCapability.Web.Webview.Core 5487 5488**Return value** 5489 5490| Type | Description | 5491| ------ | ------------------------- | 5492| string | Information about the custom user agent.| 5493 5494**Error codes** 5495 5496For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5497 5498| ID | Error Message | 5499| -------- | ------------------------------------------------------------ | 5500| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5501 5502**Example** 5503 5504```ts 5505// xxx.ets 5506import { webview } from '@kit.ArkWeb'; 5507import { BusinessError } from '@kit.BasicServicesKit'; 5508 5509@Entry 5510@Component 5511struct WebComponent { 5512 controller: webview.WebviewController = new webview.WebviewController(); 5513 @State userAgent: string = ''; 5514 5515 build() { 5516 Column() { 5517 Button('getCustomUserAgent') 5518 .onClick(() => { 5519 try { 5520 this.userAgent = this.controller.getCustomUserAgent(); 5521 console.log("userAgent: " + this.userAgent); 5522 } catch (error) { 5523 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5524 } 5525 }) 5526 Web({ src: 'www.example.com', controller: this.controller }) 5527 } 5528 } 5529} 5530``` 5531 5532### setConnectionTimeout<sup>11+</sup> 5533 5534static setConnectionTimeout(timeout: number): void 5535 5536Sets the network connection timeout. You can use the **onErrorReceive** method in the **Web** component to obtain the timeout error code. 5537 5538**System capability**: SystemCapability.Web.Webview.Core 5539 5540**Parameters** 5541 5542| Name | Type | Mandatory | Description | 5543| ---------------| ------- | ---- | ------------- | 5544| timeout | number | Yes | Socket connection timeout interval, in seconds. The value of socket must be an integer greater than 0.| 5545 5546**Error codes** 5547 5548For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5549 5550| ID| Error Message | 5551| -------- | ------------------------------------------------------------ | 5552| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 5553 5554**Example** 5555 5556```ts 5557// xxx.ets 5558import { webview } from '@kit.ArkWeb'; 5559import { BusinessError } from '@kit.BasicServicesKit'; 5560 5561@Entry 5562@Component 5563struct WebComponent { 5564 controller: webview.WebviewController = new webview.WebviewController(); 5565 5566 build() { 5567 Column() { 5568 Button('setConnectionTimeout') 5569 .onClick(() => { 5570 try { 5571 webview.WebviewController.setConnectionTimeout(5); 5572 console.log("setConnectionTimeout: 5s"); 5573 } catch (error) { 5574 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5575 } 5576 }) 5577 Web({ src: 'www.example.com', controller: this.controller }) 5578 .onErrorReceive((event) => { 5579 if (event) { 5580 console.log('getErrorInfo:' + event.error.getErrorInfo()); 5581 console.log('getErrorCode:' + event.error.getErrorCode()); 5582 } 5583 }) 5584 } 5585 } 5586} 5587``` 5588 5589### warmupServiceWorker<sup>12+</sup> 5590 5591static warmupServiceWorker(url: string): void 5592 5593Warms 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. 5594 5595**System capability**: SystemCapability.Web.Webview.Core 5596 5597**Parameters** 5598 5599| Name | Type | Mandatory | Description | 5600| ---------------| ------- | ---- | ------------- | 5601| url | string | Yes | URL of the ServiceWorker to warm up.| 5602 5603**Error codes** 5604 5605For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5606 5607| ID | Error Message | 5608| -------- | ------------------------------------------------------------ | 5609| 17100002 | Invalid url. | 5610 5611**Example** 5612 5613```ts 5614// xxx.ts 5615import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 5616import { hilog } from '@kit.PerformanceAnalysisKit'; 5617import { window } from '@kit.ArkUI'; 5618import { webview } from '@kit.ArkWeb'; 5619 5620export default class EntryAbility extends UIAbility { 5621 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 5622 console.log("EntryAbility onCreate"); 5623 webview.WebviewController.initializeWebEngine(); 5624 webview.WebviewController.warmupServiceWorker("https://www.example.com"); 5625 AppStorage.setOrCreate("abilityWant", want); 5626 } 5627} 5628``` 5629 5630### enableSafeBrowsing<sup>11+</sup> 5631 5632enableSafeBrowsing(enable: boolean): void 5633 5634<!--RP1-->Enables the safe browsing feature. This feature is forcibly enabled and cannot be disabled for identified untrusted websites. 5635By 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. 5636<!--RP1End--> 5637 5638**System capability**: SystemCapability.Web.Webview.Core 5639 5640**Parameters** 5641 5642| Name | Type | Mandatory | Description | 5643| --------| ------- | ---- | ---------------------------| 5644| enable | boolean | Yes | Whether to enable the safe browsing feature.| 5645 5646**Error codes** 5647 5648For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5649 5650| ID| Error Message | 5651| -------- | ----------------------- | 5652| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5653 5654**Example** 5655 5656```ts 5657// xxx.ets 5658import { webview } from '@kit.ArkWeb'; 5659import { BusinessError } from '@kit.BasicServicesKit'; 5660 5661@Entry 5662@Component 5663struct WebComponent { 5664 controller: webview.WebviewController = new webview.WebviewController(); 5665 5666 build() { 5667 Column() { 5668 Button('enableSafeBrowsing') 5669 .onClick(() => { 5670 try { 5671 this.controller.enableSafeBrowsing(true); 5672 console.log("enableSafeBrowsing: true"); 5673 } catch (error) { 5674 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5675 } 5676 }) 5677 Web({ src: 'www.example.com', controller: this.controller }) 5678 } 5679 } 5680} 5681``` 5682 5683### isSafeBrowsingEnabled<sup>11+</sup> 5684 5685isSafeBrowsingEnabled(): boolean 5686 5687Checks whether the safe browsing feature is enabled for this web page. 5688 5689**System capability**: SystemCapability.Web.Webview.Core 5690 5691**Return value** 5692 5693| Type | Description | 5694| ------- | --------------------------------------- | 5695| boolean | Whether the safe browsing feature is enabled. The default value is **false**.| 5696 5697**Example** 5698 5699```ts 5700// xxx.ets 5701import { webview } from '@kit.ArkWeb'; 5702 5703@Entry 5704@Component 5705struct WebComponent { 5706 controller: webview.WebviewController = new webview.WebviewController(); 5707 5708 build() { 5709 Column() { 5710 Button('isSafeBrowsingEnabled') 5711 .onClick(() => { 5712 let result = this.controller.isSafeBrowsingEnabled(); 5713 console.log("result: " + result); 5714 }) 5715 Web({ src: 'www.example.com', controller: this.controller }) 5716 } 5717 } 5718} 5719``` 5720 5721### enableIntelligentTrackingPrevention<sup>12+</sup> 5722 5723enableIntelligentTrackingPrevention(enable: boolean): void 5724 5725Enables intelligent tracking prevention. By default, this feature is disabled. 5726 5727**System capability**: SystemCapability.Web.Webview.Core 5728 5729**Parameters** 5730 5731| Name | Type | Mandatory | Description | 5732| --------| ------- | ---- | ---------------------------| 5733| enable | boolean | Yes | Whether to enable intelligent tracking prevention.| 5734 5735**Error codes** 5736 5737For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5738 5739| ID| Error Message | 5740| -------- | ----------------------- | 5741| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5742| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5743 5744**Example** 5745 5746```ts 5747// xxx.ets 5748import { webview } from '@kit.ArkWeb'; 5749import { BusinessError } from '@kit.BasicServicesKit'; 5750 5751@Entry 5752@Component 5753struct WebComponent { 5754 controller: webview.WebviewController = new webview.WebviewController(); 5755 5756 build() { 5757 Column() { 5758 Button('enableIntelligentTrackingPrevention') 5759 .onClick(() => { 5760 try { 5761 this.controller.enableIntelligentTrackingPrevention(true); 5762 console.log("enableIntelligentTrackingPrevention: true"); 5763 } catch (error) { 5764 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5765 } 5766 }) 5767 Web({ src: 'www.example.com', controller: this.controller }) 5768 } 5769 } 5770} 5771``` 5772 5773### isIntelligentTrackingPreventionEnabled<sup>12+</sup> 5774 5775isIntelligentTrackingPreventionEnabled(): boolean 5776 5777Obtains whether intelligent tracking prevention is enabled on this web page. 5778 5779**System capability**: SystemCapability.Web.Webview.Core 5780 5781**Return value** 5782 5783| Type | Description | 5784| ------- | --------------------------------------- | 5785| boolean | Whether intelligent tracking prevention is enabled on the current web page. The default value is **false**.| 5786 5787**Error codes** 5788 5789For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5790 5791| ID| Error Message | 5792| -------- | ----------------------- | 5793| 17100001 | Init error. The WebviewController must be associated with a Web component. | 5794 5795**Example** 5796 5797```ts 5798// xxx.ets 5799import { webview } from '@kit.ArkWeb'; 5800import { BusinessError } from '@kit.BasicServicesKit'; 5801 5802@Entry 5803@Component 5804struct WebComponent { 5805 controller: webview.WebviewController = new webview.WebviewController(); 5806 5807 build() { 5808 Column() { 5809 Button('isIntelligentTrackingPreventionEnabled') 5810 .onClick(() => { 5811 try { 5812 let result = this.controller.isIntelligentTrackingPreventionEnabled(); 5813 console.log("result: " + result); 5814 } catch (error) { 5815 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5816 } 5817 }) 5818 Web({ src: 'www.example.com', controller: this.controller }) 5819 } 5820 } 5821} 5822``` 5823 5824### addIntelligentTrackingPreventionBypassingList<sup>12+</sup> 5825 5826static addIntelligentTrackingPreventionBypassingList(hostList: Array\<string>): void 5827 5828Adds a list of domain names that bypass intelligent tracking prevention. 5829 5830**System capability**: SystemCapability.Web.Webview.Core 5831 5832**Parameters** 5833 5834| Name | Type | Mandatory | Description | 5835| ----------- | ------------- | ---- | ------------------------ | 5836| hostList | Array\<string> | Yes | List of domain names that bypass intelligent tracking prevention.| 5837 5838**Error codes** 5839 5840For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5841 5842| ID | Error Message | 5843| -------- | ------------------------ | 5844| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5845 5846**Example** 5847 5848```ts 5849// xxx.ets 5850import { webview } from '@kit.ArkWeb'; 5851import { BusinessError } from '@kit.BasicServicesKit'; 5852 5853@Entry 5854@Component 5855struct WebComponent { 5856 controller: webview.WebviewController = new webview.WebviewController(); 5857 5858 build() { 5859 Column() { 5860 Button('addIntelligentTrackingPreventionBypassingList') 5861 .onClick(() => { 5862 try { 5863 let hostList = ["www.test1.com", "www.test2.com", "www.test3.com"]; 5864 webview.WebviewController.addIntelligentTrackingPreventionBypassingList(hostList); 5865 } catch (error) { 5866 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5867 } 5868 }) 5869 Web({ src: 'www.example.com', controller: this.controller }) 5870 } 5871 } 5872} 5873``` 5874 5875### removeIntelligentTrackingPreventionBypassingList<sup>12+</sup> 5876 5877static removeIntelligentTrackingPreventionBypassingList(hostList: Array\<string>): void 5878 5879Deletes the domain names from the list of domain names added through the **addIntelligentTrackingPreventionBypassingList** API. 5880 5881**System capability**: SystemCapability.Web.Webview.Core 5882 5883**Parameters** 5884 5885| Name | Type | Mandatory | Description | 5886| ----------- | ------------- | ---- | ------------------------ | 5887| hostList | Array\<string> | Yes | List of domain names that bypass intelligent tracking prevention.| 5888 5889**Error codes** 5890 5891For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 5892 5893| ID | Error Message | 5894| -------- | ------------------------ | 5895| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 5896 5897**Example** 5898 5899```ts 5900// xxx.ets 5901import { webview } from '@kit.ArkWeb'; 5902import { BusinessError } from '@kit.BasicServicesKit'; 5903 5904@Entry 5905@Component 5906struct WebComponent { 5907 controller: webview.WebviewController = new webview.WebviewController(); 5908 5909 build() { 5910 Column() { 5911 Button('removeIntelligentTrackingPreventionBypassingList') 5912 .onClick(() => { 5913 try { 5914 let hostList = ["www.test1.com", "www.test2.com"]; 5915 webview.WebviewController.removeIntelligentTrackingPreventionBypassingList(hostList); 5916 } catch (error) { 5917 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 5918 } 5919 }) 5920 Web({ src: 'www.example.com', controller: this.controller }) 5921 } 5922 } 5923} 5924``` 5925 5926### clearIntelligentTrackingPreventionBypassingList<sup>12+</sup> 5927 5928static clearIntelligentTrackingPreventionBypassingList(): void 5929 5930Deletes all domain names from the list of domain names added through the **addIntelligentTrackingPreventionBypassingList** API. 5931 5932**System capability**: SystemCapability.Web.Webview.Core 5933 5934**Example** 5935 5936```ts 5937// xxx.ets 5938import { webview } from '@kit.ArkWeb'; 5939 5940@Entry 5941@Component 5942struct WebComponent { 5943 controller: webview.WebviewController = new webview.WebviewController(); 5944 5945 build() { 5946 Column() { 5947 Button('clearIntelligentTrackingPreventionBypassingList') 5948 .onClick(() => { 5949 webview.WebviewController.clearIntelligentTrackingPreventionBypassingList(); 5950 }) 5951 Web({ src: 'www.example.com', controller: this.controller }) 5952 } 5953 } 5954} 5955``` 5956 5957### getDefaultUserAgent<sup>14+</sup> 5958 5959static getDefaultUserAgent(): string 5960 5961Obtains the default user agent. 5962 5963This API can be called only in the UI thread. 5964 5965**System capability**: SystemCapability.Web.Webview.Core 5966 5967**Example** 5968 5969```ts 5970// xxx.ets 5971import { webview } from '@kit.ArkWeb'; 5972 5973@Entry 5974@Component 5975struct WebComponent { 5976 controller: webview.WebviewController = new webview.WebviewController(); 5977 5978 build() { 5979 Column() { 5980 Button('getDefaultUserAgent') 5981 .onClick(() => { 5982 let defaultUserAgent = webview.WebviewController.getDefaultUserAgent(); 5983 console.log("defaultUserAgent: " + defaultUserAgent); 5984 }) 5985 } 5986 } 5987} 5988``` 5989 5990### enableAdsBlock<sup>12+</sup> 5991 5992enableAdsBlock(enable: boolean): void 5993 5994Enables ad blocking. By default, this feature is disabled. 5995 5996**System capability**: SystemCapability.Web.Webview.Core 5997 5998**Parameters** 5999 6000| Name | Type | Mandatory | Description | 6001| --------| ------- | ---- | ---------------------------| 6002| enable | boolean | Yes | Whether to enable ad blocking.| 6003 6004**Error codes** 6005 6006For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6007 6008| ID| Error Message | 6009| -------- | ----------------------- | 6010| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6011| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Parameter string is too long. 3.Parameter verification failed. | 6012 6013**Example** 6014 6015```ts 6016// xxx.ets 6017import { webview } from '@kit.ArkWeb'; 6018import { BusinessError } from '@kit.BasicServicesKit'; 6019 6020@Entry 6021@Component 6022struct WebComponent { 6023 controller: webview.WebviewController = new webview.WebviewController(); 6024 6025 build() { 6026 Column() { 6027 Button('enableAdsBlock') 6028 .onClick(() => { 6029 try { 6030 this.controller.enableAdsBlock(true); 6031 console.log("enableAdsBlock: true") 6032 } catch (error) { 6033 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6034 } 6035 }) 6036 Web({ src: 'www.example.com', controller: this.controller }) 6037 } 6038 } 6039} 6040``` 6041 6042### isAdsBlockEnabled<sup>12+</sup> 6043 6044isAdsBlockEnabled() : boolean 6045 6046Checks whether ad blocking is enabled. By default, this feature is disabled. 6047 6048**System capability**: SystemCapability.Web.Webview.Core 6049 6050**Return value** 6051 6052| Type | Description | 6053| ------------------------------------------------------------ | ---------------------- | 6054| boolean | Returns **true** if ad blocking is enabled; returns **false** otherwise.| 6055 6056**Example** 6057 6058```ts 6059// xxx.ets 6060import { webview } from '@kit.ArkWeb'; 6061import { BusinessError } from '@kit.BasicServicesKit'; 6062 6063@Entry 6064@Component 6065struct WebComponent { 6066 controller: webview.WebviewController = new webview.WebviewController(); 6067 6068 build() { 6069 Column() { 6070 Button('isAdsBlockEnabled') 6071 .onClick(() => { 6072 try { 6073 let isAdsBlockEnabled: boolean = this.controller.isAdsBlockEnabled(); 6074 console.log("isAdsBlockEnabled:", isAdsBlockEnabled); 6075 } catch (error) { 6076 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6077 } 6078 }) 6079 Web({ src: 'www.example.com', controller: this.controller }) 6080 } 6081 } 6082} 6083``` 6084 6085### isAdsBlockEnabledForCurPage<sup>12+</sup> 6086 6087isAdsBlockEnabledForCurPage() : boolean 6088 6089Checks whether ad blocking is enabled on this web page. 6090After 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. 6091 6092**System capability**: SystemCapability.Web.Webview.Core 6093 6094**Return value** 6095 6096| Type | Description | 6097| ------------------------------------------------------------ | ---------------------- | 6098| boolean | Returns **true** if ad blocking is enabled; returns **false** otherwise.| 6099 6100**Example** 6101 6102```ts 6103// xxx.ets 6104import { webview } from '@kit.ArkWeb'; 6105import { BusinessError } from '@kit.BasicServicesKit'; 6106 6107@Entry 6108@Component 6109struct WebComponent { 6110 controller: webview.WebviewController = new webview.WebviewController(); 6111 6112 build() { 6113 Column() { 6114 Button('isAdsBlockEnabledForCurPage') 6115 .onClick(() => { 6116 try { 6117 let isAdsBlockEnabledForCurPage: boolean = this.controller.isAdsBlockEnabledForCurPage(); 6118 console.log("isAdsBlockEnabledForCurPage:", isAdsBlockEnabledForCurPage); 6119 } catch (error) { 6120 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6121 } 6122 }) 6123 Web({ src: 'www.example.com', controller: this.controller }) 6124 } 6125 } 6126} 6127``` 6128 6129### setRenderProcessMode<sup>12+</sup> 6130 6131static setRenderProcessMode(mode: RenderProcessMode): void 6132 6133Sets the ArkWeb render subprocess mode. 6134 6135**System capability**: SystemCapability.Web.Webview.Core 6136 6137**Parameters** 6138 6139| Name | Type | Mandatory | Description | 6140| ----------- | ------------- | ---- | ------------------------ | 6141| 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.| 6142 6143**Error codes** 6144 6145For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6146 6147| ID | Error Message | 6148| -------- | ------------------------ | 6149| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 6150 6151**Example** 6152 6153```ts 6154// xxx.ets 6155import { webview } from '@kit.ArkWeb'; 6156import { BusinessError } from '@kit.BasicServicesKit'; 6157 6158@Entry 6159@Component 6160struct WebComponent { 6161 controller: webview.WebviewController = new webview.WebviewController(); 6162 6163 build() { 6164 Column() { 6165 Button('setRenderProcessMode') 6166 .onClick(() => { 6167 try { 6168 webview.WebviewController.setRenderProcessMode(webview.RenderProcessMode.MULTIPLE); 6169 } catch (error) { 6170 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6171 } 6172 }) 6173 Web({ src: 'www.example.com', controller: this.controller }) 6174 } 6175 } 6176} 6177``` 6178### getRenderProcessMode<sup>12+</sup> 6179 6180static getRenderProcessMode(): RenderProcessMode 6181 6182Obtains the ArkWeb render subprocess mode. 6183 6184**System capability**: SystemCapability.Web.Webview.Core 6185 6186**Return value** 6187 6188| Type | Description | 6189| ----------------------------------------- | ------------------------------------------------------------ | 6190| [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.| 6191 6192 6193**Example** 6194 6195```ts 6196// xxx.ets 6197import { webview } from '@kit.ArkWeb'; 6198 6199@Entry 6200@Component 6201struct WebComponent { 6202 controller: webview.WebviewController = new webview.WebviewController(); 6203 6204 build() { 6205 Column() { 6206 Button('getRenderProcessMode') 6207 .onClick(() => { 6208 let mode = webview.WebviewController.getRenderProcessMode(); 6209 console.log("getRenderProcessMode: " + mode); 6210 }) 6211 Web({ src: 'www.example.com', controller: this.controller }) 6212 } 6213 } 6214} 6215``` 6216 6217### terminateRenderProcess<sup>12+</sup> 6218 6219terminateRenderProcess(): boolean 6220 6221Terminates this render process. 6222 6223Calling 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. 6224 6225**System capability**: SystemCapability.Web.Webview.Core 6226 6227**Return value** 6228 6229| Type | Description | 6230| ------------------------------------------------------------ | ---------------------- | 6231| 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.| 6232 6233**Error codes** 6234 6235For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6236 6237| ID | Error Message | 6238| -------- | ------------------------------------------------------------ | 6239| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6240 6241**Example** 6242 6243```ts 6244// xxx.ets 6245import { webview } from '@kit.ArkWeb'; 6246 6247@Entry 6248@Component 6249struct WebComponent { 6250 controller: webview.WebviewController = new webview.WebviewController(); 6251 6252 build() { 6253 Column() { 6254 Button('terminateRenderProcess') 6255 .onClick(() => { 6256 let result = this.controller.terminateRenderProcess(); 6257 console.log("terminateRenderProcess result: " + result); 6258 }) 6259 Web({ src: 'www.example.com', controller: this.controller }) 6260 } 6261 } 6262} 6263``` 6264 6265### postUrl<sup>11+</sup> 6266 6267postUrl(url: string, postData: ArrayBuffer): void 6268 6269Loads 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. 6270 6271**System capability**: SystemCapability.Web.Webview.Core 6272 6273**Parameters** 6274 6275| Name | Type | Mandatory| Description | 6276| ------- | ---------------- | ---- | :-------------------- | 6277| url | string | Yes | URL to load. | 6278| postData | ArrayBuffer | Yes | Data to transfer using the POST method. The request must be encoded in "application/x-www-form-urlencoded" format.| 6279 6280**Error codes** 6281 6282For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6283 6284| ID| Error Message | 6285| -------- | ------------------------------------------------------------ | 6286| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6287| 17100002 | Invalid url. | 6288| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 6289 6290**Example** 6291 6292```ts 6293// xxx.ets 6294import { webview } from '@kit.ArkWeb'; 6295import { BusinessError } from '@kit.BasicServicesKit'; 6296 6297class TestObj { 6298 constructor() { 6299 } 6300 6301 test(str: string): ArrayBuffer { 6302 let buf = new ArrayBuffer(str.length); 6303 let buff = new Uint8Array(buf); 6304 6305 for (let i = 0; i < str.length; i++) { 6306 buff[i] = str.charCodeAt(i); 6307 } 6308 return buf; 6309 } 6310} 6311 6312@Entry 6313@Component 6314struct WebComponent { 6315 controller: webview.WebviewController = new webview.WebviewController(); 6316 @State testObjtest: TestObj = new TestObj(); 6317 6318 build() { 6319 Column() { 6320 Button('postUrl') 6321 .onClick(() => { 6322 try { 6323 // Convert data to the ArrayBuffer type. 6324 let postData = this.testObjtest.test("Name=test&Password=test"); 6325 this.controller.postUrl('www.example.com', postData); 6326 } catch (error) { 6327 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6328 } 6329 }) 6330 Web({ src: '', controller: this.controller }) 6331 } 6332 } 6333} 6334``` 6335 6336### createWebPrintDocumentAdapter<sup>11+</sup> 6337 6338createWebPrintDocumentAdapter(jobName: string): print.PrintDocumentAdapter 6339 6340Creates a **PrintDocumentAdapter** instance to provide content for printing. 6341 6342**System capability**: SystemCapability.Web.Webview.Core 6343 6344**Parameters** 6345 6346| Name | Type | Mandatory| Description | 6347| ------- | ------ | ---- | :-------------------- | 6348| jobName | string | Yes | Name of the file to print. | 6349 6350**Return value** 6351 6352| Type | Description | 6353| -------------------- | ------------------------- | 6354| print.printDocumentAdapter | **PrintDocumentAdapter** instance created.| 6355 6356**Error codes** 6357 6358For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6359 6360| ID| Error Message | 6361| -------- | -------------------------------------------------------------------------- | 6362| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 6363| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6364 6365**Example** 6366 6367```ts 6368// xxx.ets 6369import { webview } from '@kit.ArkWeb'; 6370import { BusinessError, print } from '@kit.BasicServicesKit'; 6371 6372@Entry 6373@Component 6374struct WebComponent { 6375 controller: webview.WebviewController = new webview.WebviewController(); 6376 6377 build() { 6378 Column() { 6379 Button('createWebPrintDocumentAdapter') 6380 .onClick(() => { 6381 try { 6382 let webPrintDocadapter = this.controller.createWebPrintDocumentAdapter('example.pdf'); 6383 print.print('example_jobid', webPrintDocadapter, null, getContext()); 6384 } catch (error) { 6385 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6386 } 6387 }) 6388 Web({ src: 'www.example.com', controller: this.controller }) 6389 } 6390 } 6391} 6392``` 6393### isIncognitoMode<sup>11+</sup> 6394 6395isIncognitoMode(): boolean 6396 6397Checks whether this Webview is in incognito mode. 6398 6399**System capability**: SystemCapability.Web.Webview.Core 6400 6401**Return value** 6402 6403| Type | Description | 6404| -------------------- | ------------------------- | 6405| boolean | Whether the Webview is in incognito mode.| 6406 6407**Error codes** 6408 6409For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6410 6411| ID| Error Message | 6412| -------- | -------------------------------------------------------------------------- | 6413| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6414 6415**Example** 6416 6417```ts 6418// xxx.ets 6419import { webview } from '@kit.ArkWeb'; 6420import { BusinessError } from '@kit.BasicServicesKit'; 6421 6422@Entry 6423@Component 6424struct WebComponent { 6425 controller: webview.WebviewController = new webview.WebviewController(); 6426 6427 build() { 6428 Column() { 6429 Button('isIncognitoMode') 6430 .onClick(() => { 6431 try { 6432 let result = this.controller.isIncognitoMode(); 6433 console.log('isIncognitoMode' + result); 6434 } catch (error) { 6435 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6436 } 6437 }) 6438 Web({ src: 'www.example.com', controller: this.controller }) 6439 } 6440 } 6441} 6442``` 6443 6444### getSecurityLevel<sup>11+</sup> 6445 6446getSecurityLevel(): SecurityLevel 6447 6448Obtains the security level of this web page. 6449 6450**System capability**: SystemCapability.Web.Webview.Core 6451 6452**Return value** 6453 6454| Type | Description | 6455| ----------------------------------- | --------------------------- | 6456| [SecurityLevel](#securitylevel11) | Security level of the web page. The value can be **NONE**, **SECURE**, **WARNING**, or **DANGEROUS**.| 6457 6458**Error codes** 6459 6460For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6461 6462| ID| Error Message | 6463| -------- | ------------------------------------------------------------ | 6464| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6465 6466**Example** 6467 6468```ts 6469import { webview } from '@kit.ArkWeb'; 6470 6471@Entry 6472@Component 6473struct WebComponent { 6474 controller: webview.WebviewController = new webview.WebviewController(); 6475 6476 build() { 6477 Column() { 6478 Web({ src: 'www.example.com', controller: this.controller }) 6479 .onPageEnd((event) => { 6480 if (event) { 6481 let securityLevel = this.controller.getSecurityLevel(); 6482 console.info('securityLevel: ', securityLevel); 6483 } 6484 }) 6485 } 6486 } 6487} 6488``` 6489 6490### setScrollable<sup>12+</sup> 6491 6492setScrollable(enable: boolean, type?: ScrollType): void 6493 6494Sets whether this web page is scrollable. 6495 6496**System capability**: SystemCapability.Web.Webview.Core 6497 6498**Parameters** 6499 6500| Name| Type| Mandatory| Description | 6501| ------ | -------- | ---- | ---------------------- | 6502| enable | boolean | Yes | Whether the web page is scrollable. The value **true** means the web page is scrollable, and **false** means the opposite.| 6503| 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**.| 6504 6505**Error codes** 6506 6507For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6508 6509| ID| Error Message | 6510| -------- | ------------------------------------------------------------ | 6511| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 6512| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6513 6514**Example** 6515 6516```ts 6517// xxx.ets 6518import { webview } from '@kit.ArkWeb'; 6519import { BusinessError } from '@kit.BasicServicesKit'; 6520 6521@Entry 6522@Component 6523struct WebComponent { 6524 controller: webview.WebviewController = new webview.WebviewController(); 6525 6526 build() { 6527 Column() { 6528 Button('setScrollable') 6529 .onClick(() => { 6530 try { 6531 this.controller.setScrollable(true); 6532 } catch (error) { 6533 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6534 } 6535 }) 6536 Web({ src: 'www.example.com', controller: this.controller }) 6537 } 6538 } 6539} 6540``` 6541 6542### getScrollable<sup>12+</sup> 6543 6544getScrollable(): boolean 6545 6546Obtains whether this web page is scrollable. 6547 6548**System capability**: SystemCapability.Web.Webview.Core 6549 6550**Return value** 6551 6552| Type | Description | 6553| ------ | -------------- | 6554| boolean | Whether the web page is scrollable. The value **true** means the web page is scrollable, and **false** means the opposite.| 6555 6556**Error codes** 6557 6558For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6559 6560| ID| Error Message | 6561| -------- | ------------------------------------------------------------ | 6562| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6563 6564**Example** 6565 6566```ts 6567// xxx.ets 6568import { webview } from '@kit.ArkWeb'; 6569import { BusinessError } from '@kit.BasicServicesKit'; 6570 6571@Entry 6572@Component 6573struct WebComponent { 6574 controller: webview.WebviewController = new webview.WebviewController(); 6575 6576 build() { 6577 Column() { 6578 Button('getScrollable') 6579 .onClick(() => { 6580 try { 6581 let scrollEnabled = this.controller.getScrollable(); 6582 console.log("scrollEnabled: " + scrollEnabled); 6583 } catch (error) { 6584 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6585 } 6586 }) 6587 Web({ src: 'www.example.com', controller: this.controller }) 6588 } 6589 } 6590} 6591``` 6592 6593### setPrintBackground<sup>12+</sup> 6594 6595setPrintBackground(enable: boolean): void 6596 6597Sets whether to print the web page background. 6598 6599**System capability**: SystemCapability.Web.Webview.Core 6600 6601**Parameters** 6602 6603| Name | Type | Mandatory| Description | 6604| -------- | ------- | ---- | -------------------------------------- | 6605| 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.| 6606 6607**Error codes** 6608 6609For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6610 6611| ID| Error Message | 6612| -------- | ------------------------------------------------------------ | 6613| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 6614| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6615 6616**Example** 6617 6618```ts 6619import { webview } from '@kit.ArkWeb'; 6620import { BusinessError } from '@kit.BasicServicesKit'; 6621 6622@Entry 6623@Component 6624struct WebComponent { 6625 controller: webview.WebviewController = new webview.WebviewController(); 6626 6627 build() { 6628 Column() { 6629 Button('setPrintBackground') 6630 .onClick(() => { 6631 try { 6632 this.controller.setPrintBackground(false); 6633 } catch (error) { 6634 console.error(`ErrorCode:${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6635 } 6636 }) 6637 Web({ src: 'www.example.com', controller: this.controller }) 6638 } 6639 } 6640} 6641``` 6642 6643### getPrintBackground<sup>12+</sup> 6644 6645getPrintBackground(): boolean 6646 6647Obtains whether the web page background is printed. 6648 6649**System capability**: SystemCapability.Web.Webview.Core 6650 6651**Return value** 6652 6653| Type | Description | 6654| -------------------- | ------------------------- | 6655| boolean | Whether the web page background is printed.| 6656 6657**Error codes** 6658 6659For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6660 6661| ID| Error Message | 6662| -------- | ------------------------------------------------------------ | 6663| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6664 6665**Example** 6666 6667```ts 6668import { webview } from '@kit.ArkWeb'; 6669import { BusinessError } from '@kit.BasicServicesKit'; 6670 6671@Entry 6672@Component 6673struct WebComponent { 6674 controller: webview.WebviewController = new webview.WebviewController(); 6675 6676 build() { 6677 Column() { 6678 Button('setPrintBackground') 6679 .onClick(() => { 6680 try { 6681 let enable = this.controller.getPrintBackground(); 6682 console.log("getPrintBackground: " + enable); 6683 } catch (error) { 6684 console.error(`ErrorCode:${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6685 } 6686 }) 6687 Web({ src: 'www.example.com', controller: this.controller }) 6688 } 6689 } 6690} 6691``` 6692 6693### getLastJavascriptProxyCallingFrameUrl<sup>12+</sup> 6694 6695getLastJavascriptProxyCallingFrameUrl(): string 6696 6697Obtains 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. 6698 6699**System capability**: SystemCapability.Web.Webview.Core 6700 6701**Error codes** 6702 6703For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6704 6705| ID| Error Message | 6706| -------- | ------------------------------------------------------------ | 6707| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6708 6709**Example** 6710 6711```ts 6712// xxx.ets 6713import { webview } from '@kit.ArkWeb'; 6714import { BusinessError } from '@kit.BasicServicesKit'; 6715 6716class TestObj { 6717 mycontroller: webview.WebviewController; 6718 6719 constructor(controller: webview.WebviewController) { 6720 this.mycontroller = controller; 6721 } 6722 6723 test(testStr: string): string { 6724 console.log('Web Component str' + testStr + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 6725 return testStr; 6726 } 6727 6728 toString(): void { 6729 console.log('Web Component toString ' + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 6730 } 6731 6732 testNumber(testNum: number): number { 6733 console.log('Web Component number' + testNum + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 6734 return testNum; 6735 } 6736 6737 testBool(testBol: boolean): boolean { 6738 console.log('Web Component boolean' + testBol + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 6739 return testBol; 6740 } 6741} 6742 6743class WebObj { 6744 mycontroller: webview.WebviewController; 6745 6746 constructor(controller: webview.WebviewController) { 6747 this.mycontroller = controller; 6748 } 6749 6750 webTest(): string { 6751 console.log('Web test ' + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 6752 return "Web test"; 6753 } 6754 6755 webString(): void { 6756 console.log('Web test toString ' + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); 6757 } 6758} 6759 6760@Entry 6761@Component 6762struct Index { 6763 controller: webview.WebviewController = new webview.WebviewController(); 6764 @State testObjtest: TestObj = new TestObj(this.controller); 6765 @State webTestObj: WebObj = new WebObj(this.controller); 6766 6767 build() { 6768 Column() { 6769 Button('refresh') 6770 .onClick(() => { 6771 try { 6772 this.controller.refresh(); 6773 } catch (error) { 6774 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6775 } 6776 }) 6777 Button('Register JavaScript To Window') 6778 .onClick(() => { 6779 try { 6780 this.controller.registerJavaScriptProxy(this.testObjtest, "objName", ["test", "toString", "testNumber", "testBool"]); 6781 this.controller.registerJavaScriptProxy(this.webTestObj, "objTestName", ["webTest", "webString"]); 6782 } catch (error) { 6783 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6784 } 6785 }) 6786 Button('deleteJavaScriptRegister') 6787 .onClick(() => { 6788 try { 6789 this.controller.deleteJavaScriptRegister("objName"); 6790 this.controller.deleteJavaScriptRegister("objTestName"); 6791 } catch (error) { 6792 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6793 } 6794 }) 6795 Web({ src: $rawfile('index.html'), controller: this.controller }) 6796 .javaScriptAccess(true) 6797 } 6798 } 6799} 6800``` 6801 6802HTML file to be loaded: 6803```html 6804<!-- index.html --> 6805<!DOCTYPE html> 6806<html> 6807 <meta charset="utf-8"> 6808 <body> 6809 <button type="button" onclick="htmlTest()">Click Me!</button> 6810 <p id="demo"></p> 6811 <p id="webDemo"></p> 6812 </body> 6813 <script type="text/javascript"> 6814 function htmlTest() { 6815 // This function call expects to return "ArkUI Web Component" 6816 let str=objName.test("webtest data"); 6817 objName.testNumber(1); 6818 objName.testBool(true); 6819 document.getElementById("demo").innerHTML=str; 6820 console.log('objName.test result:'+ str) 6821 6822 // This function call expects to return "Web test" 6823 let webStr = objTestName.webTest(); 6824 document.getElementById("webDemo").innerHTML=webStr; 6825 console.log('objTestName.webTest result:'+ webStr) 6826 } 6827</script> 6828</html> 6829``` 6830 6831### pauseAllTimers<sup>12+</sup> 6832 6833pauseAllTimers(): void 6834 6835Pauses all WebView timers. 6836 6837**System capability**: SystemCapability.Web.Webview.Core 6838 6839**Error codes** 6840 6841For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6842 6843| ID| Error Message | 6844| -------- | ------------------------------------------------------------ | 6845| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6846 6847**Example** 6848 6849```ts 6850import { webview } from '@kit.ArkWeb'; 6851import { BusinessError } from '@kit.BasicServicesKit'; 6852 6853@Entry 6854@Component 6855struct WebComponent { 6856 controller: webview.WebviewController = new webview.WebviewController(); 6857 6858 build() { 6859 Column() { 6860 Row() { 6861 Button('PauseAllTimers') 6862 .onClick(() => { 6863 try { 6864 webview.WebviewController.pauseAllTimers(); 6865 } catch (error) { 6866 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6867 } 6868 }) 6869 } 6870 Web({ src: $rawfile("index.html"), controller: this.controller }) 6871 } 6872 } 6873} 6874``` 6875HTML file to be loaded: 6876 6877```html 6878<!DOCTYPE html> 6879<html> 6880 <body> 6881 <button style="width:300px;height:150px;font-size:50px" onclick="startTimer()">start</button> 6882 <button style="width:300px;height:150px;font-size:50px" onclick="resetTimer()">reset</button> 6883 <input style="width:300px;height:150px;font-size:50px" value="0" id="show_num"> 6884 </body> 6885</html> 6886<script> 6887 var timer = null; 6888 var num = 0; 6889 6890 function startTimer() { 6891 timer = setInterval(function() { 6892 document.getElementById("show_num").value = ++num; 6893 }, 1000); 6894 } 6895</script> 6896``` 6897 6898### resumeAllTimers<sup>12+</sup> 6899 6900resumeAllTimers(): void 6901 6902Resumes all timers that are paused from the **pauseAllTimers()** API. 6903 6904**System capability**: SystemCapability.Web.Webview.Core 6905 6906**Error codes** 6907 6908For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6909 6910| ID| Error Message | 6911| -------- | ------------------------------------------------------------ | 6912| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6913 6914**Example** 6915 6916```ts 6917import { webview } from '@kit.ArkWeb'; 6918import { BusinessError } from '@kit.BasicServicesKit'; 6919 6920@Entry 6921@Component 6922struct WebComponent { 6923 controller: webview.WebviewController = new webview.WebviewController(); 6924 6925 build() { 6926 Column() { 6927 Row() { 6928 Button('ResumeAllTimers') 6929 .onClick(() => { 6930 try { 6931 webview.WebviewController.resumeAllTimers(); 6932 } catch (error) { 6933 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6934 } 6935 }) 6936 Button('PauseAllTimers') 6937 .onClick(() => { 6938 try { 6939 webview.WebviewController.pauseAllTimers(); 6940 } catch (error) { 6941 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 6942 } 6943 }) 6944 } 6945 Web({ src: $rawfile("index.html"), controller: this.controller }) 6946 } 6947 } 6948} 6949``` 6950HTML file to be loaded: 6951 6952```html 6953<!DOCTYPE html> 6954<html> 6955 <body> 6956 <button style="width:300px;height:150px;font-size:50px" onclick="startTimer()">start</button> 6957 <button style="width:300px;height:150px;font-size:50px" onclick="resetTimer()">reset</button> 6958 <input style="width:300px;height:150px;font-size:50px" value="0" id="show_num"> 6959 </body> 6960</html> 6961<script> 6962 var timer = null; 6963 var num = 0; 6964 6965 function startTimer() { 6966 timer = setInterval(function() { 6967 document.getElementById("show_num").value = ++num; 6968 }, 1000); 6969 } 6970 6971 function resetTimer() { 6972 clearInterval(timer); 6973 document.getElementById("show_num").value = 0; 6974 num = 0; 6975 } 6976</script> 6977``` 6978 6979### stopAllMedia<sup>12+</sup> 6980 6981stopAllMedia(): void 6982 6983Stops all audio and video on a web page. 6984 6985**System capability**: SystemCapability.Web.Webview.Core 6986 6987**Error codes** 6988 6989For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 6990 6991| ID| Error Message | 6992| -------- | ------------------------------------------------------------ | 6993| 17100001 | Init error. The WebviewController must be associated with a Web component. | 6994 6995**Example** 6996 6997```ts 6998// xxx.ets 6999import { webview } from '@kit.ArkWeb'; 7000import { BusinessError } from '@kit.BasicServicesKit'; 7001 7002@Entry 7003@Component 7004struct WebComponent { 7005 controller: webview.WebviewController = new webview.WebviewController(); 7006 7007 build() { 7008 Column() { 7009 Button('stopAllMedia') 7010 .onClick(() => { 7011 try { 7012 this.controller.stopAllMedia(); 7013 } catch (error) { 7014 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7015 } 7016 }) 7017 Web({ src: 'www.example.com', controller: this.controller }) 7018 } 7019 } 7020} 7021``` 7022 7023### pauseAllMedia<sup>12+</sup> 7024 7025pauseAllMedia(): void 7026 7027Pauses all audio and video on a web page. 7028 7029**System capability**: SystemCapability.Web.Webview.Core 7030 7031**Error codes** 7032 7033For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7034 7035| ID| Error Message | 7036| -------- | ------------------------------------------------------------ | 7037| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7038 7039**Example** 7040 7041```ts 7042// xxx.ets 7043import { webview } from '@kit.ArkWeb'; 7044import { BusinessError } from '@kit.BasicServicesKit'; 7045 7046@Entry 7047@Component 7048struct WebComponent { 7049 controller: webview.WebviewController = new webview.WebviewController(); 7050 7051 build() { 7052 Column() { 7053 Button('pauseAllMedia') 7054 .onClick(() => { 7055 try { 7056 this.controller.pauseAllMedia(); 7057 } catch (error) { 7058 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7059 } 7060 }) 7061 Web({ src: 'www.example.com', controller: this.controller }) 7062 } 7063 } 7064} 7065``` 7066 7067### resumeAllMedia<sup>12+</sup> 7068 7069resumeAllMedia(): void 7070 7071Resumes the playback of the audio and video that are paused by the pauseAllMedia interface. 7072 7073**System capability**: SystemCapability.Web.Webview.Core 7074 7075**Error codes** 7076 7077For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7078 7079| ID| Error Message | 7080| -------- | ------------------------------------------------------------ | 7081| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7082 7083**Example** 7084 7085```ts 7086// xxx.ets 7087import { webview } from '@kit.ArkWeb'; 7088import { BusinessError } from '@kit.BasicServicesKit'; 7089 7090@Entry 7091@Component 7092struct WebComponent { 7093 controller: webview.WebviewController = new webview.WebviewController(); 7094 7095 build() { 7096 Column() { 7097 Button('resumeAllMedia') 7098 .onClick(() => { 7099 try { 7100 this.controller.resumeAllMedia(); 7101 } catch (error) { 7102 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7103 } 7104 }) 7105 Web({ src: 'www.example.com', controller: this.controller }) 7106 } 7107 } 7108} 7109``` 7110 7111### closeAllMediaPresentations<sup>12+</sup> 7112 7113closeAllMediaPresentations(): void 7114 7115Closes all full-screen videos on a web page. 7116 7117**System capability**: SystemCapability.Web.Webview.Core 7118 7119**Error codes** 7120 7121For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7122 7123| ID| Error Message | 7124| -------- | ------------------------------------------------------------ | 7125| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7126 7127**Example** 7128 7129```ts 7130// xxx.ets 7131import { webview } from '@kit.ArkWeb'; 7132import { BusinessError } from '@kit.BasicServicesKit'; 7133 7134@Entry 7135@Component 7136struct WebComponent { 7137 controller: webview.WebviewController = new webview.WebviewController(); 7138 7139 build() { 7140 Column() { 7141 Button('closeAllMediaPresentations') 7142 .onClick(() => { 7143 try { 7144 this.controller.closeAllMediaPresentations(); 7145 } catch (error) { 7146 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7147 } 7148 }) 7149 Web({ src: 'www.example.com', controller: this.controller }) 7150 } 7151 } 7152} 7153``` 7154 7155### getMediaPlaybackState<sup>12+</sup> 7156 7157getMediaPlaybackState(): MediaPlaybackState 7158 7159Queries the current audio and video playback control status. 7160 7161**System capability**: SystemCapability.Web.Webview.Core 7162 7163**Return value** 7164 7165| Type | Description | 7166| ------------------------------------------- | --------------------------------------------------------- | 7167| [MediaPlaybackState](#mediaplaybackstate12) | Playback control status of the current web page. The options are **NONE**, **PLAYING**, **PAUSED**, and **STOPPED**.| 7168 7169**Error codes** 7170 7171For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7172 7173| ID| Error Message | 7174| -------- | ------------------------------------------------------------ | 7175| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7176 7177**Example** 7178 7179```ts 7180// xxx.ets 7181import { webview } from '@kit.ArkWeb'; 7182import { BusinessError } from '@kit.BasicServicesKit'; 7183 7184@Entry 7185@Component 7186struct WebComponent { 7187 controller: webview.WebviewController = new webview.WebviewController(); 7188 7189 build() { 7190 Column() { 7191 Button('getMediaPlaybackState') 7192 .onClick(() => { 7193 try { 7194 console.log("MediaPlaybackState : " + this.controller.getMediaPlaybackState()); 7195 } catch (error) { 7196 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7197 } 7198 }) 7199 Web({ src: 'www.example.com', controller: this.controller }) 7200 } 7201 } 7202} 7203``` 7204 7205### setWebSchemeHandler<sup>12+</sup> 7206 7207setWebSchemeHandler(scheme: string, handler: WebSchemeHandler): void 7208 7209Sets the [WebSchemeHandler](#webschemehandler12), [WebSchemeHandler](#webschemehandler12) class for the current Web component to intercept requests of a specified scheme. 7210 7211**System capability**: SystemCapability.Web.Webview.Core 7212 7213**Parameters** 7214 7215| Name| Type | Mandatory| Description | 7216| ------ | ------ | ---- | :------------------------ | 7217| scheme | string | Yes | Protocol to be intercepted.| 7218| handler | [WebSchemeHandler](#webschemehandler12) | Yes | Interceptor that intercepts this protocol.| 7219 7220**Error codes** 7221 7222For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7223 7224| ID| Error Message | 7225| -------- | ------------------------------------------------------------ | 7226| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 7227| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7228 7229**Example** 7230 7231```ts 7232// xxx.ets 7233import { webview } from '@kit.ArkWeb'; 7234import { BusinessError } from '@kit.BasicServicesKit'; 7235 7236@Entry 7237@Component 7238struct WebComponent { 7239 controller: webview.WebviewController = new webview.WebviewController(); 7240 schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); 7241 7242 build() { 7243 Column() { 7244 Button('setWebSchemeHandler') 7245 .onClick(() => { 7246 try { 7247 this.controller.setWebSchemeHandler('http', this.schemeHandler); 7248 } catch (error) { 7249 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7250 } 7251 }) 7252 Web({ src: 'www.example.com', controller: this.controller }) 7253 } 7254 } 7255} 7256``` 7257 7258### clearWebSchemeHandler<sup>12+</sup> 7259 7260clearWebSchemeHandler(): void 7261 7262Clears all WebSchemeHandlers set for the current Web component. 7263 7264**System capability**: SystemCapability.Web.Webview.Core 7265 7266**Error codes** 7267 7268For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7269 7270| ID| Error Message | 7271| -------- | ------------------------------------------------------------ | 7272| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7273 7274**Example** 7275 7276```ts 7277// xxx.ets 7278import { webview } from '@kit.ArkWeb'; 7279import { BusinessError } from '@kit.BasicServicesKit'; 7280 7281@Entry 7282@Component 7283struct WebComponent { 7284 controller: webview.WebviewController = new webview.WebviewController(); 7285 7286 build() { 7287 Column() { 7288 Button('clearWebSchemeHandler') 7289 .onClick(() => { 7290 try { 7291 this.controller.clearWebSchemeHandler(); 7292 } catch (error) { 7293 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7294 } 7295 }) 7296 Web({ src: 'www.example.com', controller: this.controller }) 7297 } 7298 } 7299} 7300``` 7301 7302### setServiceWorkerWebSchemeHandler<sup>12+</sup> 7303 7304setServiceWorkerWebSchemeHandler(scheme: string, handler: WebSchemeHandler): void 7305 7306Sets the WebSchemeHandler used to intercept ServiceWorker for all Web components of the current application. 7307 7308**System capability**: SystemCapability.Web.Webview.Core 7309 7310**Parameters** 7311 7312| Name| Type | Mandatory| Description | 7313| ------ | ------ | ---- | :------------------------ | 7314| scheme | string | Yes | Protocol to be intercepted.| 7315| handler | [WebSchemeHandler](#webschemehandler12) | Yes | Interceptor that intercepts this protocol.| 7316 7317**Error codes** 7318 7319For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7320 7321| ID| Error Message | 7322| -------- | ------------------------------------------------------------ | 7323| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 7324 7325**Example** 7326 7327```ts 7328// xxx.ets 7329import { webview } from '@kit.ArkWeb'; 7330import { BusinessError } from '@kit.BasicServicesKit'; 7331 7332@Entry 7333@Component 7334struct WebComponent { 7335 controller: webview.WebviewController = new webview.WebviewController(); 7336 schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); 7337 7338 build() { 7339 Column() { 7340 Button('setWebSchemeHandler') 7341 .onClick(() => { 7342 try { 7343 webview.WebviewController.setServiceWorkerWebSchemeHandler('http', this.schemeHandler); 7344 } catch (error) { 7345 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7346 } 7347 }) 7348 Web({ src: 'www.example.com', controller: this.controller }) 7349 } 7350 } 7351} 7352``` 7353 7354### clearServiceWorkerWebSchemeHandler<sup>12+</sup> 7355 7356clearServiceWorkerWebSchemeHandler(): void 7357 7358Clears all WebSchemeHandlers that are set in the application and used to intercept ServiceWorker. 7359 7360**System capability**: SystemCapability.Web.Webview.Core 7361 7362**Example** 7363 7364```ts 7365// xxx.ets 7366import { webview } from '@kit.ArkWeb'; 7367 7368@Entry 7369@Component 7370struct WebComponent { 7371 controller: webview.WebviewController = new webview.WebviewController(); 7372 7373 build() { 7374 Column() { 7375 Button('clearServiceWorkerWebSchemeHandler') 7376 .onClick(() => { 7377 webview.WebviewController.clearServiceWorkerWebSchemeHandler(); 7378 }) 7379 Web({ src: 'www.example.com', controller: this.controller }) 7380 } 7381 } 7382} 7383``` 7384 7385### startCamera<sup>12+</sup> 7386 7387startCamera(): void 7388 7389Enables the camera capture of the current web page. 7390 7391**System capability**: SystemCapability.Web.Webview.Core 7392 7393**Error codes** 7394 7395For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7396 7397| ID| Error Message | 7398| -------- | ------------------------------------------------------------ | 7399| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7400 7401**Example** 7402```ts 7403// xxx.ets 7404import { webview } from '@kit.ArkWeb'; 7405import { BusinessError } from '@kit.BasicServicesKit'; 7406import { abilityAccessCtrl, PermissionRequestResult, common } from '@kit.AbilityKit'; 7407 7408let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); 7409try { 7410 let context: Context = getContext(this) as common.UIAbilityContext; 7411 atManager.requestPermissionsFromUser(context, ['ohos.permission.CAMERA'], (err: BusinessError, data: PermissionRequestResult) => { 7412 console.info('data:' + JSON.stringify(data)); 7413 console.info('data permissions:' + data.permissions); 7414 console.info('data authResults:' + data.authResults); 7415 }) 7416} catch (error) { 7417 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7418} 7419 7420@Entry 7421@Component 7422struct WebComponent { 7423 controller: webview.WebviewController = new webview.WebviewController(); 7424 7425 build() { 7426 Column() { 7427 Button("startCamera").onClick(() => { 7428 try { 7429 this.controller.startCamera(); 7430 } catch (error) { 7431 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7432 } 7433 }) 7434 Button("stopCamera").onClick(() => { 7435 try { 7436 this.controller.stopCamera(); 7437 } catch (error) { 7438 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7439 } 7440 }) 7441 Button("closeCamera").onClick(() => { 7442 try { 7443 this.controller.closeCamera(); 7444 } catch (error) { 7445 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 7446 } 7447 }) 7448 Web({ src: $rawfile('index.html'), controller: this.controller }) 7449 .onPermissionRequest((event) => { 7450 if (event) { 7451 AlertDialog.show({ 7452 title: 'title', 7453 message: 'text', 7454 primaryButton: { 7455 value: 'deny', 7456 action: () => { 7457 event.request.deny(); 7458 } 7459 }, 7460 secondaryButton: { 7461 value: 'onConfirm', 7462 action: () => { 7463 event.request.grant(event.request.getAccessibleResource()); 7464 } 7465 }, 7466 cancel: () => { 7467 event.request.deny(); 7468 } 7469 }) 7470 } 7471 }) 7472 } 7473 } 7474} 7475 7476``` 7477HTML file to be loaded: 7478 ```html 7479<!-- index.html --> 7480<!DOCTYPE html> 7481<html> 7482 <head> 7483 <meta charset="UTF-8"> 7484 </head> 7485 <body> 7486 <video id="video" width="400px" height="400px" autoplay="autoplay"> 7487 </video> 7488 <input type="button" title="HTML5 Camera" value="Enable Camera" onclick="getMedia()"/> 7489 <script> 7490 function getMedia() { 7491 let constraints = { 7492 video: { 7493 width: 500, 7494 height: 500 7495 }, 7496 audio: true 7497 } 7498 let video = document.getElementById("video"); 7499 let promise = navigator.mediaDevices.getUserMedia(constraints); 7500 promise.then(function(MediaStream) { 7501 video.srcObject = MediaStream; 7502 video.play(); 7503 }) 7504 } 7505 </script> 7506 </body> 7507</html> 7508 ``` 7509 7510### stopCamera<sup>12+</sup> 7511 7512stopCamera(): void 7513 7514Stops the camera capture of the current web page. 7515 7516**System capability**: SystemCapability.Web.Webview.Core 7517 7518**Error codes** 7519 7520For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7521 7522| ID| Error Message | 7523| -------- | ------------------------------------------------------------ | 7524| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7525 7526**Example** 7527 7528For the complete sample code, see [startCamera](#startcamera12). 7529 7530### closeCamera<sup>12+</sup> 7531 7532closeCamera(): void 7533 7534Disables the camera capture of the current web page. 7535 7536**System capability**: SystemCapability.Web.Webview.Core 7537 7538**Error codes** 7539 7540For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7541 7542| ID| Error Message | 7543| -------- | ------------------------------------------------------------ | 7544| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7545 7546**Example** 7547 7548For the complete sample code, see [startCamera](#startcamera12). 7549 7550### precompileJavaScript<sup>12+</sup> 7551 7552precompileJavaScript(url: string, script: string | Uint8Array, cacheOptions: CacheOptions): Promise\<number\> 7553 7554Precompiles JavaScript to generate the bytecode cache or update the existing bytecode cache based on the provided parameters. 7555The API determines whether to update the existing bytecode cache based on the provided file information, E-Tag response header, and Last-Modified response header. 7556 7557**System capability**: SystemCapability.Web.Webview.Core 7558 7559**Parameters** 7560 7561| Name | Type | Mandatory| Description | 7562| ------- | ------ | ---- | :-------------------- | 7563| 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. | 7564| script | string \| Uint8Array | Yes | Text content of the local JavaScript. The content cannot be empty. | 7565| cacheOptions | [CacheOptions](#cacheoptions12) | Yes | Whether to update the bytecode cache. | 7566 7567**Return value** 7568 7569| Type | Description | 7570| ----------------------------------- | --------------------------- | 7571| 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.| 7572 7573**Error codes** 7574 7575For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 7576 7577| ID| Error Message | 7578| -------- | ------------------------------------------------------------ | 7579| 401 | Invalid input parameter.Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | 7580| 17100001 | Init error. The WebviewController must be associated with a Web component. | 7581 7582**Example** 7583 7584The 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: 7585 75861. Save **UIContext** to localStorage in **EntryAbility**. 7587 7588 ```ts 7589 // EntryAbility.ets 7590 import { UIAbility } from '@kit.AbilityKit'; 7591 import { window } from '@kit.ArkUI'; 7592 7593 const localStorage: LocalStorage = new LocalStorage('uiContext'); 7594 7595 export default class EntryAbility extends UIAbility { 7596 storage: LocalStorage = localStorage; 7597 7598 onWindowStageCreate(windowStage: window.WindowStage) { 7599 windowStage.loadContent('pages/Index', this.storage, (err, data) => { 7600 if (err.code) { 7601 return; 7602 } 7603 7604 this.storage.setOrCreate<UIContext>("uiContext", windowStage.getMainWindowSync().getUIContext()); 7605 }); 7606 } 7607 } 7608 ``` 7609 76102. Write the basic code required by the dynamic component. 7611 7612 ```ts 7613 // DynamicComponent.ets 7614 import { NodeController, BuilderNode, FrameNode, UIContext } from '@kit.ArkUI'; 7615 7616 export interface BuilderData { 7617 url: string; 7618 controller: WebviewController; 7619 } 7620 7621 const storage = LocalStorage.getShared(); 7622 7623 export class NodeControllerImpl extends NodeController { 7624 private rootNode: BuilderNode<BuilderData[]> | null = null; 7625 private wrappedBuilder: WrappedBuilder<BuilderData[]> | null = null; 7626 7627 constructor(wrappedBuilder: WrappedBuilder<BuilderData[]>) { 7628 super(); 7629 this.wrappedBuilder = wrappedBuilder; 7630 } 7631 7632 makeNode(): FrameNode | null { 7633 if (this.rootNode != null) { 7634 return this.rootNode.getFrameNode(); 7635 } 7636 return null; 7637 } 7638 7639 initWeb(url: string, controller: WebviewController) { 7640 if(this.rootNode != null) { 7641 return; 7642 } 7643 7644 const uiContext: UIContext = storage.get<UIContext>("uiContext") as UIContext; 7645 if (!uiContext) { 7646 return; 7647 } 7648 this.rootNode = new BuilderNode(uiContext); 7649 this.rootNode.build(this.wrappedBuilder, { url: url, controller: controller }); 7650 } 7651 } 7652 7653 export const createNode = (wrappedBuilder: WrappedBuilder<BuilderData[]>, data: BuilderData) => { 7654 const baseNode = new NodeControllerImpl(wrappedBuilder); 7655 baseNode.initWeb(data.url, data.controller); 7656 return baseNode; 7657 } 7658 ``` 7659 76603. 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. 7661 7662 <!--code_no_check--> 7663 ```ts 7664 // PrecompileWebview.ets 7665 import { BuilderData } from "./DynamicComponent"; 7666 import { Config, configs } from "./PrecompileConfig"; 7667 7668 @Builder 7669 function WebBuilder(data: BuilderData) { 7670 Web({ src: data.url, controller: data.controller }) 7671 .onControllerAttached(() => { 7672 precompile(data.controller, configs); 7673 }) 7674 .fileAccess(true) 7675 } 7676 7677 export const precompileWebview = wrapBuilder<BuilderData[]>(WebBuilder); 7678 7679 export const precompile = async (controller: WebviewController, configs: Array<Config>) => { 7680 for (const config of configs) { 7681 let content = await readRawFile(config.localPath); 7682 7683 try { 7684 controller.precompileJavaScript(config.url, content, config.options) 7685 .then(errCode => { 7686 console.error("precompile successfully! " + errCode); 7687 }).catch((errCode: number) => { 7688 console.error("precompile failed. " + errCode); 7689 }); 7690 } catch (err) { 7691 console.error("precompile failed. " + err.code + " " + err.message); 7692 } 7693 } 7694 } 7695 7696 async function readRawFile(path: string) { 7697 try { 7698 return await getContext().resourceManager.getRawFileContent(path);; 7699 } catch (err) { 7700 return new Uint8Array(0); 7701 } 7702 } 7703 ``` 7704 7705JavaScript 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. 7706 77074. Compile the code of the service component. 7708 7709 <!--code_no_check--> 7710 ```ts 7711 // BusinessWebview.ets 7712 import { BuilderData } from "./DynamicComponent"; 7713 7714 @Builder 7715 function WebBuilder(data: BuilderData) { 7716 // The component can be extended based on service requirements. 7717 Web({ src: data.url, controller: data.controller }) 7718 .cacheMode(CacheMode.Default) 7719 } 7720 7721 export const businessWebview = wrapBuilder<BuilderData[]>(WebBuilder); 7722 ``` 7723 77245. Write the resource configuration information. 7725 7726 ```ts 7727 // PrecompileConfig.ets 7728 import { webview } from '@kit.ArkWeb' 7729 7730 export interface Config { 7731 url: string, 7732 localPath: string, // Local resource path 7733 options: webview.CacheOptions 7734 } 7735 7736 export let configs: Array<Config> = [ 7737 { 7738 url: "https://www.example.com/example.js", 7739 localPath: "example.js", 7740 options: { 7741 responseHeaders: [ 7742 { headerKey: "E-Tag", headerValue: "aWO42N9P9dG/5xqYQCxsx+vDOoU="}, 7743 { headerKey: "Last-Modified", headerValue: "Wed, 21 Mar 2024 10:38:41 GMT"} 7744 ] 7745 } 7746 } 7747 ] 7748 ``` 7749 77506. Use the component on the page. 7751 7752 <!--code_no_check--> 7753 ```ts 7754 // Index.ets 7755 import { webview } from '@kit.ArkWeb'; 7756 import { NodeController } from '@kit.ArkUI'; 7757 import { createNode } from "./DynamicComponent" 7758 import { precompileWebview } from "./PrecompileWebview" 7759 import { businessWebview } from "./BusinessWebview" 7760 7761 @Entry 7762 @Component 7763 struct Index { 7764 @State precompileNode: NodeController | undefined = undefined; 7765 precompileController: webview.WebviewController = new webview.WebviewController(); 7766 7767 @State businessNode: NodeController | undefined = undefined; 7768 businessController: webview.WebviewController = new webview.WebviewController(); 7769 7770 aboutToAppear(): void { 7771 // Initialize the Web component used to inject local resources. 7772 this.precompileNode = createNode(precompileWebview, 7773 { url: "https://www.example.com/empty.html", controller: this.precompileController}); 7774 } 7775 7776 build() { 7777 Column() { 7778 // Load the Web component used by the service at a proper time. In this example, the button is clicked. 7779 Button ("Load Page") 7780 .onClick(() => { 7781 this.businessNode = createNode(businessWebview, { 7782 url: "https://www.example.com/business.html", 7783 controller: this.businessController 7784 }); 7785 }) 7786 // The Web component used for the service. 7787 NodeContainer(this.businessNode); 7788 } 7789 } 7790 } 7791 ``` 7792 7793To 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. 7794 7795### onCreateNativeMediaPlayer<sup>12+</sup> 7796 7797onCreateNativeMediaPlayer(callback: CreateNativeMediaPlayerCallback): void 7798 7799Called 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. 7800If the application does not take over media playback on the web page, this callback is not invoked. 7801 7802**System capability**: SystemCapability.Web.Webview.Core 7803 7804**Parameters** 7805 7806| Name| Type| Mandatory| Description| 7807|--------|------|------|------| 7808| callback | [CreateNativeMediaPlayerCallback](#createnativemediaplayercallback12) | Yes| Callback when the application takes over media playback on the web page.| 7809 7810**Example** 7811 7812```ts 7813// xxx.ets 7814import { webview } from '@kit.ArkWeb'; 7815 7816class ActualNativeMediaPlayerListener { 7817 handler: webview.NativeMediaPlayerHandler; 7818 7819 constructor(handler: webview.NativeMediaPlayerHandler) { 7820 this.handler = handler; 7821 } 7822 7823 onPlaying() { 7824 // The native media player starts playback. 7825 this.handler.handleStatusChanged(webview.PlaybackStatus.PLAYING); 7826 } 7827 onPaused() { 7828 // The native media player pauses the playback. 7829 this.handler.handleStatusChanged(webview.PlaybackStatus.PAUSED); 7830 } 7831 onSeeking() { 7832 // The local player starts to jump to the target time point. 7833 this.handler.handleSeeking(); 7834 } 7835 onSeekDone() { 7836 // The native media player seeks to the target time point. 7837 this.handler.handleSeekFinished(); 7838 } 7839 onEnded() { 7840 // The playback on the native media player is ended. 7841 this.handler.handleEnded(); 7842 } 7843 onVolumeChanged() { 7844 // Obtain the volume of the local player. 7845 let volume: number = getVolume(); 7846 this.handler.handleVolumeChanged(volume); 7847 } 7848 onCurrentPlayingTimeUpdate() { 7849 // Update the playback time. 7850 let currentTime: number = getCurrentPlayingTime(); 7851 // Convert the time unit to second. 7852 let currentTimeInSeconds = convertToSeconds(currentTime); 7853 this.handler.handleTimeUpdate(currentTimeInSeconds); 7854 } 7855 onBufferedChanged() { 7856 // The cache is changed. 7857 // Obtain the cache duration of the native media player. 7858 let bufferedEndTime: number = getCurrentBufferedTime(); 7859 // Convert the time unit to second. 7860 let bufferedEndTimeInSeconds = convertToSeconds(bufferedEndTime); 7861 this.handler.handleBufferedEndTimeChanged(bufferedEndTimeInSeconds); 7862 7863 // Check the cache status. 7864 // If the cache status changes, notify the ArkWeb engine of the cache status. 7865 let lastReadyState: webview.ReadyState = getLastReadyState(); 7866 let currentReadyState: webview.ReadyState = getCurrentReadyState(); 7867 if (lastReadyState != currentReadyState) { 7868 this.handler.handleReadyStateChanged(currentReadyState); 7869 } 7870 } 7871 onEnterFullscreen() { 7872 // The native media player enters the full screen mode. 7873 let isFullscreen: boolean = true; 7874 this.handler.handleFullscreenChanged(isFullscreen); 7875 } 7876 onExitFullscreen() { 7877 // The native media player exits the full screen mode. 7878 let isFullscreen: boolean = false; 7879 this.handler.handleFullscreenChanged(isFullscreen); 7880 } 7881 onUpdateVideoSize(width: number, height: number) { 7882 // Notify the ArkWeb kernel when the native media player parses the video width and height. 7883 this.handler.handleVideoSizeChanged(width, height); 7884 } 7885 onDurationChanged(duration: number) { 7886 // Notify the ArkWeb kernel when the native media player parses the video duration. 7887 this.handler.handleDurationChanged(duration); 7888 } 7889 onError(error: webview.MediaError, errorMessage: string) { 7890 // Notify the ArkWeb kernel that an error occurs in the native media player. 7891 this.handler.handleError(error, errorMessage); 7892 } 7893 onNetworkStateChanged(state: webview.NetworkState) { 7894 // Notify the ArkWeb kernel that the network state of the native media player changes. 7895 this.handler.handleNetworkStateChanged(state); 7896 } 7897 onPlaybackRateChanged(playbackRate: number) { 7898 // Notify the ArkWeb kernel that the playback rate of the native media player changes. 7899 this.handler.handlePlaybackRateChanged(playbackRate); 7900 } 7901 onMutedChanged(muted: boolean) { 7902 // Notify the ArkWeb kernel that the native media player is muted. 7903 this.handler.handleMutedChanged(muted); 7904 } 7905 7906 // Listen for other state of the native media player. 7907} 7908 7909class NativeMediaPlayerImpl implements webview.NativeMediaPlayerBridge { 7910 constructor(handler: webview.NativeMediaPlayerHandler, mediaInfo: webview.MediaInfo) { 7911 // 1. Create a listener for the native media player. 7912 let listener: ActualNativeMediaPlayerListener = new ActualNativeMediaPlayerListener(handler); 7913 // 2. Create a native media player. 7914 // 3. Listen for the local player. 7915 // ... 7916 } 7917 7918 updateRect(x: number, y: number, width: number, height: number) { 7919 // The position and size of the <video> tag are changed. 7920 // Make changes based on the information change. 7921 } 7922 7923 play() { 7924 // Start the native media player for playback. 7925 } 7926 7927 pause() { 7928 //Pause the playback on the local player. 7929 } 7930 7931 seek(targetTime: number) { 7932 // The local player jumps to a specified time point. 7933 } 7934 7935 release() { 7936 // Destroy the local player. 7937 } 7938 7939 setVolume(volume: number) { 7940 // The ArkWeb kernel requires to adjust the volume of the local player. 7941 // Set the volume of the local player. 7942 } 7943 7944 setMuted(muted: boolean) { 7945 // Mute or unmute the local player. 7946 } 7947 7948 setPlaybackRate(playbackRate: number) { 7949 // Adjust the playback speed of the local player. 7950 } 7951 7952 enterFullscreen() { 7953 // Set the local player to play in full screen mode. 7954 } 7955 7956 exitFullscreen() { 7957 // Set the local player to exit full screen mode. 7958 } 7959 7960 resumePlayer() { 7961 // Create a player again. 7962 // Resume the status information of the player. 7963 } 7964 7965 suspendPlayer(type: webview.SuspendType) { 7966 // Record the status information of the player. 7967 // Destroy the player. 7968 } 7969} 7970 7971@Entry 7972@Component 7973struct WebComponent { 7974 controller: webview.WebviewController = new webview.WebviewController() 7975 build() { 7976 Column() { 7977 Web({ src: 'www.example.com', controller: this.controller }) 7978 .enableNativeMediaPlayer({enable: true, shouldOverlay: false}) 7979 .onPageBegin((event) => { 7980 this.controller.onCreateNativeMediaPlayer((handler: webview.NativeMediaPlayerHandler, mediaInfo: webview.MediaInfo) => { 7981 if (!shouldHandle(mediaInfo)) { 7982 // The local player does not take over the media. 7983 // The ArkWeb engine will play the media with its own player. 7984 return null; 7985 } 7986 let nativePlayer: webview.NativeMediaPlayerBridge = new NativeMediaPlayerImpl(handler, mediaInfo); 7987 return nativePlayer; 7988 }); 7989 }) 7990 } 7991 } 7992} 7993 7994// stub 7995function getVolume() { 7996 return 1; 7997} 7998function getCurrentPlayingTime() { 7999 return 1; 8000} 8001function getCurrentBufferedTime() { 8002 return 1; 8003} 8004function convertToSeconds(input: number) { 8005 return input; 8006} 8007function getLastReadyState() { 8008 return webview.ReadyState.HAVE_NOTHING; 8009} 8010function getCurrentReadyState() { 8011 return webview.ReadyState.HAVE_NOTHING; 8012} 8013function shouldHandle(mediaInfo: webview.MediaInfo) { 8014 return true; 8015} 8016``` 8017 8018### enableWholeWebPageDrawing<sup>12+</sup> 8019 8020static enableWholeWebPageDrawing(): void 8021 8022Enables the full drawing capability for the web page. This API works only during **Web** component initialization. 8023 8024**System capability**: SystemCapability.Web.Webview.Core 8025 8026**Example** 8027 8028```ts 8029// xxx.ets 8030import { webview } from '@kit.ArkWeb'; 8031import { BusinessError } from '@kit.BasicServicesKit'; 8032 8033@Entry 8034@Component 8035struct WebComponent { 8036 controller: webview.WebviewController = new webview.WebviewController(); 8037 8038 aboutToAppear(): void { 8039 try { 8040 webview.WebviewController.enableWholeWebPageDrawing(); 8041 } catch (error) { 8042 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8043 } 8044 } 8045 8046 build() { 8047 Column() { 8048 Web({ src: 'www.example.com', controller: this.controller }) 8049 } 8050 } 8051} 8052``` 8053 8054### webPageSnapshot<sup>12+</sup> 8055 8056webPageSnapshot(info: SnapshotInfo, callback: AsyncCallback\<SnapshotResult>): void 8057 8058Obtains the full drawing result of the web page. 8059 8060**System capability**: SystemCapability.Web.Webview.Core 8061 8062**Parameters** 8063 8064| Name | Type | Mandatory | Description | 8065| ----------- | ------------- | ---- | ------------------------ | 8066| info | [SnapshotInfo](#snapshotinfo12)| Yes | Information for obtaining the full drawing result.| 8067| callback | [SnapshotResult](#snapshotresult12)| Yes | Callback used to return the result.| 8068 8069**Example** 8070 8071```ts 8072// xxx.ets 8073import { webview } from '@kit.ArkWeb'; 8074import { BusinessError } from '@kit.BasicServicesKit'; 8075 8076@Entry 8077@Component 8078struct WebComponent { 8079 controller: webview.WebviewController = new webview.WebviewController(); 8080 8081 build() { 8082 Column() { 8083 Button('webPageSnapshot') 8084 .onClick(() => { 8085 try { 8086 this.controller.webPageSnapshot({ id: "1234", size: { width: 100, height: 100 } }, (error, result) => { 8087 if (error) { 8088 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8089 return; 8090 } 8091 if (result) { 8092 console.info(`return value is:${result}`); 8093 // You can process the returned result as required. 8094 } 8095 }); 8096 } catch (error) { 8097 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8098 } 8099 }) 8100 Web({ src: 'www.example.com', controller: this.controller }) 8101 } 8102 } 8103} 8104``` 8105 8106### injectOfflineResources<sup>12+</sup> 8107 8108injectOfflineResources(resourceMaps: Array\<[OfflineResourceMap](#offlineresourcemap12)\>): void 8109 8110Injects local offline resources to the memory cache to improve the initial page startup speed. 8111Resources 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. 8112Under 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. 8113The 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. 8114Resources 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. 8115After **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. 8116 8117**System capability**: SystemCapability.Web.Webview.Core 8118 8119**Parameters** 8120 8121| Name | Type | Mandatory| Description | 8122| ------- | ------ | ---- | :-------------------- | 8123| 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. | 8124 8125**Error codes** 8126 8127For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8128 8129| ID| Error Message | 8130| -------- | ------------------------------------------------------------ | 8131| 401 | Invalid input parameter.Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | 8132| 17100001 | Init error. The WebviewController must be associated with a Web component. | 8133| 17100002 | Invalid url. | 8134 8135**Example** 8136 8137When 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: 81381. Save **UIContext** to localStorage in **EntryAbility**. 8139 8140 ```ts 8141 // EntryAbility.ets 8142 import { UIAbility } from '@kit.AbilityKit'; 8143 import { window } from '@kit.ArkUI'; 8144 8145 const localStorage: LocalStorage = new LocalStorage('uiContext'); 8146 8147 export default class EntryAbility extends UIAbility { 8148 storage: LocalStorage = localStorage; 8149 8150 onWindowStageCreate(windowStage: window.WindowStage) { 8151 windowStage.loadContent('pages/Index', this.storage, (err, data) => { 8152 if (err.code) { 8153 return; 8154 } 8155 8156 this.storage.setOrCreate<UIContext>("uiContext", windowStage.getMainWindowSync().getUIContext()); 8157 }); 8158 } 8159 } 8160 ``` 8161 81622. Write the basic code required by the dynamic component. 8163 8164 ```ts 8165 // DynamicComponent.ets 8166 import { NodeController, BuilderNode, FrameNode, UIContext } from '@kit.ArkUI'; 8167 8168 export interface BuilderData { 8169 url: string; 8170 controller: WebviewController; 8171 } 8172 8173 const storage = LocalStorage.getShared(); 8174 8175 export class NodeControllerImpl extends NodeController { 8176 private rootNode: BuilderNode<BuilderData[]> | null = null; 8177 private wrappedBuilder: WrappedBuilder<BuilderData[]> | null = null; 8178 8179 constructor(wrappedBuilder: WrappedBuilder<BuilderData[]>) { 8180 super(); 8181 this.wrappedBuilder = wrappedBuilder; 8182 } 8183 8184 makeNode(): FrameNode | null { 8185 if (this.rootNode != null) { 8186 return this.rootNode.getFrameNode(); 8187 } 8188 return null; 8189 } 8190 8191 initWeb(url: string, controller: WebviewController) { 8192 if(this.rootNode != null) { 8193 return; 8194 } 8195 8196 const uiContext: UIContext = storage.get<UIContext>("uiContext") as UIContext; 8197 if (!uiContext) { 8198 return; 8199 } 8200 this.rootNode = new BuilderNode(uiContext); 8201 this.rootNode.build(this.wrappedBuilder, { url: url, controller: controller }); 8202 } 8203 } 8204 8205 export const createNode = (wrappedBuilder: WrappedBuilder<BuilderData[]>, data: BuilderData) => { 8206 const baseNode = new NodeControllerImpl(wrappedBuilder); 8207 baseNode.initWeb(data.url, data.controller); 8208 return baseNode; 8209 } 8210 ``` 8211 82123. 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. 8213 8214 <!--code_no_check--> 8215 ```ts 8216 // InjectWebview.ets 8217 import { webview } from '@kit.ArkWeb'; 8218 import { resourceConfigs } from "./Resource"; 8219 import { BuilderData } from "./DynamicComponent"; 8220 8221 @Builder 8222 function WebBuilder(data: BuilderData) { 8223 Web({ src: data.url, controller: data.controller }) 8224 .onControllerAttached(async () => { 8225 try { 8226 data.controller.injectOfflineResources(await getData ()); 8227 } catch (err) { 8228 console.error("error: " + err.code + " " + err.message); 8229 } 8230 }) 8231 .fileAccess(true) 8232 } 8233 8234 export const injectWebview = wrapBuilder<BuilderData[]>(WebBuilder); 8235 8236 export async function getData() { 8237 const resourceMapArr: Array<webview.OfflineResourceMap> = []; 8238 8239 // Read the configuration and read the file content from the rawfile directory. 8240 for (let config of resourceConfigs) { 8241 let buf: Uint8Array = new Uint8Array(0); 8242 if (config.localPath) { 8243 buf = await readRawFile(config.localPath); 8244 } 8245 8246 resourceMapArr.push({ 8247 urlList: config.urlList, 8248 resource: buf, 8249 responseHeaders: config.responseHeaders, 8250 type: config.type, 8251 }) 8252 } 8253 8254 return resourceMapArr; 8255 } 8256 8257 export async function readRawFile(url: string) { 8258 try { 8259 return await getContext().resourceManager.getRawFileContent(url); 8260 } catch (err) { 8261 return new Uint8Array(0); 8262 } 8263 } 8264 ``` 8265 82664. Compile the code of the service component. 8267 8268 <!--code_no_check--> 8269 ```ts 8270 // BusinessWebview.ets 8271 import { BuilderData } from "./DynamicComponent"; 8272 8273 @Builder 8274 function WebBuilder(data: BuilderData) { 8275 // The component can be extended based on service requirements. 8276 Web({ src: data.url, controller: data.controller }) 8277 .cacheMode(CacheMode.Default) 8278 } 8279 8280 export const businessWebview = wrapBuilder<BuilderData[]>(WebBuilder); 8281 ``` 8282 82835. Write the resource configuration information. 8284 8285 ```ts 8286 // Resource.ets 8287 import { webview } from '@kit.ArkWeb'; 8288 8289 export interface ResourceConfig { 8290 urlList: Array<string>, 8291 type: webview.OfflineResourceType, 8292 responseHeaders: Array<Header>, 8293 localPath: string, // Path for storing local resources in the rawfile directory. 8294 } 8295 8296 export const resourceConfigs: Array<ResourceConfig> = [ 8297 { 8298 localPath: "example.png", 8299 urlList: [ 8300 "https://www.example.com/", 8301 "https://www.example.com/path1/example.png", 8302 "https://www.example.com/path2/example.png", 8303 ], 8304 type: webview.OfflineResourceType.IMAGE, 8305 responseHeaders: [ 8306 { headerKey: "Cache-Control", headerValue: "max-age=1000" }, 8307 { headerKey: "Content-Type", headerValue: "image/png" }, 8308 ] 8309 }, 8310 { 8311 localPath: "example.js", 8312 urlList: [ // Only one URL is provided. This URL is used as both the resource origin and the network request address of the resource. 8313 "https://www.example.com/example.js", 8314 ], 8315 type: webview.OfflineResourceType.CLASSIC_JS, 8316 responseHeaders: [ 8317 // Used in <script crossorigin="anonymous" /> mode to provide additional response headers. 8318 { headerKey: "Cross-Origin", headerValue:"anonymous" } 8319 ] 8320 }, 8321 ]; 8322 ``` 8323 83246. Use the component on the page. 8325 <!--code_no_check--> 8326 ```ts 8327 // Index.ets 8328 import { webview } from '@kit.ArkWeb'; 8329 import { NodeController } from '@kit.ArkUI'; 8330 import { createNode } from "./DynamicComponent" 8331 import { injectWebview } from "./InjectWebview" 8332 import { businessWebview } from "./BusinessWebview" 8333 8334 @Entry 8335 @Component 8336 struct Index { 8337 @State injectNode: NodeController | undefined = undefined; 8338 injectController: webview.WebviewController = new webview.WebviewController(); 8339 8340 @State businessNode: NodeController | undefined = undefined; 8341 businessController: webview.WebviewController = new webview.WebviewController(); 8342 8343 aboutToAppear(): void { 8344 // Initialize the Web component used to inject local resources and provide an empty HTML page as the URL. 8345 this.injectNode = createNode(injectWebview, 8346 { url: "https://www.example.com/empty.html", controller: this.injectController}); 8347 } 8348 8349 build() { 8350 Column() { 8351 // Load the Web component used by the service at a proper time. In this example, the button is clicked. 8352 Button ("Load Page") 8353 .onClick(() => { 8354 this.businessNode = createNode(businessWebview, { 8355 url: "https://www.example.com/business.html", 8356 controller: this.businessController 8357 }); 8358 }) 8359 // The Web component used for the service. 8360 NodeContainer(this.businessNode); 8361 } 8362 } 8363 } 8364 ``` 8365 83667. Example of a loaded HTML web page: 8367 8368 ```HTML 8369 <!DOCTYPE html> 8370 <html lang="en"> 8371 <head></head> 8372 <body> 8373 <img src="https://www.example.com/path1/request.png" /> 8374 <img src="https://www.example.com/path2/request.png" /> 8375 <script src="https://www.example.com/example.js" crossorigin="anonymous"></script> 8376 </body> 8377 </html> 8378 ``` 8379 8380### setHostIP<sup>12+</sup> 8381 8382static setHostIP(hostName: string, address: string, aliveTime: number): void 8383 8384Sets the IP address of the host after domain name resolution. 8385 8386**System capability**: SystemCapability.Web.Webview.Core 8387 8388**Parameters** 8389 8390| Name | Type| Mandatory| Description | 8391| --------- | -------- | ---- | ------------------------------------ | 8392| hostName | string | Yes | Domain name of the host whose DNS records are to be added. | 8393| address | string | Yes | Host domain name resolution address (IPv4 and IPv6).| 8394| aliveTime | number | Yes | Cache validity period, in seconds. | 8395 8396**Error codes** 8397 8398For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8399 8400| ID| Error Message | 8401| -------- | ------------------------ | 8402| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | 8403 8404**Example** 8405 8406For details, see [clearHostIP](#clearhostip12). 8407 8408### clearHostIP<sup>12+</sup> 8409 8410static clearHostIP(hostName: string): void 8411 8412Clears the IP address of a specified host after domain name resolution. 8413 8414**System capability**: SystemCapability.Web.Webview.Core 8415 8416**Parameters** 8417 8418| Name | Type| Mandatory| Description | 8419| -------- | -------- | ---- | ------------------------- | 8420| hostName | string | Yes | Domain name of the host whose DNS records are to be cleared.| 8421 8422**Error codes** 8423 8424For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8425 8426| ID| Error Message | 8427| -------- | ------------------------ | 8428| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | 8429 8430**Example** 8431 8432```ts 8433// xxx.ets 8434import { webview } from '@kit.ArkWeb'; 8435import { BusinessError } from '@kit.BasicServicesKit'; 8436 8437@Entry 8438@Component 8439struct WebComponent { 8440 controller: webview.WebviewController = new webview.WebviewController(); 8441 8442 build() { 8443 Column() { 8444 // The setting takes effect before the URL is loaded. 8445 Button('setHostIP') 8446 .onClick(() => { 8447 try { 8448 webview.WebviewController.setHostIP('www.example.com', '127.0.0.1', 30); 8449 } catch (error) { 8450 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8451 } 8452 }) 8453 Button('clearHostIP') 8454 .onClick(() => { 8455 try { 8456 webview.WebviewController.clearHostIP('www.example.com'); 8457 } catch (error) { 8458 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8459 } 8460 }) 8461 Web({ src: 'www.example.com', controller: this.controller }) 8462 } 8463 } 8464} 8465``` 8466 8467### getSurfaceId<sup>12+</sup> 8468 8469getSurfaceId(): string 8470 8471Obtains 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. 8472 8473**System capability**: SystemCapability.Web.Webview.Core 8474 8475**Return value** 8476 8477| Type | Description | 8478| ------ | ------------------- | 8479| string | ID of the surface held by ArkWeb.| 8480 8481**Example** 8482 8483```ts 8484// xxx.ets 8485import { webview } from '@kit.ArkWeb'; 8486import { image } from '@kit.ImageKit'; 8487import { BusinessError } from '@kit.BasicServicesKit'; 8488 8489@Entry 8490@Component 8491struct Example{ 8492 controller: webview.WebviewController = new webview.WebviewController(); 8493 8494 @State imagePixelMap: image.PixelMap | undefined = undefined; 8495 8496 build(){ 8497 Column(){ 8498 Button ("Screenshot") 8499 .onClick(()=>{ 8500 try { 8501 let surfaceId = this.controller.getSurfaceId(); 8502 console.log("surfaceId: " + surfaceId); 8503 if(surfaceId.length != 0) { 8504 let region:image.Region = { x: 0, y: 0, size: { height: 800, width: 1000}} 8505 this.imagePixelMap = image.createPixelMapFromSurfaceSync(surfaceId, region) 8506 } 8507 } catch (error) { 8508 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8509 } 8510 }) 8511 Image(this.imagePixelMap) 8512 .height(100) 8513 Web({src: 'www.example.com', controller: this.controller}) 8514 } 8515 } 8516} 8517``` 8518 8519### setUrlTrustList<sup>12+</sup> 8520 8521setUrlTrustList(urlTrustList: string): void 8522 8523Sets 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. 8524 8525**System capability**: SystemCapability.Web.Webview.Core 8526 8527**Parameters** 8528 8529| Name | Type | Mandatory| Description | 8530| ------- | ------ | ---- | :-------------------- | 8531| 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>} | 8532 8533**Parameters in JSON format**: 8534| Name | Type| Mandatory| Description | 8535| -------- | -------- | ---- | ------------------------- | 8536| scheme | string | No| Optional parameter. The supported protocols are HTTP and HTTPS.| 8537| 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.| 8538| port | number | No| Optional parameter.| 8539| 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.| 8540 8541**Error codes** 8542 8543For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8544 8545| ID| Error Message | 8546| -------- | ------------------------------------------------------------ | 8547| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified.2. Parameter string is too long.3. Parameter verification failed. | 8548| 17100001 | Init error. The WebviewController must be associated with a Web component. | 8549 8550**Example** 8551 ```ts 8552 // xxx.ets 8553 import { webview } from '@kit.ArkWeb'; 8554 import { BusinessError } from '@kit.BasicServicesKit'; 8555 8556 @Entry 8557 @Component 8558 struct WebComponent { 8559 controller: webview.WebviewController = new webview.WebviewController(); 8560 urltrustList: string = "{\"UrlPermissionList\":[{\"scheme\":\"http\", \"host\":\"trust.example.com\", \"port\":80, \"path\":\"test\"}]}" 8561 8562 build() { 8563 Column() { 8564 Button('Setting the trustlist') 8565 .onClick(() => { 8566 try { 8567 // Set a trustlist to allow access only to trust web pages. 8568 this.controller.setUrlTrustList(this.urltrustList); 8569 } catch (error) { 8570 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8571 } 8572 }) 8573 Button('Cancel the trustlist.') 8574 .onClick(() => { 8575 try { 8576 // Input an empty string to setUrlTrustList() to disable the trustlist, and all URLs can be accessed. 8577 this.controller.setUrlTrustList(""); 8578 } catch (error) { 8579 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8580 } 8581 }) 8582 Button('Access the trust web') 8583 .onClick(() => { 8584 try { 8585 // The trustlist is enabled and trust web pages can be accessed. 8586 this.controller.loadUrl('http://trust.example.com/test'); 8587 } catch (error) { 8588 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8589 } 8590 }) 8591 Button('Access the untrust web') 8592 .onClick(() => { 8593 try { 8594 // The trustlist is enabled that untrust web pages cannot be accessed and an error page is displayed. 8595 this.controller.loadUrl('http://untrust.example.com/test'); 8596 } catch (error) { 8597 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8598 } 8599 }) 8600 Web({ src: 'http://untrust.example.com/test', controller: this.controller }).onControllerAttached(() => { 8601 try { 8602 // 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. 8603 this.controller.setUrlTrustList(this.urltrustList); 8604 } catch (error) { 8605 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8606 } 8607 }) 8608 } 8609 } 8610 } 8611 ``` 8612 8613### setPathAllowingUniversalAccess<sup>12+</sup> 8614 8615setPathAllowingUniversalAccess(pathList: Array\<string\>): void 8616 8617Sets 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: 8618 86191. 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: 8620 8621* /data/storage/el2/base/files/example 8622* /data/storage/el2/base/haps/entry/files/example 8623 86242. 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: 8625 8626* /data/storage/el1/bundle/entry/resource/resfile 8627* /data/storage/el1/bundle/entry/resource/resfile/example 8628 8629If 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). 8630 8631**System capability**: SystemCapability.Web.Webview.Core 8632 8633**Parameters** 8634 8635| Name | Type| Mandatory| Description | 8636| -------- | -------- | ---- | ------------------------- | 8637| pathList | Array\<string\> | Yes | The path list.| 8638 8639**Error codes** 8640 8641For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8642 8643| ID| Error Message | 8644| -------- | ------------------------ | 8645| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Parameter string is too long. 3.Parameter verification failed. | 8646| 17100001 | Init error. The WebviewController must be associated with a Web component. | 8647 8648**Example** 8649 8650```ts 8651// xxx.ets 8652import { webview } from '@kit.ArkWeb'; 8653import { BusinessError } from '@kit.BasicServicesKit'; 8654 8655@Entry 8656@Component 8657struct WebComponent { 8658 controller: WebviewController = new webview.WebviewController(); 8659 8660 build() { 8661 Row() { 8662 Web({ src: "", controller: this.controller }) 8663 .onControllerAttached(() => { 8664 try { 8665 // Set the list of paths that can be accessed across domains. 8666 this.controller.setPathAllowingUniversalAccess([ 8667 getContext().resourceDir, 8668 getContext().filesDir + "/example" 8669 ]) 8670 this.controller.loadUrl("file://" + getContext().resourceDir + "/index.html") 8671 } catch (error) { 8672 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8673 } 8674 }) 8675 .javaScriptAccess(true) 8676 .fileAccess(true) 8677 .domStorageAccess(true) 8678 } 8679 } 8680} 8681 8682``` 8683 8684Load the HTML file in the application resource directory **resource/resfile/index.html**. 8685```html 8686<!-- index.html --> 8687<!DOCTYPE html> 8688<html lang="en"> 8689 8690<head> 8691 <meta charset="utf-8"> 8692 <title>Demo</title> 8693 <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, viewport-fit=cover"> 8694 <script> 8695 function getFile() { 8696 var file = "file:///data/storage/el1/bundle/entry/resources/resfile/js/script.js"; 8697 var xmlHttpReq = new XMLHttpRequest(); 8698 xmlHttpReq.onreadystatechange = function(){ 8699 console.log("readyState:" + xmlHttpReq.readyState); 8700 console.log("status:" + xmlHttpReq.status); 8701 if(xmlHttpReq.readyState == 4){ 8702 if (xmlHttpReq.status == 200) { 8703 // If the path list is set on the eTS, resources can be obtained. 8704 const element = document.getElementById('text'); 8705 element.textContent = "load " + file + " success"; 8706 } else { 8707 // If the path list is not set on the eTS, a CORS error is triggered. 8708 const element = document.getElementById('text'); 8709 element.textContent = "load " + file + " failed"; 8710 } 8711 } 8712 } 8713 xmlHttpReq.open("GET", file); 8714 xmlHttpReq.send(null); 8715 } 8716 8717 </script> 8718</head> 8719 8720<body> 8721<div class="page"> 8722 <button id="example" onclick="getFile()">stealFile</button> 8723</div> 8724<div id="text"></div> 8725</body> 8726 8727</html> 8728``` 8729 8730In 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**. 8731<!--code_no_check--> 8732```javascript 8733const body = document.body; 8734const element = document.createElement('div'); 8735element.textContent = 'success'; 8736body.appendChild(element); 8737``` 8738 8739### enableBackForwardCache<sup>12+</sup> 8740 8741static enableBackForwardCache(features: BackForwardCacheSupportedFeatures): void 8742 8743Enables the back-forward cache of a **Web** component. You can specify whether to add a specific page to the back-forward cache. 8744 8745This API must be called before [initializeWebEngine()](#initializewebengine) initializes the kernel. 8746 8747**System capability**: SystemCapability.Web.Webview.Core 8748 8749**Parameters** 8750 8751| Name | Type | Mandatory | Description | 8752| ---------------| ------- | ---- | ------------- | 8753| features | [BackForwardCacheSupportedFeatures](#backforwardcachesupportedfeatures12) | Yes | Features of the pages, which allow them to be added to the back-forward cache.| 8754 8755**Example** 8756 8757```ts 8758// EntryAbility.ets 8759import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 8760import { hilog } from '@kit.PerformanceAnalysisKit'; 8761import { window } from '@kit.ArkUI'; 8762import { webview } from '@kit.ArkWeb'; 8763 8764export default class EntryAbility extends UIAbility { 8765 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 8766 let features = new webview.BackForwardCacheSupportedFeatures(); 8767 features.nativeEmbed = true; 8768 features.mediaTakeOver = true; 8769 // 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. 8770 8771 webview.WebviewController.enableBackForwardCache(features); 8772 webview.WebviewController.initializeWebEngine(); 8773 AppStorage.setOrCreate("abilityWant", want); 8774 } 8775} 8776``` 8777 8778### setBackForwardCacheOptions<sup>12+</sup> 8779 8780setBackForwardCacheOptions(options: BackForwardCacheOptions): void 8781 8782Sets the back-forward cache options of the **Web** component. 8783 8784**System capability**: SystemCapability.Web.Webview.Core 8785 8786**Parameters** 8787 8788| Name | Type | Mandatory | Description | 8789| ---------------| ------- | ---- | ------------- | 8790| options | [BackForwardCacheOptions](#backforwardcacheoptions12) | Yes | Options to control the back-forward cache of the **Web** component.| 8791 8792**Error codes** 8793 8794For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8795 8796| ID| Error Message | 8797| -------- | ------------------------------------------------------------ | 8798| 17100001 | Init error. The WebviewController must be associated with a Web component. | 8799 8800**Example** 8801 8802```ts 8803// xxx.ts 8804import { webview } from '@kit.ArkWeb'; 8805 8806@Entry 8807@Component 8808struct Index { 8809 controller: webview.WebviewController = new webview.WebviewController(); 8810 8811 build() { 8812 Column() { 8813 Row() { 8814 Button("Add options").onClick((event: ClickEvent) => { 8815 let options = new webview.BackForwardCacheOptions(); 8816 options.size = 3; 8817 options.timeToLive = 10; 8818 this.controller.setBackForwardCacheOptions(options); 8819 }) 8820 Button("Backward").onClick((event: ClickEvent) => { 8821 this.controller.backward(); 8822 }) 8823 Button("Forward").onClick((event: ClickEvent) => { 8824 this.controller.forward(); 8825 }) 8826 } 8827 Web({ src: "https://www.example.com", controller: this.controller }) 8828 } 8829 .height('100%') 8830 .width('100%') 8831 } 8832} 8833``` 8834 8835### trimMemoryByPressureLevel<sup>14+</sup> 8836 8837trimMemoryByPressureLevel(level: PressureLevel): void 8838 8839Clears the cache occupied by **Web** component based on the specified memory pressure level. 8840 8841**System capability**: SystemCapability.Web.Webview.Core 8842 8843**Parameters** 8844 8845| Name | Type | Mandatory| Description | 8846| ------- | ------ | ---- | :-------------------- | 8847| level | [PressureLevel](#pressurelevel14) | Yes| Pressure level of the memory to be cleared.| 8848 8849**Error codes** 8850 8851For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8852 8853| ID| Error Message | 8854| -------- | ------------------------------------------------------------ | 8855| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Parameter string is too long. 3.Parameter verification failed. | 8856 8857**Example** 8858```ts 8859// xxx.ets 8860import { webview } from '@kit.ArkWeb'; 8861import { BusinessError } from '@kit.BasicServicesKit'; 8862 8863@Entry 8864@Component 8865struct WebComponent { 8866 controller: WebviewController = new webview.WebviewController(); 8867 build() { 8868 Column() { 8869 Row() { 8870 Button('trim_Memory') 8871 .onClick(() => { 8872 try { 8873 // Set the current memory pressure level to moderate and release a small amount of memory. 8874 webview.WebviewController.trimMemoryByPressureLevel( 8875 webview.PressureLevel.MEMORY_PRESSURE_LEVEL_MODERATE); 8876 } catch (error) { 8877 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8878 } 8879 }) 8880 }.height('10%') 8881 Web({ src: 'www.example.com', controller: this.controller }) 8882 } 8883 } 8884} 8885``` 8886 8887### createPdf<sup>14+</sup> 8888 8889createPdf(configuration: PdfConfiguration, callback: AsyncCallback\<PdfData\>): void 8890 8891Obtains the data stream of a specified web page using an asynchronous callback. 8892 8893**System capability**: SystemCapability.Web.Webview.Core 8894 8895**Parameters** 8896 8897| Name | Type | Mandatory| Description | 8898| ------------- | --------------------------------------- | ---- | ----------------------- | 8899| configuration | [PdfConfiguration](#pdfconfiguration14) | Yes | Parameters required for creating a PDF file. | 8900| callback | AsyncCallback<[PdfData](#pdfdata14)> | Yes | Callback used to return the data stream of an online PDF file.| 8901 8902**Error codes** 8903 8904For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8905 8906| ID| Error Message | 8907| -------- | ------------------------------------------------------------ | 8908| 401 | Invalid input parameter. | 8909| 17100001 | Init error. The WebviewController must be associated with a Web component. | 8910 8911**Example** 8912 8913```ts 8914import { fileIo as fs } from '@kit.CoreFileKit'; 8915import { webview } from '@kit.ArkWeb'; 8916import { BusinessError } from '@kit.BasicServicesKit'; 8917import { common } from '@kit.AbilityKit'; 8918 8919@Entry 8920@Component 8921struct Index { 8922 controller: webview.WebviewController = new webview.WebviewController(); 8923 pdfConfig: webview.PdfConfiguration = { 8924 width: 8.27, 8925 height: 11.69, 8926 marginTop: 0, 8927 marginBottom: 0, 8928 marginRight: 0, 8929 marginLeft: 0, 8930 shouldPrintBackground: true 8931 } 8932 8933 build() { 8934 Column() { 8935 Button('SavePDF') 8936 .onClick(() => { 8937 this.controller.createPdf( 8938 this.pdfConfig, 8939 (error, result: webview.PdfData) => { 8940 try { 8941 // Obtain the component context. 8942 let context = getContext(this) as common.UIAbilityContext; 8943 // Obtain the sandbox path and set the PDF file name. 8944 let filePath = context.filesDir + "/test.pdf"; 8945 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 8946 fs.write(file.fd, result.pdfArrayBuffer().buffer).then((writeLen: number) => { 8947 console.info("createPDF write data to file succeed and size is:" + writeLen); 8948 }).catch((err: BusinessError) => { 8949 console.error("createPDF write data to file failed with error message: " + err.message + 8950 ", error code: " + err.code); 8951 }).finally(() => { 8952 fs.closeSync(file); 8953 }); 8954 } catch (resError) { 8955 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 8956 } 8957 }); 8958 }) 8959 Web({ src: "www.example.com", controller: this.controller }) 8960 } 8961 } 8962} 8963``` 8964 8965### createPdf<sup>14+</sup> 8966 8967createPdf(configuration: PdfConfiguration): Promise\<PdfData\> 8968 8969Obtains the data stream of a specified web page using a promise. 8970 8971**System capability**: SystemCapability.Web.Webview.Core 8972 8973**Parameters** 8974 8975| Name | Type | Mandatory| Description | 8976| ------------- | --------------------------------------- | ---- | ----------------- | 8977| configuration | [PdfConfiguration](#pdfconfiguration14) | Yes | Parameters required for creating a PDF file.| 8978 8979**Return value** 8980 8981| Type | Description | 8982| ------------------------------ | ----------------------------- | 8983| Promise<[PdfData](#pdfdata14)> | Promise used to return the data stream of a web page.| 8984 8985**Error codes** 8986 8987For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 8988 8989| ID| Error Message | 8990| -------- | ------------------------------------------------------------ | 8991| 401 | Invalid input parameter. | 8992| 17100001 | Init error. The WebviewController must be associated with a Web component. | 8993 8994**Example** 8995 8996```ts 8997import { fileIo as fs } from '@kit.CoreFileKit'; 8998import { webview } from '@kit.ArkWeb'; 8999import { BusinessError } from '@kit.BasicServicesKit'; 9000import { common } from '@kit.AbilityKit'; 9001 9002@Entry 9003@Component 9004struct Index { 9005 controller: webview.WebviewController = new webview.WebviewController(); 9006 pdfConfig: webview.PdfConfiguration = { 9007 width: 8.27, 9008 height: 11.69, 9009 marginTop: 0, 9010 marginBottom: 0, 9011 marginRight: 0, 9012 marginLeft: 0, 9013 shouldPrintBackground: true 9014 } 9015 9016 build() { 9017 Column() { 9018 Button('SavePDF') 9019 .onClick(() => { 9020 this.controller.createPdf(this.pdfConfig) 9021 .then((result: webview.PdfData) => { 9022 try { 9023 // Obtain the component context. 9024 let context = getContext(this) as common.UIAbilityContext; 9025 // Obtain the sandbox path and set the PDF file name. 9026 let filePath = context.filesDir + "/test.pdf"; 9027 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 9028 fs.write(file.fd, result.pdfArrayBuffer().buffer).then((writeLen: number) => { 9029 console.info("createPDF write data to file succeed and size is:" + writeLen); 9030 }).catch((err: BusinessError) => { 9031 console.error("createPDF write data to file failed with error message: " + err.message + 9032 ", error code: " + err.code); 9033 }).finally(() => { 9034 fs.closeSync(file); 9035 }); 9036 } catch (resError) { 9037 console.error(`ErrorCode: ${(resError as BusinessError).code}, Message: ${(resError as BusinessError).message}`); 9038 } 9039 }) 9040 }) 9041 Web({ src: "www.example.com", controller: this.controller }) 9042 } 9043 } 9044} 9045``` 9046 9047### getScrollOffset<sup>13+</sup> 9048 9049getScrollOffset(): ScrollOffset 9050 9051Obtains the current scrolling offset of a web page. 9052 9053**System capability**: SystemCapability.Web.Webview.Core 9054 9055**Return value** 9056 9057| Type | Description | 9058| :------------------------------ | ---------------------- | 9059| [ScrollOffset](#scrolloffset13) | Current scrolling offset of the web page.| 9060 9061**Example** 9062 9063```ts 9064import { webview } from '@kit.ArkWeb'; 9065import { componentUtils } from '@kit.ArkUI'; 9066 9067@Entry 9068@Component 9069struct WebComponent { 9070 @State testTitle: string = 'webScroll' 9071 controller: webview.WebviewController = new webview.WebviewController(); 9072 @State controllerX: number =-100; 9073 @State controllerY: number =-100; 9074 @State mode: OverScrollMode = OverScrollMode.ALWAYS; 9075 9076 build() { 9077 Column() { 9078 Row() { 9079 Text(this.testTitle) 9080 .fontSize(30) 9081 .fontWeight(FontWeight.Bold) 9082 .margin(5) 9083 } 9084 Column() { 9085 Text(`controllerX: ${this.controllerX}, controllerY: ${this.controllerY}`) 9086 } 9087 .margin({ top: 10, bottom: 10 }) 9088 Web({ src: $rawfile("scrollByTo.html"), controller: this.controller }) 9089 .key("web_01") 9090 .overScrollMode(this.mode) 9091 .onTouch((event) => { 9092 this.controllerX = this.controller.getScrollOffset().x; 9093 this.controllerY = this.controller.getScrollOffset().y; 9094 let componentInfo = componentUtils.getRectangleById("web_01"); 9095 let webHeight = px2vp(componentInfo.size.height); 9096 let pageHeight = this.controller.getPageHeight(); 9097 if (this.controllerY < 0) { 9098 // Case 1: When a web page is scrolled down, use ScrollOffset.y directly. 9099 console.log(`get downwards overscroll offsetY = ${this.controllerY}`); 9100 } else if ((this.controllerY != 0) && (this.controllerY > (pageHeight - webHeight))) { 9101 // 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. 9102 console.log(`get upwards overscroll offsetY = ${this.controllerY - (pageHeight >= webHeight ? (pageHeight - webHeight) : 0)}`); 9103 } else { 9104 // Case 3: If the web page is not scrolled, use ScrollOffset.y directly. 9105 console.log(`get scroll offsetY = ${this.controllerY}`); 9106 } 9107 }) 9108 .height(600) 9109 } 9110 .width('100%') 9111 .height('100%') 9112 } 9113} 9114``` 9115## WebCookieManager 9116 9117Implements a **WebCookieManager** instance to manage behavior of cookies in **Web** components. All **Web** components in an application share a **WebCookieManager** instance. 9118 9119### getCookie<sup>(deprecated)</sup> 9120 9121static getCookie(url: string): string 9122 9123Obtains the cookie value of the specified URL. 9124 9125> **NOTE** 9126> 9127> This API is supported since API version 9 and deprecated since API version 11. You are advised to use [fetchCookieSync](#fetchcookiesync11) instead. 9128 9129**System capability**: SystemCapability.Web.Webview.Core 9130 9131**Parameters** 9132 9133| Name| Type | Mandatory| Description | 9134| ------ | ------ | ---- | :------------------------ | 9135| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 9136 9137**Return value** 9138 9139| Type | Description | 9140| ------ | ------------------------- | 9141| string | Cookie value corresponding to the specified URL.| 9142 9143**Error codes** 9144 9145For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9146 9147| ID| Error Message | 9148| -------- | ------------------------------------------------------ | 9149| 17100002 | Invalid url. | 9150| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 9151 9152**Example** 9153 9154```ts 9155// xxx.ets 9156import { webview } from '@kit.ArkWeb'; 9157import { BusinessError } from '@kit.BasicServicesKit'; 9158 9159@Entry 9160@Component 9161struct WebComponent { 9162 controller: webview.WebviewController = new webview.WebviewController(); 9163 9164 build() { 9165 Column() { 9166 Button('getCookie') 9167 .onClick(() => { 9168 try { 9169 let value = webview.WebCookieManager.getCookie('https://www.example.com'); 9170 console.log("value: " + value); 9171 } catch (error) { 9172 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9173 } 9174 }) 9175 Web({ src: 'www.example.com', controller: this.controller }) 9176 } 9177 } 9178} 9179``` 9180 9181### fetchCookieSync<sup>11+</sup> 9182 9183static fetchCookieSync(url: string, incognito?: boolean): string 9184 9185Obtains the cookie value of the specified URL. 9186 9187> **NOTE** 9188> 9189> The system automatically deletes expired cookies. For data with the same key name, the new data overwrites the previous data. 9190> 9191> To obtain the cookie value that can be used, pass a complete link to **fetchCookieSync()**. 9192> 9193> **fetchCookieSync()** is used to obtain all cookie values. Cookie values are separated by semicolons (;). However, a specific cookie value cannot be obtained separately. 9194 9195**System capability**: SystemCapability.Web.Webview.Core 9196 9197**Parameters** 9198 9199| Name| Type | Mandatory| Description | 9200| ------ | ------ | ---- | :------------------------ | 9201| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 9202| 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.| 9203 9204**Return value** 9205 9206| Type | Description | 9207| ------ | ------------------------- | 9208| string | Cookie value corresponding to the specified URL.| 9209 9210**Error codes** 9211 9212For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9213 9214| ID| Error Message | 9215| -------- | ------------------------------------------------------ | 9216| 17100002 | Invalid url. | 9217| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9218 9219**Example** 9220 9221```ts 9222// xxx.ets 9223import { webview } from '@kit.ArkWeb'; 9224import { BusinessError } from '@kit.BasicServicesKit'; 9225 9226@Entry 9227@Component 9228struct WebComponent { 9229 controller: webview.WebviewController = new webview.WebviewController(); 9230 9231 build() { 9232 Column() { 9233 Button('fetchCookieSync') 9234 .onClick(() => { 9235 try { 9236 let value = webview.WebCookieManager.fetchCookieSync('https://www.example.com'); 9237 console.log("fetchCookieSync cookie = " + value); 9238 } catch (error) { 9239 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9240 } 9241 }) 9242 Web({ src: 'www.example.com', controller: this.controller }) 9243 } 9244 } 9245} 9246``` 9247 9248### fetchCookie<sup>11+</sup> 9249 9250static fetchCookie(url: string, callback: AsyncCallback\<string>): void 9251 9252Obtains the cookie value of a specified URL. This API uses an asynchronous callback to return the result. 9253 9254**System capability**: SystemCapability.Web.Webview.Core 9255 9256**Parameters** 9257 9258| Name| Type | Mandatory| Description | 9259| ------ | ------ | ---- | :------------------------ | 9260| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 9261| callback | AsyncCallback\<string> | Yes| Callback used to return the result.| 9262 9263**Error codes** 9264 9265For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9266 9267| ID| Error Message | 9268| -------- | ------------------------------------------------------ | 9269| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9270| 17100002 | Invalid url. | 9271 9272**Example** 9273 9274```ts 9275// xxx.ets 9276import { webview } from '@kit.ArkWeb'; 9277import { BusinessError } from '@kit.BasicServicesKit'; 9278 9279@Entry 9280@Component 9281struct WebComponent { 9282 controller: webview.WebviewController = new webview.WebviewController(); 9283 9284 build() { 9285 Column() { 9286 Button('fetchCookie') 9287 .onClick(() => { 9288 try { 9289 webview.WebCookieManager.fetchCookie('https://www.example.com', (error, cookie) => { 9290 if (error) { 9291 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9292 return; 9293 } 9294 if (cookie) { 9295 console.log('fetchCookie cookie = ' + cookie); 9296 } 9297 }) 9298 } catch (error) { 9299 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9300 } 9301 }) 9302 Web({ src: 'www.example.com', controller: this.controller }) 9303 } 9304 } 9305} 9306``` 9307 9308### fetchCookie<sup>11+</sup> 9309 9310static fetchCookie(url: string): Promise\<string> 9311 9312Obtains the cookie value of a specified URL. This API uses a promise to return the result. 9313 9314**System capability**: SystemCapability.Web.Webview.Core 9315 9316**Parameters** 9317 9318| Name| Type | Mandatory| Description | 9319| ------ | ------ | ---- | :------------------------ | 9320| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 9321 9322**Return value** 9323 9324| Type | Description | 9325| ------ | ------------------------- | 9326| Promise\<string> | Promise used to return the result.| 9327 9328**Error codes** 9329 9330For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9331 9332| ID| Error Message | 9333| -------- | ------------------------------------------------------ | 9334| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9335| 17100002 | Invalid url. | 9336 9337**Example** 9338 9339```ts 9340// xxx.ets 9341import { webview } from '@kit.ArkWeb'; 9342import { BusinessError } from '@kit.BasicServicesKit'; 9343 9344@Entry 9345@Component 9346struct WebComponent { 9347 controller: webview.WebviewController = new webview.WebviewController(); 9348 9349 build() { 9350 Column() { 9351 Button('fetchCookie') 9352 .onClick(() => { 9353 try { 9354 webview.WebCookieManager.fetchCookie('https://www.example.com') 9355 .then(cookie => { 9356 console.log("fetchCookie cookie = " + cookie); 9357 }) 9358 .catch((error: BusinessError) => { 9359 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 9360 }) 9361 } catch (error) { 9362 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9363 } 9364 }) 9365 Web({ src: 'www.example.com', controller: this.controller }) 9366 } 9367 } 9368} 9369``` 9370 9371### fetchCookie<sup>14+</sup> 9372 9373static fetchCookie(url: string, incognito: boolean): Promise\<string> 9374 9375Obtains the cookie value of a specified URL. This API uses a promise to return the result. 9376 9377**System capability**: SystemCapability.Web.Webview.Core 9378 9379**Parameters** 9380 9381| Name| Type | Mandatory| Description | 9382| ------ | ------ | ---- | :------------------------ | 9383| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 9384| 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.| 9385 9386**Return value** 9387 9388| Type | Description | 9389| ------ | ------------------------- | 9390| Promise\<string> | Promise used to return the result.| 9391 9392**Error codes** 9393 9394For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9395 9396| ID| Error Message | 9397| -------- | ------------------------------------------------------ | 9398| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9399| 17100002 | Invalid url. | 9400 9401**Example** 9402 9403```ts 9404// xxx.ets 9405import { webview } from '@kit.ArkWeb'; 9406import { BusinessError } from '@kit.BasicServicesKit'; 9407 9408@Entry 9409@Component 9410struct WebComponent { 9411 controller: webview.WebviewController = new webview.WebviewController(); 9412 9413 build() { 9414 Column() { 9415 Button('fetchCookie') 9416 .onClick(() => { 9417 try { 9418 webview.WebCookieManager.fetchCookie('https://www.example.com', false) 9419 .then(cookie => { 9420 console.log("fetchCookie cookie = " + cookie); 9421 }) 9422 .catch((error: BusinessError) => { 9423 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 9424 }) 9425 } catch (error) { 9426 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9427 } 9428 }) 9429 Web({ src: 'www.example.com', controller: this.controller }) 9430 } 9431 } 9432} 9433``` 9434 9435### setCookie<sup>(deprecated)</sup> 9436 9437static setCookie(url: string, value: string): void 9438 9439Sets a cookie for the specified URL. 9440 9441> **NOTE** 9442> 9443> 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. 9444 9445**System capability**: SystemCapability.Web.Webview.Core 9446 9447**Parameters** 9448 9449| Name| Type | Mandatory| Description | 9450| ------ | ------ | ---- | :------------------------ | 9451| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 9452| value | string | Yes | Cookie value to set. | 9453 9454**Error codes** 9455 9456For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9457 9458| ID| Error Message | 9459| -------- | ------------------------------------------------------ | 9460| 17100002 | Invalid url. | 9461| 17100005 | Invalid cookie value. | 9462| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9463 9464**Example** 9465 9466```ts 9467// xxx.ets 9468import { webview } from '@kit.ArkWeb'; 9469import { BusinessError } from '@kit.BasicServicesKit'; 9470 9471@Entry 9472@Component 9473struct WebComponent { 9474 controller: webview.WebviewController = new webview.WebviewController(); 9475 9476 build() { 9477 Column() { 9478 Button('setCookie') 9479 .onClick(() => { 9480 try { 9481 webview.WebCookieManager.setCookie('https://www.example.com', 'a=b'); 9482 } catch (error) { 9483 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9484 } 9485 }) 9486 Web({ src: 'www.example.com', controller: this.controller }) 9487 } 9488 } 9489} 9490``` 9491 9492### configCookieSync<sup>11+</sup> 9493 9494static configCookieSync(url: string, value: string, incognito?: boolean): void 9495 9496Sets a cookie for the specified URL. 9497 9498> **NOTE** 9499> 9500> You can set **url** in **configCookieSync** to a domain name so that the cookie is attached to the requests on the page. 9501> 9502> It is recommended that cookie syncing be completed before the **Web** component is loaded. 9503> 9504> If **configCookieSync()** is used to set cookies for two or more times, the cookies set each time are separated by semicolons (;). 9505 9506**System capability**: SystemCapability.Web.Webview.Core 9507 9508**Parameters** 9509 9510| Name| Type | Mandatory| Description | 9511| ------ | ------ | ---- | :------------------------ | 9512| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 9513| value | string | Yes | Cookie value to set. | 9514| 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.| 9515 9516**Error codes** 9517 9518For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9519 9520| ID| Error Message | 9521| -------- | ------------------------------------------------------ | 9522| 17100002 | Invalid url. | 9523| 17100005 | Invalid cookie value. | 9524| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9525 9526**Example** 9527 9528```ts 9529// xxx.ets 9530import { webview } from '@kit.ArkWeb'; 9531import { BusinessError } from '@kit.BasicServicesKit'; 9532 9533@Entry 9534@Component 9535struct WebComponent { 9536 controller: webview.WebviewController = new webview.WebviewController(); 9537 9538 build() { 9539 Column() { 9540 Button('configCookieSync') 9541 .onClick(() => { 9542 try { 9543 // Only one cookie value can be set in configCookieSync at a time. 9544 webview.WebCookieManager.configCookieSync('https://www.example.com', 'a=b'); 9545 } catch (error) { 9546 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9547 } 9548 }) 9549 Web({ src: 'www.example.com', controller: this.controller }) 9550 } 9551 } 9552} 9553``` 9554 9555### configCookieSync<sup>14+</sup> 9556 9557static configCookieSync(url: string, value: string, incognito: boolean, includeHttpOnly: boolean): void 9558 9559Sets the cookie value for the specified URL. 9560 9561**System capability**: SystemCapability.Web.Webview.Core 9562 9563**Parameters** 9564 9565| Name| Type | Mandatory| Description | 9566| ------ | ------ | ---- | :------------------------ | 9567| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 9568| value | string | Yes | Cookie value to set. | 9569| 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.| 9570| includeHttpOnly | boolean | Yes | Whether to overwrite cookies containing **HttpOnly**. The value **true** means to overwrite cookies containing **HttpOnly**, and **false** means the opposite.| 9571 9572**Error codes** 9573 9574For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9575 9576| ID| Error Message | 9577| -------- | ------------------------------------------------------ | 9578| 17100002 | Invalid url. | 9579| 17100005 | Invalid cookie value. | 9580| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9581 9582**Example** 9583 9584```ts 9585// xxx.ets 9586import { webview } from '@kit.ArkWeb'; 9587import { BusinessError } from '@kit.BasicServicesKit'; 9588 9589@Entry 9590@Component 9591struct WebComponent { 9592 controller: webview.WebviewController = new webview.WebviewController(); 9593 9594 build() { 9595 Column() { 9596 Button('configCookieSync') 9597 .onClick(() => { 9598 try { 9599 // Only a single cookie value can be set. 9600 webview.WebCookieManager.configCookieSync('https://www.example.com', 'a=b', false, false); 9601 } catch (error) { 9602 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9603 } 9604 }) 9605 Web({ src: 'www.example.com', controller: this.controller }) 9606 } 9607 } 9608} 9609``` 9610 9611### configCookie<sup>11+</sup> 9612 9613static configCookie(url: string, value: string, callback: AsyncCallback\<void>): void 9614 9615Sets the value of a single cookie for a specified URL. This API uses an asynchronous callback to return the result. 9616 9617**System capability**: SystemCapability.Web.Webview.Core 9618 9619**Parameters** 9620 9621| Name| Type | Mandatory| Description | 9622| ------ | ------ | ---- | :------------------------ | 9623| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 9624| value | string | Yes | Cookie value to set. | 9625| callback | AsyncCallback\<void> | Yes| Callback used to return the result.| 9626 9627**Error codes** 9628 9629For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9630 9631| ID| Error Message | 9632| -------- | ------------------------------------------------------ | 9633| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9634| 17100002 | Invalid url. | 9635| 17100005 | Invalid cookie value. | 9636 9637**Example** 9638 9639```ts 9640// xxx.ets 9641import { webview } from '@kit.ArkWeb'; 9642import { BusinessError } from '@kit.BasicServicesKit'; 9643 9644@Entry 9645@Component 9646struct WebComponent { 9647 controller: webview.WebviewController = new webview.WebviewController(); 9648 9649 build() { 9650 Column() { 9651 Button('configCookie') 9652 .onClick(() => { 9653 try { 9654 webview.WebCookieManager.configCookie('https://www.example.com', "a=b", (error) => { 9655 if (error) { 9656 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9657 } 9658 }) 9659 } catch (error) { 9660 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9661 } 9662 }) 9663 Web({ src: 'www.example.com', controller: this.controller }) 9664 } 9665 } 9666} 9667``` 9668 9669### configCookie<sup>11+</sup> 9670 9671static configCookie(url: string, value: string): Promise\<void> 9672 9673Sets the value of a single cookie for a specified URL. This API uses a promise to return the result. 9674 9675**System capability**: SystemCapability.Web.Webview.Core 9676 9677**Parameters** 9678 9679| Name| Type | Mandatory| Description | 9680| ------ | ------ | ---- | :------------------------ | 9681| url | string | Yes | URL of the cookie to set. A complete URL is recommended.| 9682| value | string | Yes | Cookie value to set. | 9683 9684**Return value** 9685 9686| Type | Description | 9687| ------ | ------------------------- | 9688| Promise\<void> | Promise used to return the result.| 9689 9690**Error codes** 9691 9692For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9693 9694| ID| Error Message | 9695| -------- | ------------------------------------------------------ | 9696| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9697| 17100002 | Invalid url. | 9698| 17100005 | Invalid cookie value. | 9699 9700**Example** 9701 9702```ts 9703// xxx.ets 9704import { webview } from '@kit.ArkWeb'; 9705import { BusinessError } from '@kit.BasicServicesKit'; 9706 9707@Entry 9708@Component 9709struct WebComponent { 9710 controller: webview.WebviewController = new webview.WebviewController(); 9711 9712 build() { 9713 Column() { 9714 Button('configCookie') 9715 .onClick(() => { 9716 try { 9717 webview.WebCookieManager.configCookie('https://www.example.com', 'a=b') 9718 .then(() => { 9719 console.log('configCookie success!'); 9720 }) 9721 .catch((error: BusinessError) => { 9722 console.log('error: ' + JSON.stringify(error)); 9723 }) 9724 } catch (error) { 9725 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9726 } 9727 }) 9728 Web({ src: 'www.example.com', controller: this.controller }) 9729 } 9730 } 9731} 9732``` 9733 9734### configCookie<sup>14+</sup> 9735 9736static configCookie(url: string, value: string, incognito: boolean, includeHttpOnly: boolean): Promise\<void> 9737 9738Sets the value of a single cookie for a specified URL. This API uses a promise to return the result. 9739 9740**System capability**: SystemCapability.Web.Webview.Core 9741 9742**Parameters** 9743 9744| Name| Type | Mandatory| Description | 9745| ------ | ------ | ---- | :------------------------ | 9746| url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.| 9747| value | string | Yes | Cookie value to set. | 9748| 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.| 9749| includeHttpOnly | boolean | Yes | Whether to overwrite cookies containing **HttpOnly**. The value **true** means to overwrite cookies containing **HttpOnly**, and **false** means the opposite.| 9750 9751**Return value** 9752 9753| Type | Description | 9754| ------ | ------------------------- | 9755| Promise\<void> | Promise used to return the result.| 9756 9757**Error codes** 9758 9759For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9760 9761| ID| Error Message | 9762| -------- | ------------------------------------------------------ | 9763| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 9764| 17100002 | Invalid url. | 9765| 17100005 | Invalid cookie value. | 9766 9767**Example** 9768 9769```ts 9770// xxx.ets 9771import { webview } from '@kit.ArkWeb'; 9772import { BusinessError } from '@kit.BasicServicesKit'; 9773 9774@Entry 9775@Component 9776struct WebComponent { 9777 controller: webview.WebviewController = new webview.WebviewController(); 9778 9779 build() { 9780 Column() { 9781 Button('configCookie') 9782 .onClick(() => { 9783 try { 9784 webview.WebCookieManager.configCookie('https://www.example.com', 'a=b', false, false) 9785 .then(() => { 9786 console.log('configCookie success!'); 9787 }) 9788 .catch((error: BusinessError) => { 9789 console.log('error: ' + JSON.stringify(error)); 9790 }) 9791 } catch (error) { 9792 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9793 } 9794 }) 9795 Web({ src: 'www.example.com', controller: this.controller }) 9796 } 9797 } 9798} 9799``` 9800 9801### saveCookieAsync 9802 9803static saveCookieAsync(callback: AsyncCallback\<void>): void 9804 9805Saves the cookies in the memory to the drive. This API uses an asynchronous callback to return the result. 9806 9807**System capability**: SystemCapability.Web.Webview.Core 9808 9809**Parameters** 9810 9811| Name | Type | Mandatory| Description | 9812| -------- | ---------------------- | ---- | :------------------------------------------------- | 9813| callback | AsyncCallback\<void> | Yes | Callback used to return whether the cookies are successfully saved.| 9814 9815**Error codes** 9816 9817For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9818 9819| ID| Error Message | 9820| -------- | ------------------------------------------------------ | 9821| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 9822 9823**Example** 9824 9825```ts 9826// xxx.ets 9827import { webview } from '@kit.ArkWeb'; 9828import { BusinessError } from '@kit.BasicServicesKit'; 9829 9830@Entry 9831@Component 9832struct WebComponent { 9833 controller: webview.WebviewController = new webview.WebviewController(); 9834 9835 build() { 9836 Column() { 9837 Button('saveCookieAsync') 9838 .onClick(() => { 9839 try { 9840 webview.WebCookieManager.saveCookieAsync((error) => { 9841 if (error) { 9842 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9843 } 9844 }) 9845 } catch (error) { 9846 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9847 } 9848 }) 9849 Web({ src: 'www.example.com', controller: this.controller }) 9850 } 9851 } 9852} 9853``` 9854 9855### saveCookieAsync 9856 9857static saveCookieAsync(): Promise\<void> 9858 9859Saves the cookies in the memory to the drive. This API uses a promise to return the result. 9860 9861**System capability**: SystemCapability.Web.Webview.Core 9862 9863**Return value** 9864 9865| Type | Description | 9866| ---------------- | ----------------------------------------- | 9867| Promise\<void> | Promise used to return the operation result.| 9868 9869**Error codes** 9870 9871For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9872 9873| ID| Error Message | 9874| -------- | ------------------------------------------------------ | 9875| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 9876 9877**Example** 9878 9879```ts 9880// xxx.ets 9881import { webview } from '@kit.ArkWeb'; 9882import { BusinessError } from '@kit.BasicServicesKit'; 9883 9884@Entry 9885@Component 9886struct WebComponent { 9887 controller: webview.WebviewController = new webview.WebviewController(); 9888 9889 build() { 9890 Column() { 9891 Button('saveCookieAsync') 9892 .onClick(() => { 9893 try { 9894 webview.WebCookieManager.saveCookieAsync() 9895 .then(() => { 9896 console.log("saveCookieAsyncCallback success!"); 9897 }) 9898 .catch((error: BusinessError) => { 9899 console.error("error: " + error); 9900 }); 9901 } catch (error) { 9902 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9903 } 9904 }) 9905 Web({ src: 'www.example.com', controller: this.controller }) 9906 } 9907 } 9908} 9909``` 9910 9911### putAcceptCookieEnabled 9912 9913static putAcceptCookieEnabled(accept: boolean): void 9914 9915Sets whether the **WebCookieManager** instance has the permission to send and receive cookies. 9916 9917**System capability**: SystemCapability.Web.Webview.Core 9918 9919**Parameters** 9920 9921| Name| Type | Mandatory| Description | 9922| ------ | ------- | ---- | :----------------------------------- | 9923| accept | boolean | Yes | Whether the **WebCookieManager** instance has the permission to send and receive cookies.<br>Default value: **true**| 9924 9925**Error codes** 9926 9927For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 9928 9929| ID| Error Message | 9930| -------- | ------------------------------------------------------ | 9931| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 9932 9933**Example** 9934 9935```ts 9936// xxx.ets 9937import { webview } from '@kit.ArkWeb'; 9938import { BusinessError } from '@kit.BasicServicesKit'; 9939 9940@Entry 9941@Component 9942struct WebComponent { 9943 controller: webview.WebviewController = new webview.WebviewController(); 9944 9945 build() { 9946 Column() { 9947 Button('putAcceptCookieEnabled') 9948 .onClick(() => { 9949 try { 9950 webview.WebCookieManager.putAcceptCookieEnabled(false); 9951 } catch (error) { 9952 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 9953 } 9954 }) 9955 Web({ src: 'www.example.com', controller: this.controller }) 9956 } 9957 } 9958} 9959``` 9960 9961### isCookieAllowed 9962 9963static isCookieAllowed(): boolean 9964 9965Checks whether the **WebCookieManager** instance has the permission to send and receive cookies. 9966 9967**System capability**: SystemCapability.Web.Webview.Core 9968 9969**Return value** 9970 9971| Type | Description | 9972| ------- | -------------------------------- | 9973| boolean | Whether the **WebCookieManager** instance has the permission to send and receive cookies. The default value is **true**.| 9974 9975**Example** 9976 9977```ts 9978// xxx.ets 9979import { webview } from '@kit.ArkWeb'; 9980 9981@Entry 9982@Component 9983struct WebComponent { 9984 controller: webview.WebviewController = new webview.WebviewController(); 9985 9986 build() { 9987 Column() { 9988 Button('isCookieAllowed') 9989 .onClick(() => { 9990 let result = webview.WebCookieManager.isCookieAllowed(); 9991 console.log("result: " + result); 9992 }) 9993 Web({ src: 'www.example.com', controller: this.controller }) 9994 } 9995 } 9996} 9997``` 9998 9999### putAcceptThirdPartyCookieEnabled 10000 10001static putAcceptThirdPartyCookieEnabled(accept: boolean): void 10002 10003Sets whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. 10004 10005**System capability**: SystemCapability.Web.Webview.Core 10006 10007**Parameters** 10008 10009| Name| Type | Mandatory| Description | 10010| ------ | ------- | ---- | :----------------------------------------- | 10011| accept | boolean | Yes | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies.<br>Default value: **false**| 10012 10013**Error codes** 10014 10015For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10016 10017| ID| Error Message | 10018| -------- | ------------------------------------------------------ | 10019| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10020 10021**Example** 10022 10023```ts 10024// xxx.ets 10025import { webview } from '@kit.ArkWeb'; 10026import { BusinessError } from '@kit.BasicServicesKit'; 10027 10028@Entry 10029@Component 10030struct WebComponent { 10031 controller: webview.WebviewController = new webview.WebviewController(); 10032 10033 build() { 10034 Column() { 10035 Button('putAcceptThirdPartyCookieEnabled') 10036 .onClick(() => { 10037 try { 10038 webview.WebCookieManager.putAcceptThirdPartyCookieEnabled(false); 10039 } catch (error) { 10040 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10041 } 10042 }) 10043 Web({ src: 'www.example.com', controller: this.controller }) 10044 } 10045 } 10046} 10047``` 10048 10049### isThirdPartyCookieAllowed 10050 10051static isThirdPartyCookieAllowed(): boolean 10052 10053Checks whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. 10054 10055**System capability**: SystemCapability.Web.Webview.Core 10056 10057**Return value** 10058 10059| Type | Description | 10060| ------- | -------------------------------------- | 10061| boolean | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. The default value is **false**.| 10062 10063**Example** 10064 10065```ts 10066// xxx.ets 10067import { webview } from '@kit.ArkWeb'; 10068 10069@Entry 10070@Component 10071struct WebComponent { 10072 controller: webview.WebviewController = new webview.WebviewController(); 10073 10074 build() { 10075 Column() { 10076 Button('isThirdPartyCookieAllowed') 10077 .onClick(() => { 10078 let result = webview.WebCookieManager.isThirdPartyCookieAllowed(); 10079 console.log("result: " + result); 10080 }) 10081 Web({ src: 'www.example.com', controller: this.controller }) 10082 } 10083 } 10084} 10085``` 10086 10087### existCookie 10088 10089static existCookie(incognito?: boolean): boolean 10090 10091Checks whether cookies exist. 10092 10093**System capability**: SystemCapability.Web.Webview.Core 10094 10095**Parameters** 10096 10097| Name| Type | Mandatory| Description | 10098| ------ | ------- | ---- | :----------------------------------------- | 10099| 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.| 10100 10101**Return value** 10102 10103| Type | Description | 10104| ------- | -------------------------------------- | 10105| boolean | Whether cookies exist. The value **true** means that cookies exist, and **false** means the opposite.| 10106 10107**Example** 10108 10109```ts 10110// xxx.ets 10111import { webview } from '@kit.ArkWeb'; 10112 10113@Entry 10114@Component 10115struct WebComponent { 10116 controller: webview.WebviewController = new webview.WebviewController(); 10117 10118 build() { 10119 Column() { 10120 Button('existCookie') 10121 .onClick(() => { 10122 let result = webview.WebCookieManager.existCookie(); 10123 console.log("result: " + result); 10124 }) 10125 Web({ src: 'www.example.com', controller: this.controller }) 10126 } 10127 } 10128} 10129``` 10130 10131### deleteEntireCookie<sup>(deprecated)</sup> 10132 10133static deleteEntireCookie(): void 10134 10135Deletes all cookies. 10136 10137> **NOTE** 10138> 10139> This API is supported since API version 9 and deprecated since API version 11. You are advised to use [clearAllCookiesSync](#clearallcookiessync11) instead. 10140 10141**System capability**: SystemCapability.Web.Webview.Core 10142 10143**Example** 10144 10145```ts 10146// xxx.ets 10147import { webview } from '@kit.ArkWeb'; 10148 10149@Entry 10150@Component 10151struct WebComponent { 10152 controller: webview.WebviewController = new webview.WebviewController(); 10153 10154 build() { 10155 Column() { 10156 Button('deleteEntireCookie') 10157 .onClick(() => { 10158 webview.WebCookieManager.deleteEntireCookie(); 10159 }) 10160 Web({ src: 'www.example.com', controller: this.controller }) 10161 } 10162 } 10163} 10164``` 10165 10166### clearAllCookiesSync<sup>11+</sup> 10167 10168static clearAllCookiesSync(incognito?: boolean): void 10169 10170Deletes all cookies. 10171 10172**System capability**: SystemCapability.Web.Webview.Core 10173 10174**Parameters** 10175 10176| Name| Type | Mandatory| Description | 10177| ------ | ------- | ---- | :----------------------------------------- | 10178| 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.| 10179 10180**Example** 10181 10182```ts 10183// xxx.ets 10184import { webview } from '@kit.ArkWeb'; 10185 10186@Entry 10187@Component 10188struct WebComponent { 10189 controller: webview.WebviewController = new webview.WebviewController(); 10190 10191 build() { 10192 Column() { 10193 Button('clearAllCookiesSync') 10194 .onClick(() => { 10195 webview.WebCookieManager.clearAllCookiesSync(); 10196 }) 10197 Web({ src: 'www.example.com', controller: this.controller }) 10198 } 10199 } 10200} 10201``` 10202 10203### clearAllCookies<sup>11+</sup> 10204 10205static clearAllCookies(callback: AsyncCallback\<void>): void 10206 10207Clears all cookies. This API uses an asynchronous callback to return the result. 10208 10209**System capability**: SystemCapability.Web.Webview.Core 10210 10211**Parameters** 10212 10213| Name | Type | Mandatory| Description | 10214| -------- | ---------------------- | ---- | :------------------------------------------------- | 10215| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 10216 10217**Error codes** 10218 10219For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10220 10221| ID| Error Message | 10222| -------- | ------------------------------------------------------ | 10223| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 10224 10225**Example** 10226 10227```ts 10228// xxx.ets 10229import { webview } from '@kit.ArkWeb'; 10230import { BusinessError } from '@kit.BasicServicesKit'; 10231 10232@Entry 10233@Component 10234struct WebComponent { 10235 controller: webview.WebviewController = new webview.WebviewController(); 10236 10237 build() { 10238 Column() { 10239 Button('clearAllCookies') 10240 .onClick(() => { 10241 try { 10242 webview.WebCookieManager.clearAllCookies((error) => { 10243 if (error) { 10244 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10245 } 10246 }) 10247 } catch (error) { 10248 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10249 } 10250 }) 10251 Web({ src: 'www.example.com', controller: this.controller }) 10252 } 10253 } 10254} 10255``` 10256 10257### clearAllCookies<sup>11+</sup> 10258 10259static clearAllCookies(): Promise\<void> 10260 10261Clears all cookies. This API uses a promise to return the result. 10262 10263**System capability**: SystemCapability.Web.Webview.Core 10264 10265**Return value** 10266 10267| Type | Description | 10268| ---------------- | ----------------------------------------- | 10269| Promise\<void> | Promise used to return the result.| 10270 10271**Error codes** 10272 10273For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10274 10275| ID| Error Message | 10276| -------- | ------------------------------------------------------ | 10277| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 10278 10279**Example** 10280 10281```ts 10282// xxx.ets 10283import { webview } from '@kit.ArkWeb'; 10284import { BusinessError } from '@kit.BasicServicesKit'; 10285 10286@Entry 10287@Component 10288struct WebComponent { 10289 controller: webview.WebviewController = new webview.WebviewController(); 10290 10291 build() { 10292 Column() { 10293 Button('clearAllCookies') 10294 .onClick(() => { 10295 try { 10296 webview.WebCookieManager.clearAllCookies() 10297 .then(() => { 10298 console.log("clearAllCookies success!"); 10299 }) 10300 .catch((error: BusinessError) => { 10301 console.error("error: " + error); 10302 }); 10303 } catch (error) { 10304 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10305 } 10306 }) 10307 Web({ src: 'www.example.com', controller: this.controller }) 10308 } 10309 } 10310} 10311``` 10312 10313### deleteSessionCookie<sup>(deprecated)</sup> 10314 10315static deleteSessionCookie(): void 10316 10317Deletes all session cookies. 10318 10319> **NOTE** 10320> 10321> This API is supported since API version 9 and deprecated since API version 11. You are advised to use [clearSessionCookiesync](#clearsessioncookiesync11) instead. 10322 10323**System capability**: SystemCapability.Web.Webview.Core 10324 10325**Example** 10326 10327```ts 10328// xxx.ets 10329import { webview } from '@kit.ArkWeb'; 10330 10331@Entry 10332@Component 10333struct WebComponent { 10334 controller: webview.WebviewController = new webview.WebviewController(); 10335 10336 build() { 10337 Column() { 10338 Button('deleteSessionCookie') 10339 .onClick(() => { 10340 webview.WebCookieManager.deleteSessionCookie(); 10341 }) 10342 Web({ src: 'www.example.com', controller: this.controller }) 10343 } 10344 } 10345} 10346``` 10347 10348### clearSessionCookieSync<sup>11+</sup> 10349 10350static clearSessionCookieSync(): void 10351 10352Deletes all session cookies. 10353 10354**System capability**: SystemCapability.Web.Webview.Core 10355 10356**Example** 10357 10358```ts 10359// xxx.ets 10360import { webview } from '@kit.ArkWeb'; 10361 10362@Entry 10363@Component 10364struct WebComponent { 10365 controller: webview.WebviewController = new webview.WebviewController(); 10366 10367 build() { 10368 Column() { 10369 Button('clearSessionCookieSync') 10370 .onClick(() => { 10371 webview.WebCookieManager.clearSessionCookieSync(); 10372 }) 10373 Web({ src: 'www.example.com', controller: this.controller }) 10374 } 10375 } 10376} 10377``` 10378 10379### clearSessionCookie<sup>11+</sup> 10380 10381static clearSessionCookie(callback: AsyncCallback\<void>): void 10382 10383Clears all session cookies. This API uses an asynchronous callback to return the result. 10384 10385**System capability**: SystemCapability.Web.Webview.Core 10386 10387**Parameters** 10388 10389| Name | Type | Mandatory| Description | 10390| -------- | ---------------------- | ---- | :------------------------------------------------- | 10391| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 10392 10393**Error codes** 10394 10395For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10396 10397| ID| Error Message | 10398| -------- | ------------------------------------------------------ | 10399| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 10400 10401**Example** 10402 10403```ts 10404// xxx.ets 10405import { webview } from '@kit.ArkWeb'; 10406import { BusinessError } from '@kit.BasicServicesKit'; 10407 10408@Entry 10409@Component 10410struct WebComponent { 10411 controller: webview.WebviewController = new webview.WebviewController(); 10412 10413 build() { 10414 Column() { 10415 Button('clearSessionCookie') 10416 .onClick(() => { 10417 try { 10418 webview.WebCookieManager.clearSessionCookie((error) => { 10419 if (error) { 10420 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10421 } 10422 }) 10423 } catch (error) { 10424 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10425 } 10426 }) 10427 Web({ src: 'www.example.com', controller: this.controller }) 10428 } 10429 } 10430} 10431``` 10432 10433### clearSessionCookie<sup>11+</sup> 10434 10435static clearSessionCookie(): Promise\<void> 10436 10437Clears all session cookies. This API uses a promise to return the result. 10438 10439**System capability**: SystemCapability.Web.Webview.Core 10440 10441**Return value** 10442 10443| Type | Description | 10444| ---------------- | ----------------------------------------- | 10445| Promise\<void> | Promise used to return the result.| 10446 10447**Error codes** 10448 10449For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10450 10451| ID| Error Message | 10452| -------- | ------------------------------------------------------ | 10453| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 10454 10455**Example** 10456 10457```ts 10458// xxx.ets 10459import { webview } from '@kit.ArkWeb'; 10460import { BusinessError } from '@kit.BasicServicesKit'; 10461 10462@Entry 10463@Component 10464struct WebComponent { 10465 controller: webview.WebviewController = new webview.WebviewController(); 10466 10467 build() { 10468 Column() { 10469 Button('clearSessionCookie') 10470 .onClick(() => { 10471 try { 10472 webview.WebCookieManager.clearSessionCookie() 10473 .then(() => { 10474 console.log("clearSessionCookie success!"); 10475 }) 10476 .catch((error: BusinessError) => { 10477 console.error("error: " + error); 10478 }); 10479 } catch (error) { 10480 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10481 } 10482 }) 10483 Web({ src: 'www.example.com', controller: this.controller }) 10484 } 10485 } 10486} 10487``` 10488 10489## WebStorage 10490 10491Implements a **WebStorage** object to manage the Web SQL database and HTML5 Web Storage APIs. All **Web** components in an application share a **WebStorage** object. 10492 10493> **NOTE** 10494> 10495> You must load the **Web** component before calling the APIs in **WebStorage**. 10496 10497### deleteOrigin 10498 10499static deleteOrigin(origin: string): void 10500 10501Deletes all data in the specified origin. 10502 10503**System capability**: SystemCapability.Web.Webview.Core 10504 10505**Parameters** 10506 10507| Name| Type | Mandatory| Description | 10508| ------ | ------ | ---- | ------------------------ | 10509| origin | string | Yes | Index of the origin, which is obtained through [getOrigins](#getorigins).| 10510 10511**Error codes** 10512 10513For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10514 10515| ID| Error Message | 10516| -------- | ------------------------------------------------------ | 10517| 17100011 | Invalid origin. | 10518| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10519 10520**Example** 10521 10522```ts 10523// xxx.ets 10524import { webview } from '@kit.ArkWeb'; 10525import { BusinessError } from '@kit.BasicServicesKit'; 10526 10527@Entry 10528@Component 10529struct WebComponent { 10530 controller: webview.WebviewController = new webview.WebviewController(); 10531 origin: string = "resource://rawfile/"; 10532 10533 build() { 10534 Column() { 10535 Button('deleteOrigin') 10536 .onClick(() => { 10537 try { 10538 webview.WebStorage.deleteOrigin(this.origin); 10539 } catch (error) { 10540 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10541 } 10542 10543 }) 10544 Web({ src: $rawfile('index.html'), controller: this.controller }) 10545 .databaseAccess(true) 10546 } 10547 } 10548} 10549``` 10550 10551HTML file to be loaded: 10552 ```html 10553 <!-- index.html --> 10554 <!DOCTYPE html> 10555 <html> 10556 <head> 10557 <meta charset="UTF-8"> 10558 <title>test</title> 10559 <script type="text/javascript"> 10560 10561 var db = openDatabase('mydb','1.0','Test DB',2 * 1024 * 1024); 10562 var msg; 10563 10564 db.transaction(function(tx){ 10565 tx.executeSql('INSERT INTO LOGS (id,log) VALUES(1,"test1")'); 10566 tx.executeSql('INSERT INTO LOGS (id,log) VALUES(2,"test2")'); 10567 msg = '<p>Data table created, with two data records inserted.</p>'; 10568 10569 document.querySelector('#status').innerHTML = msg; 10570 }); 10571 10572 db.transaction(function(tx){ 10573 tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) { 10574 var len = results.rows.length,i; 10575 msg = "<p>Number of records: " + len + "</p>"; 10576 10577 document.querySelector('#status').innerHTML += msg; 10578 10579 for(i = 0; i < len; i++){ 10580 msg = "<p><b>" + results.rows.item(i).log + "</b></p>"; 10581 10582 document.querySelector('#status').innerHTML += msg; 10583 } 10584 },null); 10585 }); 10586 10587 </script> 10588 </head> 10589 <body> 10590 <div id="status" name="status">Status</div> 10591 </body> 10592 </html> 10593 ``` 10594 10595### getOrigins 10596 10597static getOrigins(callback: AsyncCallback\<Array\<WebStorageOrigin>>): void 10598 10599Obtains information about all origins that are currently using the Web SQL Database. This API uses an asynchronous callback to return the result. 10600 10601**System capability**: SystemCapability.Web.Webview.Core 10602 10603**Parameters** 10604 10605| Name | Type | Mandatory| Description | 10606| -------- | -------------------------------------- | ---- | ------------------------------------------------------ | 10607| callback | AsyncCallback\<Array\<[WebStorageOrigin](#webstorageorigin)>> | Yes | Callback used to return the information about the origins. For details, see [WebStorageOrigin](#webstorageorigin).| 10608 10609**Error codes** 10610 10611For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10612 10613| ID| Error Message | 10614| -------- | ------------------------------------------------------ | 10615| 17100012 | Invalid web storage origin. | 10616| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10617 10618**Example** 10619 10620```ts 10621// xxx.ets 10622import { webview } from '@kit.ArkWeb'; 10623import { BusinessError } from '@kit.BasicServicesKit'; 10624 10625@Entry 10626@Component 10627struct WebComponent { 10628 controller: webview.WebviewController = new webview.WebviewController(); 10629 10630 build() { 10631 Column() { 10632 Button('getOrigins') 10633 .onClick(() => { 10634 try { 10635 webview.WebStorage.getOrigins((error, origins) => { 10636 if (error) { 10637 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10638 return; 10639 } 10640 for (let i = 0; i < origins.length; i++) { 10641 console.log('origin: ' + origins[i].origin); 10642 console.log('usage: ' + origins[i].usage); 10643 console.log('quota: ' + origins[i].quota); 10644 } 10645 }) 10646 } catch (error) { 10647 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10648 } 10649 10650 }) 10651 Web({ src: $rawfile('index.html'), controller: this.controller }) 10652 .databaseAccess(true) 10653 } 10654 } 10655} 10656``` 10657 10658For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 10659 10660### getOrigins 10661 10662static getOrigins(): Promise\<Array\<WebStorageOrigin>> 10663 10664Obtains information about all origins that are currently using the Web SQL Database. This API uses a promise to return the result. 10665 10666**System capability**: SystemCapability.Web.Webview.Core 10667 10668**Return value** 10669 10670| Type | Description | 10671| -------------------------------- | ------------------------------------------------------------ | 10672| Promise\<Array\<[WebStorageOrigin](#webstorageorigin)>> | Promise used to return the information about the origins. For details, see [WebStorageOrigin](#webstorageorigin).| 10673 10674**Error codes** 10675 10676For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10677 10678| ID| Error Message | 10679| -------- | ------------------------------------------------------ | 10680| 17100012 | Invalid web storage origin. | 10681| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10682 10683**Example** 10684 10685```ts 10686// xxx.ets 10687import { webview } from '@kit.ArkWeb'; 10688import { BusinessError } from '@kit.BasicServicesKit'; 10689 10690@Entry 10691@Component 10692struct WebComponent { 10693 controller: webview.WebviewController = new webview.WebviewController(); 10694 10695 build() { 10696 Column() { 10697 Button('getOrigins') 10698 .onClick(() => { 10699 try { 10700 webview.WebStorage.getOrigins() 10701 .then(origins => { 10702 for (let i = 0; i < origins.length; i++) { 10703 console.log('origin: ' + origins[i].origin); 10704 console.log('usage: ' + origins[i].usage); 10705 console.log('quota: ' + origins[i].quota); 10706 } 10707 }) 10708 .catch((e: BusinessError) => { 10709 console.log('error: ' + JSON.stringify(e)); 10710 }) 10711 } catch (error) { 10712 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10713 } 10714 10715 }) 10716 Web({ src: $rawfile('index.html'), controller: this.controller }) 10717 .databaseAccess(true) 10718 } 10719 } 10720} 10721``` 10722 10723For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 10724 10725### getOriginQuota 10726 10727static getOriginQuota(origin: string, callback: AsyncCallback\<number>): void 10728 10729Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. 10730 10731**System capability**: SystemCapability.Web.Webview.Core 10732 10733**Parameters** 10734 10735| Name | Type | Mandatory| Description | 10736| -------- | --------------------- | ---- | ------------------ | 10737| origin | string | Yes | Index of the origin.| 10738| callback | AsyncCallback\<number> | Yes | Storage quota of the origin. | 10739 10740**Error codes** 10741 10742For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10743 10744| ID| Error Message | 10745| -------- | ------------------------------------------------------ | 10746| 17100011 | Invalid origin. | 10747| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10748 10749**Example** 10750 10751```ts 10752// xxx.ets 10753import { webview } from '@kit.ArkWeb'; 10754import { BusinessError } from '@kit.BasicServicesKit'; 10755 10756@Entry 10757@Component 10758struct WebComponent { 10759 controller: webview.WebviewController = new webview.WebviewController(); 10760 origin: string = "resource://rawfile/"; 10761 10762 build() { 10763 Column() { 10764 Button('getOriginQuota') 10765 .onClick(() => { 10766 try { 10767 webview.WebStorage.getOriginQuota(this.origin, (error, quota) => { 10768 if (error) { 10769 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10770 return; 10771 } 10772 console.log('quota: ' + quota); 10773 }) 10774 } catch (error) { 10775 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10776 } 10777 10778 }) 10779 Web({ src: $rawfile('index.html'), controller: this.controller }) 10780 .databaseAccess(true) 10781 } 10782 } 10783} 10784``` 10785 10786For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 10787 10788### getOriginQuota 10789 10790static getOriginQuota(origin: string): Promise\<number> 10791 10792Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. 10793 10794**System capability**: SystemCapability.Web.Webview.Core 10795 10796**Parameters** 10797 10798| Name| Type | Mandatory| Description | 10799| ------ | ------ | ---- | ------------------ | 10800| origin | string | Yes | Index of the origin.| 10801 10802**Return value** 10803 10804| Type | Description | 10805| --------------- | --------------------------------------- | 10806| Promise\<number> | Promise used to return the storage quota of the origin.| 10807 10808**Error codes** 10809 10810For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10811 10812| ID| Error Message | 10813| -------- | ------------------------------------------------------ | 10814| 17100011 | Invalid origin. | 10815| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10816 10817**Example** 10818 10819```ts 10820// xxx.ets 10821import { webview } from '@kit.ArkWeb'; 10822import { BusinessError } from '@kit.BasicServicesKit'; 10823 10824@Entry 10825@Component 10826struct WebComponent { 10827 controller: webview.WebviewController = new webview.WebviewController(); 10828 origin: string = "resource://rawfile/"; 10829 10830 build() { 10831 Column() { 10832 Button('getOriginQuota') 10833 .onClick(() => { 10834 try { 10835 webview.WebStorage.getOriginQuota(this.origin) 10836 .then(quota => { 10837 console.log('quota: ' + quota); 10838 }) 10839 .catch((e: BusinessError) => { 10840 console.log('error: ' + JSON.stringify(e)); 10841 }) 10842 } catch (error) { 10843 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10844 } 10845 10846 }) 10847 Web({ src: $rawfile('index.html'), controller: this.controller }) 10848 .databaseAccess(true) 10849 } 10850 } 10851} 10852``` 10853 10854For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 10855 10856### getOriginUsage 10857 10858static getOriginUsage(origin: string, callback: AsyncCallback\<number>): void 10859 10860Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. 10861 10862**System capability**: SystemCapability.Web.Webview.Core 10863 10864**Parameters** 10865 10866| Name | Type | Mandatory| Description | 10867| -------- | --------------------- | ---- | ------------------ | 10868| origin | string | Yes | Index of the origin.| 10869| callback | AsyncCallback\<number> | Yes | Storage usage of the origin. | 10870 10871**Error codes** 10872 10873For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10874 10875| ID| Error Message | 10876| -------- | ------------------------------------------------------ | 10877| 17100011 | Invalid origin. | 10878| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10879 10880**Example** 10881 10882```ts 10883// xxx.ets 10884import { webview } from '@kit.ArkWeb'; 10885import { BusinessError } from '@kit.BasicServicesKit'; 10886 10887@Entry 10888@Component 10889struct WebComponent { 10890 controller: webview.WebviewController = new webview.WebviewController(); 10891 origin: string = "resource://rawfile/"; 10892 10893 build() { 10894 Column() { 10895 Button('getOriginUsage') 10896 .onClick(() => { 10897 try { 10898 webview.WebStorage.getOriginUsage(this.origin, (error, usage) => { 10899 if (error) { 10900 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10901 return; 10902 } 10903 console.log('usage: ' + usage); 10904 }) 10905 } catch (error) { 10906 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10907 } 10908 10909 }) 10910 Web({ src: $rawfile('index.html'), controller: this.controller }) 10911 .databaseAccess(true) 10912 } 10913 } 10914} 10915``` 10916 10917For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 10918 10919### getOriginUsage 10920 10921static getOriginUsage(origin: string): Promise\<number> 10922 10923Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. 10924 10925**System capability**: SystemCapability.Web.Webview.Core 10926 10927**Parameters** 10928 10929| Name| Type | Mandatory| Description | 10930| ------ | ------ | ---- | ------------------ | 10931| origin | string | Yes | Index of the origin.| 10932 10933**Return value** 10934 10935| Type | Description | 10936| --------------- | ------------------------------------- | 10937| Promise\<number> | Promise used to return the storage usage of the origin.| 10938 10939**Error codes** 10940 10941For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 10942 10943| ID| Error Message | 10944| -------- | ----------------------------------------------------- | 10945| 17100011 | Invalid origin. | 10946| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 10947 10948**Example** 10949 10950```ts 10951// xxx.ets 10952import { webview } from '@kit.ArkWeb'; 10953import { BusinessError } from '@kit.BasicServicesKit'; 10954 10955@Entry 10956@Component 10957struct WebComponent { 10958 controller: webview.WebviewController = new webview.WebviewController(); 10959 origin: string = "resource://rawfile/"; 10960 10961 build() { 10962 Column() { 10963 Button('getOriginUsage') 10964 .onClick(() => { 10965 try { 10966 webview.WebStorage.getOriginUsage(this.origin) 10967 .then(usage => { 10968 console.log('usage: ' + usage); 10969 }).catch((e: BusinessError) => { 10970 console.error('error: ' + JSON.stringify(e)); 10971 }) 10972 } catch (error) { 10973 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 10974 } 10975 }) 10976 Web({ src: $rawfile('index.html'), controller: this.controller }) 10977 .databaseAccess(true) 10978 } 10979 } 10980} 10981``` 10982 10983For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 10984 10985### deleteAllData 10986 10987static deleteAllData(incognito?: boolean): void 10988 10989Deletes all data in the Web SQL Database. 10990 10991**System capability**: SystemCapability.Web.Webview.Core 10992 10993**Parameters** 10994 10995| Name| Type | Mandatory| Description | 10996| ------ | ------ | ---- | ------------------ | 10997| 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.| 10998 10999**Example** 11000 11001```ts 11002// xxx.ets 11003import { webview } from '@kit.ArkWeb'; 11004import { BusinessError } from '@kit.BasicServicesKit'; 11005 11006@Entry 11007@Component 11008struct WebComponent { 11009 controller: webview.WebviewController = new webview.WebviewController(); 11010 11011 build() { 11012 Column() { 11013 Button('deleteAllData') 11014 .onClick(() => { 11015 try { 11016 webview.WebStorage.deleteAllData(); 11017 } catch (error) { 11018 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11019 } 11020 }) 11021 Web({ src: $rawfile('index.html'), controller: this.controller }) 11022 .databaseAccess(true) 11023 } 11024 } 11025} 11026``` 11027 11028For details about the HTML file loaded, see the HTML file loaded using the [deleteOrigin](#deleteorigin) API. 11029 11030## WebDataBase 11031 11032Implements a **WebDataBase** object. 11033 11034> **NOTE** 11035> 11036> You must load the **Web** component before calling the APIs in **WebDataBase**. 11037 11038### getHttpAuthCredentials 11039 11040static getHttpAuthCredentials(host: string, realm: string): Array\<string> 11041 11042Retrieves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. 11043 11044**System capability**: SystemCapability.Web.Webview.Core 11045 11046**Parameters** 11047 11048| Name| Type | Mandatory| Description | 11049| ------ | ------ | ---- | ---------------------------- | 11050| host | string | Yes | Host to which HTTP authentication credentials apply.| 11051| realm | string | Yes | Realm to which HTTP authentication credentials apply. | 11052 11053**Return value** 11054 11055| Type | Description | 11056| ----- | -------------------------------------------- | 11057| Array\<string> | Returns the array of the matching user names and passwords if the operation is successful; returns an empty array otherwise.| 11058 11059**Error codes** 11060 11061For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11062 11063| ID| Error Message | 11064| -------- | ------------------------------------------------------ | 11065| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11066 11067**Example** 11068 11069```ts 11070// xxx.ets 11071import { webview } from '@kit.ArkWeb'; 11072import { BusinessError } from '@kit.BasicServicesKit'; 11073 11074@Entry 11075@Component 11076struct WebComponent { 11077 controller: webview.WebviewController = new webview.WebviewController(); 11078 host: string = "www.spincast.org"; 11079 realm: string = "protected example"; 11080 username_password: string[] = []; 11081 11082 build() { 11083 Column() { 11084 Button('getHttpAuthCredentials') 11085 .onClick(() => { 11086 try { 11087 this.username_password = webview.WebDataBase.getHttpAuthCredentials(this.host, this.realm); 11088 console.log('num: ' + this.username_password.length); 11089 } catch (error) { 11090 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11091 } 11092 }) 11093 Web({ src: 'www.example.com', controller: this.controller }) 11094 } 11095 } 11096} 11097``` 11098 11099### saveHttpAuthCredentials 11100 11101static saveHttpAuthCredentials(host: string, realm: string, username: string, password: string): void 11102 11103Saves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. 11104 11105**System capability**: SystemCapability.Web.Webview.Core 11106 11107**Parameters** 11108 11109| Name | Type | Mandatory| Description | 11110| -------- | ------ | ---- | ---------------------------- | 11111| host | string | Yes | Host to which HTTP authentication credentials apply.| 11112| realm | string | Yes | Realm to which HTTP authentication credentials apply. | 11113| username | string | Yes | User name. | 11114| password | string | Yes | Password. | 11115 11116**Error codes** 11117 11118For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11119 11120| ID| Error Message | 11121| -------- | ------------------------------------------------------ | 11122| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11123 11124**Example** 11125 11126```ts 11127// xxx.ets 11128import { webview } from '@kit.ArkWeb'; 11129import { BusinessError } from '@kit.BasicServicesKit'; 11130 11131@Entry 11132@Component 11133struct WebComponent { 11134 controller: webview.WebviewController = new webview.WebviewController(); 11135 host: string = "www.spincast.org"; 11136 realm: string = "protected example"; 11137 11138 build() { 11139 Column() { 11140 Button('saveHttpAuthCredentials') 11141 .onClick(() => { 11142 try { 11143 webview.WebDataBase.saveHttpAuthCredentials(this.host, this.realm, "Stromgol", "Laroche"); 11144 } catch (error) { 11145 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11146 } 11147 }) 11148 Web({ src: 'www.example.com', controller: this.controller }) 11149 } 11150 } 11151} 11152``` 11153 11154### existHttpAuthCredentials 11155 11156static existHttpAuthCredentials(): boolean 11157 11158Checks whether any saved HTTP authentication credentials exist. This API returns the result synchronously. 11159 11160**System capability**: SystemCapability.Web.Webview.Core 11161 11162**Return value** 11163 11164| Type | Description | 11165| ------- | ------------------------------------------------------------ | 11166| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist; returns **false** otherwise.| 11167 11168**Example** 11169 11170```ts 11171// xxx.ets 11172import { webview } from '@kit.ArkWeb'; 11173import { BusinessError } from '@kit.BasicServicesKit'; 11174 11175@Entry 11176@Component 11177struct WebComponent { 11178 controller: webview.WebviewController = new webview.WebviewController(); 11179 11180 build() { 11181 Column() { 11182 Button('existHttpAuthCredentials') 11183 .onClick(() => { 11184 try { 11185 let result = webview.WebDataBase.existHttpAuthCredentials(); 11186 } catch (error) { 11187 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11188 } 11189 }) 11190 Web({ src: 'www.example.com', controller: this.controller }) 11191 } 11192 } 11193} 11194``` 11195 11196### deleteHttpAuthCredentials 11197 11198static deleteHttpAuthCredentials(): void 11199 11200Deletes all HTTP authentication credentials saved in the cache. This API returns the result synchronously. 11201 11202**System capability**: SystemCapability.Web.Webview.Core 11203 11204**Example** 11205 11206```ts 11207// xxx.ets 11208import { webview } from '@kit.ArkWeb'; 11209import { BusinessError } from '@kit.BasicServicesKit'; 11210 11211@Entry 11212@Component 11213struct WebComponent { 11214 controller: webview.WebviewController = new webview.WebviewController(); 11215 11216 build() { 11217 Column() { 11218 Button('deleteHttpAuthCredentials') 11219 .onClick(() => { 11220 try { 11221 webview.WebDataBase.deleteHttpAuthCredentials(); 11222 } catch (error) { 11223 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11224 } 11225 }) 11226 Web({ src: 'www.example.com', controller: this.controller }) 11227 } 11228 } 11229} 11230``` 11231 11232## GeolocationPermissions 11233 11234Implements a **GeolocationPermissions** object. 11235 11236> **NOTE** 11237> 11238> You must load the **Web** component before calling the APIs in **GeolocationPermissions**. 11239 11240### Required Permissions 11241 11242**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). 11243 11244### allowGeolocation 11245 11246static allowGeolocation(origin: string, incognito?: boolean): void 11247 11248Allows the specified origin to use the geolocation information. 11249 11250**System capability**: SystemCapability.Web.Webview.Core 11251 11252**Parameters** 11253 11254| Name| Type | Mandatory| Description | 11255| ------ | ------ | ---- | ------------------ | 11256| origin | string | Yes |Index of the origin.| 11257| 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.| 11258 11259**Error codes** 11260 11261For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11262 11263| ID| Error Message | 11264| -------- | ------------------------------------------------------ | 11265| 17100011 | Invalid origin. | 11266| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11267 11268**Example** 11269 11270```ts 11271// xxx.ets 11272import { webview } from '@kit.ArkWeb'; 11273import { BusinessError } from '@kit.BasicServicesKit'; 11274 11275@Entry 11276@Component 11277struct WebComponent { 11278 controller: webview.WebviewController = new webview.WebviewController(); 11279 origin: string = "file:///"; 11280 11281 build() { 11282 Column() { 11283 Button('allowGeolocation') 11284 .onClick(() => { 11285 try { 11286 webview.GeolocationPermissions.allowGeolocation(this.origin); 11287 } catch (error) { 11288 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11289 } 11290 }) 11291 Web({ src: 'www.example.com', controller: this.controller }) 11292 } 11293 } 11294} 11295``` 11296 11297### deleteGeolocation 11298 11299static deleteGeolocation(origin: string, incognito?: boolean): void 11300 11301Clears the geolocation permission status of a specified origin. 11302 11303**System capability**: SystemCapability.Web.Webview.Core 11304 11305**Parameters** 11306 11307| Name| Type | Mandatory| Description | 11308| ------ | ------ | ---- | ------------------ | 11309| origin | string | Yes | Index of the origin.| 11310| 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.| 11311 11312**Error codes** 11313 11314For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11315 11316| ID| Error Message | 11317| -------- | ------------------------------------------------------ | 11318| 17100011 | Invalid origin. | 11319| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11320 11321**Example** 11322 11323```ts 11324// xxx.ets 11325import { webview } from '@kit.ArkWeb'; 11326import { BusinessError } from '@kit.BasicServicesKit'; 11327 11328@Entry 11329@Component 11330struct WebComponent { 11331 controller: webview.WebviewController = new webview.WebviewController(); 11332 origin: string = "file:///"; 11333 11334 build() { 11335 Column() { 11336 Button('deleteGeolocation') 11337 .onClick(() => { 11338 try { 11339 webview.GeolocationPermissions.deleteGeolocation(this.origin); 11340 } catch (error) { 11341 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11342 } 11343 }) 11344 Web({ src: 'www.example.com', controller: this.controller }) 11345 } 11346 } 11347} 11348``` 11349 11350### getAccessibleGeolocation 11351 11352static getAccessibleGeolocation(origin: string, callback: AsyncCallback\<boolean>, incognito?: boolean): void 11353 11354Obtains the geolocation permission status of the specified origin. This API uses an asynchronous callback to return the result. 11355 11356**System capability**: SystemCapability.Web.Webview.Core 11357 11358**Parameters** 11359 11360| Name | Type | Mandatory| Description | 11361| -------- | ---------------------- | ---- | ------------------------------------------------------------ | 11362| origin | string | Yes | Index of the origin. | 11363| 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.| 11364| 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.| 11365 11366**Error codes** 11367 11368For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11369 11370| ID| Error Message | 11371| -------- | ------------------------------------------------------ | 11372| 17100011 | Invalid origin. | 11373| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11374 11375**Example** 11376 11377```ts 11378// xxx.ets 11379import { webview } from '@kit.ArkWeb'; 11380import { BusinessError } from '@kit.BasicServicesKit'; 11381 11382@Entry 11383@Component 11384struct WebComponent { 11385 controller: webview.WebviewController = new webview.WebviewController(); 11386 origin: string = "file:///"; 11387 11388 build() { 11389 Column() { 11390 Button('getAccessibleGeolocation') 11391 .onClick(() => { 11392 try { 11393 webview.GeolocationPermissions.getAccessibleGeolocation(this.origin, (error, result) => { 11394 if (error) { 11395 console.error(`getAccessibleGeolocationAsync error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11396 return; 11397 } 11398 console.log('getAccessibleGeolocationAsync result: ' + result); 11399 }); 11400 } catch (error) { 11401 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11402 } 11403 }) 11404 Web({ src: 'www.example.com', controller: this.controller }) 11405 } 11406 } 11407} 11408``` 11409 11410### getAccessibleGeolocation 11411 11412static getAccessibleGeolocation(origin: string, incognito?: boolean): Promise\<boolean> 11413 11414Obtains the geolocation permission status of the specified origin. This API uses a promise to return the result. 11415 11416**System capability**: SystemCapability.Web.Webview.Core 11417 11418**Parameters** 11419 11420| Name| Type| Mandatory| Description | 11421| ------ | -------- | ---- | -------------------- | 11422| origin | string | Yes | Index of the origin.| 11423| 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.| 11424 11425**Return value** 11426 11427| Type | Description | 11428| ---------------- | ------------------------------------------------------------ | 11429| 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.| 11430 11431**Error codes** 11432 11433For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11434 11435| ID| Error Message | 11436| -------- | ------------------------------------------------------ | 11437| 17100011 | Invalid origin. | 11438| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11439 11440**Example** 11441 11442```ts 11443// xxx.ets 11444import { webview } from '@kit.ArkWeb'; 11445import { BusinessError } from '@kit.BasicServicesKit'; 11446 11447@Entry 11448@Component 11449struct WebComponent { 11450 controller: webview.WebviewController = new webview.WebviewController(); 11451 origin: string = "file:///"; 11452 11453 build() { 11454 Column() { 11455 Button('getAccessibleGeolocation') 11456 .onClick(() => { 11457 try { 11458 webview.GeolocationPermissions.getAccessibleGeolocation(this.origin) 11459 .then(result => { 11460 console.log('getAccessibleGeolocationPromise result: ' + result); 11461 }).catch((error: BusinessError) => { 11462 console.error(`getAccessibleGeolocationPromise error, ErrorCode: ${error.code}, Message: ${error.message}`); 11463 }); 11464 } catch (error) { 11465 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11466 } 11467 }) 11468 Web({ src: 'www.example.com', controller: this.controller }) 11469 } 11470 } 11471} 11472``` 11473 11474### getStoredGeolocation 11475 11476static getStoredGeolocation(callback: AsyncCallback\<Array\<string>>, incognito?: boolean): void 11477 11478Obtains the geolocation permission status of all origins. This API uses an asynchronous callback to return the result. 11479 11480**System capability**: SystemCapability.Web.Webview.Core 11481 11482**Parameters** 11483 11484| Name | Type | Mandatory| Description | 11485| -------- | ---------------------------- | ---- | ---------------------------------------- | 11486| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return the geolocation permission status of all origins.| 11487| 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.| 11488 11489**Error codes** 11490 11491For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11492 11493| ID| Error Message | 11494| -------- | ------------------------------------------------------ | 11495| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11496 11497**Example** 11498 11499```ts 11500// xxx.ets 11501import { webview } from '@kit.ArkWeb'; 11502import { BusinessError } from '@kit.BasicServicesKit'; 11503 11504@Entry 11505@Component 11506struct WebComponent { 11507 controller: webview.WebviewController = new webview.WebviewController(); 11508 11509 build() { 11510 Column() { 11511 Button('getStoredGeolocation') 11512 .onClick(() => { 11513 try { 11514 webview.GeolocationPermissions.getStoredGeolocation((error, origins) => { 11515 if (error) { 11516 console.error(`getStoredGeolocationAsync error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11517 return; 11518 } 11519 let origins_str: string = origins.join(); 11520 console.log('getStoredGeolocationAsync origins: ' + origins_str); 11521 }); 11522 } catch (error) { 11523 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11524 } 11525 }) 11526 Web({ src: 'www.example.com', controller: this.controller }) 11527 } 11528 } 11529} 11530``` 11531 11532### getStoredGeolocation 11533 11534static getStoredGeolocation(incognito?: boolean): Promise\<Array\<string>> 11535 11536Obtains the geolocation permission status of all origins. This API uses a promise to return the result. 11537 11538**System capability**: SystemCapability.Web.Webview.Core 11539 11540**Parameters** 11541 11542| Name | Type | Mandatory| Description | 11543| -------- | ---------------------------- | ---- | ---------------------------------------- | 11544| 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.| 11545 11546**Return value** 11547 11548| Type | Description | 11549| ---------------------- | --------------------------------------------------------- | 11550| Promise\<Array\<string>> | Promise used to return the geolocation permission status of all origins.| 11551 11552**Error codes** 11553 11554For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11555 11556| ID| Error Message | 11557| -------- | ------------------------------------------------------ | 11558| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 11559 11560**Example** 11561 11562```ts 11563// xxx.ets 11564import { webview } from '@kit.ArkWeb'; 11565import { BusinessError } from '@kit.BasicServicesKit'; 11566 11567@Entry 11568@Component 11569struct WebComponent { 11570 controller: webview.WebviewController = new webview.WebviewController(); 11571 11572 build() { 11573 Column() { 11574 Button('getStoredGeolocation') 11575 .onClick(() => { 11576 try { 11577 webview.GeolocationPermissions.getStoredGeolocation() 11578 .then(origins => { 11579 let origins_str: string = origins.join(); 11580 console.log('getStoredGeolocationPromise origins: ' + origins_str); 11581 }).catch((error: BusinessError) => { 11582 console.error(`getStoredGeolocationPromise error, ErrorCode: ${error.code}, Message: ${error.message}`); 11583 }); 11584 } catch (error) { 11585 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11586 } 11587 }) 11588 Web({ src: 'www.example.com', controller: this.controller }) 11589 } 11590 } 11591} 11592``` 11593 11594### deleteAllGeolocation 11595 11596static deleteAllGeolocation(incognito?: boolean): void 11597 11598Clears the geolocation permission status of all sources. 11599 11600**System capability**: SystemCapability.Web.Webview.Core 11601 11602**Parameters** 11603 11604| Name | Type | Mandatory| Description | 11605| -------- | ---------------------------- | ---- | ---------------------------------------- | 11606| 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.| 11607 11608**Example** 11609 11610```ts 11611// xxx.ets 11612import { webview } from '@kit.ArkWeb'; 11613import { BusinessError } from '@kit.BasicServicesKit'; 11614 11615@Entry 11616@Component 11617struct WebComponent { 11618 controller: webview.WebviewController = new webview.WebviewController(); 11619 11620 build() { 11621 Column() { 11622 Button('deleteAllGeolocation') 11623 .onClick(() => { 11624 try { 11625 webview.GeolocationPermissions.deleteAllGeolocation(); 11626 } catch (error) { 11627 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 11628 } 11629 }) 11630 Web({ src: 'www.example.com', controller: this.controller }) 11631 } 11632 } 11633} 11634``` 11635## WebHeader 11636 11637Describes the request/response header returned by the **Web** component. 11638 11639**System capability**: SystemCapability.Web.Webview.Core 11640 11641| Name | Type | Readable| Writable|Description | 11642| ----------- | ------ | -----|------|------------------- | 11643| headerKey | string | Yes| Yes| Key of the request/response header. | 11644| headerValue | string | Yes| Yes| Value of the request/response header.| 11645 11646## RequestInfo<sup>12+</sup> 11647 11648Describes the information about the resource request sent by the **Web** component. 11649 11650**System capability**: SystemCapability.Web.Webview.Core 11651 11652| Name | Type | Readable| Writable|Description | 11653| ---------| ------ | -----|------|-------- | 11654| url | string | Yes| Yes| URL of the request. | 11655| method | string | Yes| Yes| Method of the request. | 11656| formData | string | Yes| Yes| Form data in the request body.| 11657 11658## WebHitTestType 11659 11660The [getHitTest](#gethittest) API is used to indicate a cursor node. 11661 11662**System capability**: SystemCapability.Web.Webview.Core 11663 11664| Name | Value| Description | 11665| ------------- | -- |----------------------------------------- | 11666| EditText | 0 |Editable area. | 11667| Email | 1 |Email address. | 11668| HttpAnchor | 2 |Hyperlink, where **src** is **http**. | 11669| HttpAnchorImg | 3 |Image with a hyperlink, where **src** is http + HTML::img.| 11670| Img | 4 |HTML::img tag. | 11671| Map | 5 |Geographical address. | 11672| Phone | 6 |Phone number. | 11673| Unknown | 7 |Unknown content. | 11674 11675## SecurityLevel<sup>11+</sup> 11676 11677Defines the security level of the web page. 11678 11679**System capability**: SystemCapability.Web.Webview.Core 11680 11681| Name | Value| Description | 11682| ------------- | -- |----------------------------------------- | 11683| 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.| 11684| SECURE | 1 |The web page is secure, using the HTTPS protocol and a trusted certificate.| 11685| 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.| 11686| 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.| 11687 11688## HitTestValue 11689 11690Provides the element information of the area being clicked. For details about the sample code, see [getHitTestValue](#gethittestvalue). 11691 11692**System capability**: SystemCapability.Web.Webview.Core 11693 11694| Name| Type| Readable| Writable| Description| 11695| ---- | ---- | ---- | ---- |---- | 11696| type | [WebHitTestType](#webhittesttype) | Yes| Yes| Element type of the area being clicked.| 11697| 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.| 11698 11699## WebMessage 11700 11701type WebMessage = ArrayBuffer | string 11702 11703Describes the data types supported for [WebMessagePort](#webmessageport). 11704 11705**System capability**: SystemCapability.Web.Webview.Core 11706 11707| Type | Description | 11708| -------- | -------------------------------------- | 11709| string | String type.| 11710| ArrayBuffer | Binary type.| 11711 11712## JsMessageType<sup>10+</sup> 11713 11714Describes the type of the returned result of script execution using [runJavaScriptExt](#runjavascriptext10). 11715 11716**System capability**: SystemCapability.Web.Webview.Core 11717 11718| Name | Value| Description | 11719| ------------ | -- |--------------------------------- | 11720| NOT_SUPPORT | 0 |Unsupported data type.| 11721| STRING | 1 |String type.| 11722| NUMBER | 2 |Number type.| 11723| BOOLEAN | 3 |Boolean type.| 11724| ARRAY_BUFFER | 4 |Raw binary data buffer.| 11725| ARRAY | 5 |Array type.| 11726 11727## WebMessageType<sup>10+</sup> 11728 11729Describes the data type supported by the [webMessagePort](#webmessageport) API. 11730 11731**System capability**: SystemCapability.Web.Webview.Core 11732 11733| Name | Value| Description | 11734| ------------ | -- |------------------------------- | 11735| NOT_SUPPORT | 0 |Unsupported data type.| 11736| STRING | 1 |String type.| 11737| NUMBER | 2 |Number type.| 11738| BOOLEAN | 3 |Boolean type.| 11739| ARRAY_BUFFER | 4 |Raw binary data buffer.| 11740| ARRAY | 5 |Array type.| 11741| ERROR | 6 |Error object type.| 11742 11743## MediaPlaybackState<sup>12+</sup> 11744 11745Enumerates the playback states on the current web page. 11746 11747**System capability**: SystemCapability.Web.Webview.Core 11748 11749| Name | Value | Description | 11750| ------- | ---- | ------------------ | 11751| NONE | 0 | No audio or video playback is started on the page.| 11752| PLAYING | 1 | The audio and video on the page are being played.| 11753| PAUSED | 2 | The audio and video on the page are paused. | 11754| STOPPED | 3 | The audio and video on the page are stopped. | 11755 11756## RenderProcessMode<sup>12+</sup> 11757 11758Enumerates the ArkWeb render subprocess modes. 11759 11760**System capability**: SystemCapability.Web.Webview.Core 11761 11762| Name | Value| Description | 11763| ------------- | -- |----------------------------------------- | 11764| SINGLE | 0 |ArkWeb single render subprocess mode. In this mode, multiple **Web** components share one render subprocess.| 11765| MULTIPLE | 1 |ArkWeb multi-render subprocess mode. In this mode, each **Web** component has a rendering subprocess.| 11766 11767 11768## JsMessageExt<sup>10+</sup> 11769 11770Implements the **JsMessageExt** data object that is returned after script execution using the [runJavaScriptExt](#runjavascriptext10) API. 11771 11772### getType<sup>10+</sup> 11773 11774getType(): JsMessageType 11775 11776Obtains the type of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 11777 11778**System capability**: SystemCapability.Web.Webview.Core 11779 11780**Return value** 11781 11782| Type | Description | 11783| --------------| --------------------------------------------------------- | 11784| [JsMessageType](#jsmessagetype10) | Type of the data object that is returned after script execution using the [runJavaScriptExt](#runjavascriptext10) API.| 11785 11786### getString<sup>10+</sup> 11787 11788getString(): string 11789 11790Obtains string-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 11791 11792**System capability**: SystemCapability.Web.Webview.Core 11793 11794**Return value** 11795 11796| Type | Description | 11797| --------------| ------------- | 11798| string | Data of the string type.| 11799 11800**Error codes** 11801 11802For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11803 11804| ID| Error Message | 11805| -------- | ------------------------------------- | 11806| 17100014 | The type and value of the message do not match. | 11807 11808### getNumber<sup>10+</sup> 11809 11810getNumber(): number 11811 11812Obtains number-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 11813 11814**System capability**: SystemCapability.Web.Webview.Core 11815 11816**Return value** 11817 11818| Type | Description | 11819| --------------| ------------- | 11820| number | Data of the number type.| 11821 11822**Error codes** 11823 11824For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11825 11826| ID| Error Message | 11827| -------- | ------------------------------------- | 11828| 17100014 | The type and value of the message do not match. | 11829 11830### getBoolean<sup>10+</sup> 11831 11832getBoolean(): boolean 11833 11834Obtains Boolean-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 11835 11836**System capability**: SystemCapability.Web.Webview.Core 11837 11838**Return value** 11839 11840| Type | Description | 11841| --------------| ------------- | 11842| boolean | Data of the Boolean type.| 11843 11844**Error codes** 11845 11846For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11847 11848| ID| Error Message | 11849| -------- | ------------------------------------- | 11850| 17100014 | The type and value of the message do not match. | 11851 11852### getArrayBuffer<sup>10+</sup> 11853 11854getArrayBuffer(): ArrayBuffer 11855 11856Obtains raw binary data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 11857 11858**System capability**: SystemCapability.Web.Webview.Core 11859 11860**Return value** 11861 11862| Type | Description | 11863| --------------| ------------- | 11864| ArrayBuffer | Raw binary data.| 11865 11866**Error codes** 11867 11868For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11869 11870| ID| Error Message | 11871| -------- | ------------------------------------- | 11872| 17100014 | The type and value of the message do not match. | 11873 11874### getArray<sup>10+</sup> 11875 11876getArray(): Array\<string | number | boolean\> 11877 11878Obtains array-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10). 11879 11880**System capability**: SystemCapability.Web.Webview.Core 11881 11882**Return value** 11883 11884| Type | Description | 11885| --------------| ------------- | 11886| Array\<string \| number \| boolean\> | Data of the array type.| 11887 11888**Error codes** 11889 11890For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11891 11892| ID| Error Message | 11893| -------- | ------------------------------------- | 11894| 17100014 | The type and value of the message do not match. | 11895 11896## WebMessageExt<sup>10+</sup> 11897 11898Represents a data object received and sent through the [webMessagePort](#webmessageport) API. 11899 11900### getType<sup>10+</sup> 11901 11902getType(): WebMessageType 11903 11904Obtains the type of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11905 11906**System capability**: SystemCapability.Web.Webview.Core 11907 11908**Return value** 11909 11910| Type | Description | 11911| --------------| --------------------------------------------------------- | 11912| [WebMessageType](#webmessagetype10) | Data type supported by the [webMessagePort](#webmessageport) API.| 11913 11914### getString<sup>10+</sup> 11915 11916getString(): string 11917 11918Obtains string-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11919 11920**System capability**: SystemCapability.Web.Webview.Core 11921 11922**Return value** 11923 11924| Type | Description | 11925| --------------| ------------- | 11926| string | Data of the string type.| 11927 11928**Error codes** 11929 11930For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11931 11932| ID| Error Message | 11933| -------- | ------------------------------------- | 11934| 17100014 | The type and value of the message do not match. | 11935 11936### getNumber<sup>10+</sup> 11937 11938getNumber(): number 11939 11940Obtains number-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11941 11942**System capability**: SystemCapability.Web.Webview.Core 11943 11944**Return value** 11945 11946| Type | Description | 11947| --------------| ------------- | 11948| number | Data of the number type.| 11949 11950**Error codes** 11951 11952For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11953 11954| ID| Error Message | 11955| -------- | ------------------------------------- | 11956| 17100014 | The type and value of the message do not match. | 11957 11958### getBoolean<sup>10+</sup> 11959 11960getBoolean(): boolean 11961 11962Obtains Boolean-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11963 11964**System capability**: SystemCapability.Web.Webview.Core 11965 11966**Return value** 11967 11968| Type | Description | 11969| --------------| ------------- | 11970| boolean | Data of the Boolean type.| 11971 11972**Error codes** 11973 11974For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11975 11976| ID| Error Message | 11977| -------- | ------------------------------------- | 11978| 17100014 | The type and value of the message do not match. | 11979 11980### getArrayBuffer<sup>10+</sup> 11981 11982getArrayBuffer(): ArrayBuffer 11983 11984Obtains raw binary data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 11985 11986**System capability**: SystemCapability.Web.Webview.Core 11987 11988**Return value** 11989 11990| Type | Description | 11991| --------------| ------------- | 11992| ArrayBuffer | Raw binary data.| 11993 11994**Error codes** 11995 11996For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 11997 11998| ID| Error Message | 11999| -------- | ------------------------------------- | 12000| 17100014 | The type and value of the message do not match. | 12001 12002### getArray<sup>10+</sup> 12003 12004getArray(): Array\<string | number | boolean\> 12005 12006Obtains array-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12007 12008**System capability**: SystemCapability.Web.Webview.Core 12009 12010**Return value** 12011 12012| Type | Description | 12013| --------------| ------------- | 12014| Array\<string \| number \| boolean\> | Data of the array type.| 12015 12016**Error codes** 12017 12018For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12019 12020| ID| Error Message | 12021| -------- | ------------------------------------- | 12022| 17100014 | The type and value of the message do not match. | 12023 12024### getError<sup>10+</sup> 12025 12026getError(): Error 12027 12028Obtains the error-object-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12029 12030**System capability**: SystemCapability.Web.Webview.Core 12031 12032**Return value** 12033 12034| Type | Description | 12035| --------------| ------------- | 12036| Error | Data of the error object type.| 12037 12038**Error codes** 12039 12040For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12041 12042| ID| Error Message | 12043| -------- | ------------------------------------- | 12044| 17100014 | The type and value of the message do not match. | 12045 12046### setType<sup>10+</sup> 12047 12048setType(type: WebMessageType): void 12049 12050Sets the type for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12051 12052**System capability**: SystemCapability.Web.Webview.Core 12053 12054**Parameters** 12055 12056| Name| Type | Mandatory| Description | 12057| ------ | ------ | ---- | ---------------------- | 12058| type | [WebMessageType](#webmessagetype10) | Yes | Data type supported by the [webMessagePort](#webmessageport) API.| 12059 12060**Error codes** 12061 12062| ID| Error Message | 12063| -------- | ------------------------------------- | 12064| 17100014 | The type and value of the message do not match. | 12065| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12066 12067### setString<sup>10+</sup> 12068 12069setString(message: string): void 12070 12071Sets the string-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12072 12073**System capability**: SystemCapability.Web.Webview.Core 12074 12075**Parameters** 12076 12077| Name| Type | Mandatory| Description | 12078| ------ | ------ | ---- | -------------------- | 12079| message | string | Yes | String type.| 12080 12081**Error codes** 12082 12083| ID| Error Message | 12084| -------- | ------------------------------------- | 12085| 17100014 | The type and value of the message do not match. | 12086| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12087 12088### setNumber<sup>10+</sup> 12089 12090setNumber(message: number): void 12091 12092Sets the number-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12093 12094**System capability**: SystemCapability.Web.Webview.Core 12095 12096**Parameters** 12097 12098| Name| Type | Mandatory| Description | 12099| ------ | ------ | ---- | -------------------- | 12100| message | number | Yes | Data of the number type.| 12101 12102**Error codes** 12103 12104| ID| Error Message | 12105| -------- | ------------------------------------- | 12106| 17100014 | The type and value of the message do not match. | 12107| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12108 12109### setBoolean<sup>10+</sup> 12110 12111setBoolean(message: boolean): void 12112 12113Sets the Boolean-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12114 12115**System capability**: SystemCapability.Web.Webview.Core 12116 12117**Parameters** 12118 12119| Name| Type | Mandatory| Description | 12120| ------ | ------ | ---- | -------------------- | 12121| message | boolean | Yes | Data of the Boolean type.| 12122 12123**Error codes** 12124 12125| ID| Error Message | 12126| -------- | ------------------------------------- | 12127| 17100014 | The type and value of the message do not match. | 12128| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12129 12130### setArrayBuffer<sup>10+</sup> 12131 12132setArrayBuffer(message: ArrayBuffer): void 12133 12134Sets the raw binary data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12135 12136**System capability**: SystemCapability.Web.Webview.Core 12137 12138**Parameters** 12139 12140| Name| Type | Mandatory| Description | 12141| ------ | ------ | ---- | -------------------- | 12142| message | ArrayBuffer | Yes | Raw binary data.| 12143 12144**Error codes** 12145 12146For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12147 12148| ID| Error Message | 12149| -------- | ------------------------------------- | 12150| 17100014 | The type and value of the message do not match. | 12151| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12152 12153### setArray<sup>10+</sup> 12154 12155setArray(message: Array\<string | number | boolean\>): void 12156 12157Sets the array-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12158 12159**System capability**: SystemCapability.Web.Webview.Core 12160 12161**Parameters** 12162 12163| Name| Type | Mandatory| Description | 12164| ------ | ------ | ---- | -------------------- | 12165| message | Array\<string \| number \| boolean\> | Yes | Data of the array type.| 12166 12167**Error codes** 12168 12169For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12170 12171| ID| Error Message | 12172| -------- | ------------------------------------- | 12173| 17100014 | The type and value of the message do not match. | 12174| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12175 12176### setError<sup>10+</sup> 12177 12178setError(message: Error): void 12179 12180Sets the error-object-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 12181 12182**System capability**: SystemCapability.Web.Webview.Core 12183 12184**Parameters** 12185 12186| Name| Type | Mandatory| Description | 12187| ------ | ------ | ---- | -------------------- | 12188| message | Error | Yes | Data of the error object type.| 12189 12190**Error codes** 12191 12192For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12193 12194| ID| Error Message | 12195| -------- | ------------------------------------- | 12196| 17100014 | The type and value of the message do not match. | 12197| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12198 12199## WebStorageOrigin 12200 12201Provides usage information of the Web SQL Database. 12202 12203**System capability**: SystemCapability.Web.Webview.Core 12204 12205| Name | Type | Readable| Writable| Description| 12206| ------ | ------ | ---- | ---- | ---- | 12207| origin | string | Yes | Yes| Index of the origin.| 12208| usage | number | Yes | Yes| Storage usage of the origin. | 12209| quota | number | Yes | Yes| Storage quota of the origin. | 12210 12211## BackForwardList 12212 12213Provides the historical information list of the current webview. 12214 12215**System capability**: SystemCapability.Web.Webview.Core 12216 12217| Name | Type | Readable| Writable| Description | 12218| ------------ | ------ | ---- | ---- | ------------------------------------------------------------ | 12219| currentIndex | number | Yes | Yes | Index of the current page in the page history stack. | 12220| 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.| 12221 12222### getItemAtIndex 12223 12224getItemAtIndex(index: number): HistoryItem 12225 12226Obtains the page record with the specified index in the history stack. 12227 12228**System capability**: SystemCapability.Web.Webview.Core 12229 12230**Parameters** 12231 12232| Name| Type | Mandatory| Description | 12233| ------ | ------ | ---- | ---------------------- | 12234| index | number | Yes | Index of the target page record in the history stack.| 12235 12236**Return value** 12237 12238| Type | Description | 12239| --------------------------- | ------------ | 12240| [HistoryItem](#historyitem) | Historical page record.| 12241 12242**Error codes** 12243 12244For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 12245 12246| ID| Error Message | 12247| -------- | ------------------------------------------------------ | 12248| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 12249 12250**Example** 12251 12252```ts 12253// xxx.ets 12254import { webview } from '@kit.ArkWeb'; 12255import { BusinessError } from '@kit.BasicServicesKit'; 12256import { image } from '@kit.ImageKit'; 12257 12258@Entry 12259@Component 12260struct WebComponent { 12261 controller: webview.WebviewController = new webview.WebviewController(); 12262 @State icon: image.PixelMap | undefined = undefined; 12263 12264 build() { 12265 Column() { 12266 Button('getBackForwardEntries') 12267 .onClick(() => { 12268 try { 12269 let list = this.controller.getBackForwardEntries(); 12270 let historyItem = list.getItemAtIndex(list.currentIndex); 12271 console.log("HistoryItem: " + JSON.stringify(historyItem)); 12272 this.icon = historyItem.icon; 12273 } catch (error) { 12274 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12275 } 12276 }) 12277 Web({ src: 'www.example.com', controller: this.controller }) 12278 } 12279 } 12280} 12281``` 12282 12283## HistoryItem 12284 12285Describes a historical page record. 12286 12287**System capability**: SystemCapability.Web.Webview.Core 12288 12289| Name | Type | Readable| Writable| Description | 12290| ------------- | -------------------------------------- | ---- | ---- | ---------------------------- | 12291| icon | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | No | **PixelMap** object of the icon on the historical page.| 12292| historyUrl | string | Yes | Yes | URL of the historical page. | 12293| historyRawUrl | string | Yes | Yes | Original URL of the historical page. | 12294| title | string | Yes | Yes | Title of the historical page. | 12295 12296## WebCustomScheme 12297 12298Defines a custom URL scheme. 12299 12300**System capability**: SystemCapability.Web.Webview.Core 12301 12302| Name | Type | Readable| Writable| Description | 12303| -------------- | --------- | ---- | ---- | ---------------------------- | 12304| 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. | 12305| isSupportCORS | boolean | Yes | Yes | Whether to support cross-origin resource sharing (CORS). | 12306| isSupportFetch | boolean | Yes | Yes | Whether to support fetch requests. | 12307| 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. | 12308| isLocal<sup>12+</sup> | boolean | Yes | Yes | Whether the scheme is treated with the same security rules as those applied to file URLs. | 12309| 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. | 12310| isSecure<sup>12+</sup> | boolean | Yes | Yes | Whether the scheme is treated with the same security rules as those applied to HTTPS URLs. | 12311| 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**. | 12312| isCodeCacheSupported<sup>12+</sup> | boolean | Yes | Yes | Whether JavaScript resources loaded with the scheme can be used to create a code cache. | 12313 12314## SecureDnsMode<sup>10+</sup> 12315 12316Describes the mode in which the **Web** component uses HTTPDNS. 12317 12318**System capability**: SystemCapability.Web.Webview.Core 12319 12320| Name | Value| Description | 12321| ------------- | -- |----------------------------------------- | 12322| OFF | 0 |HTTPDNS is not used. This value can be used to revoke the previously used HTTPDNS configuration.| 12323| 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.| 12324| SECURE_ONLY | 2 |The specified HTTPDNS server is forcibly used for DNS resolution.| 12325 12326## WebDownloadState<sup>11+</sup> 12327 12328Describes the state of a download task. 12329 12330**System capability**: SystemCapability.Web.Webview.Core 12331 12332| Name | Value| Description | 12333| ------------- | -- |----------------------------------------- | 12334| IN_PROGRESS | 0 |The download task is in progress.| 12335| COMPLETED | 1 |The download task is completed.| 12336| CANCELED | 2 |The download task has been canceled.| 12337| INTERRUPTED | 3 |The download task is interrupted.| 12338| PENDING | 4 |The download task is pending.| 12339| PAUSED | 5 |The download task is paused.| 12340| UNKNOWN | 6 |The state of the download task is unknown.| 12341 12342## WebDownloadErrorCode<sup>11+</sup> 12343 12344Describes the download task error code. 12345 12346**System capability**: SystemCapability.Web.Webview.Core 12347 12348| Name | Value| Description | 12349| ------------- | -- |----------------------------------------- | 12350| ERROR_UNKNOWN | 0 |Unknown error.| 12351| FILE_FAILED | 1 | Failed to operate the file.| 12352| FILE_ACCESS_DENIED | 2 | No permission to access the file.| 12353| FILE_NO_SPACE | 3 | The disk space is insufficient.| 12354| FILE_NAME_TOO_LONG | 5 | The file name is too long.| 12355| FILE_TOO_LARGE | 6 | The file is too large.| 12356| FILE_TRANSIENT_ERROR | 10 | Some temporary issues occur, such as insufficient memory, files in use, and too many files open at the same time.| 12357| FILE_BLOCKED | 11 | Access to the file is blocked due to certain local policies.| 12358| FILE_TOO_SHORT | 13 | The file to resume downloading is not long enough. It may not exist.| 12359| FILE_HASH_MISMATCH | 14 | Hash mismatch.| 12360| FILE_SAME_AS_SOURCE | 15 | The file already exists.| 12361| NETWORK_FAILED | 20 | Common network error.| 12362| NETWORK_TIMEOUT | 21 | Network connection timeout.| 12363| NETWORK_DISCONNECTED | 22 | Network disconnected.| 12364| NETWORK_SERVER_DOWN | 23 | The server is shut down.| 12365| NETWORK_INVALID_REQUEST | 24 | Invalid network request. The request may be redirected to an unsupported scheme or an invalid URL.| 12366| SERVER_FAILED | 30 | The server returns a general error.| 12367| SERVER_NO_RANGE | 31 | The server does not support the range request.| 12368| SERVER_BAD_CONTENT | 33 | The server does not have the requested data.| 12369| SERVER_UNAUTHORIZED | 34 | The file cannot be downloaded from the server.| 12370| SERVER_CERT_PROBLEM | 35 | The server certificate is incorrect.| 12371| SERVER_FORBIDDEN | 36 | The access to the server is forbidden.| 12372| SERVER_UNREACHABLE | 37 | The server cannot be accessed.| 12373| SERVER_CONTENT_LENGTH_MISMATCH | 38 | The received data does not match the content length.| 12374| SERVER_CROSS_ORIGIN_REDIRECT | 39 | An unexpected cross-site redirection occurs.| 12375| USER_CANCELED | 40 | The user cancels the download.| 12376| USER_SHUTDOWN | 41 | The user closes the application.| 12377| CRASH | 50 | The application crashes.| 12378 12379## WebDownloadItem<sup>11+</sup> 12380 12381 Implements a **WebDownloadItem** object. You can use this object to perform operations on the corresponding download task. 12382 12383> **NOTE** 12384> 12385> During the download, the download process is notified to the user through **WebDownloadDelegate**. The user can operate the download task through the **WebDownloadItem** parameter. 12386 12387### getGuid<sup>11+</sup> 12388 12389getGuid(): string 12390 12391Obtains the unique ID of this download task. 12392 12393**System capability**: SystemCapability.Web.Webview.Core 12394 12395**Return value** 12396 12397| Type | Description | 12398| ------ | ------------------------- | 12399| string | Unique ID of the download task.| 12400 12401**Example** 12402 12403```ts 12404// xxx.ets 12405import { webview } from '@kit.ArkWeb'; 12406import { BusinessError } from '@kit.BasicServicesKit'; 12407 12408@Entry 12409@Component 12410struct WebComponent { 12411 controller: webview.WebviewController = new webview.WebviewController(); 12412 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12413 12414 build() { 12415 Column() { 12416 Button('setDownloadDelegate') 12417 .onClick(() => { 12418 try { 12419 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12420 console.log("will start a download."); 12421 // Pass in a download path and start the download. 12422 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12423 }) 12424 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12425 console.log("download update guid: " + webDownloadItem.getGuid()); 12426 }) 12427 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12428 console.log("download failed guid: " + webDownloadItem.getGuid()); 12429 }) 12430 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12431 console.log("download finish guid: " + webDownloadItem.getGuid()); 12432 }) 12433 this.controller.setDownloadDelegate(this.delegate); 12434 } catch (error) { 12435 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12436 } 12437 }) 12438 Button('startDownload') 12439 .onClick(() => { 12440 try { 12441 this.controller.startDownload('https://www.example.com'); 12442 } catch (error) { 12443 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12444 } 12445 }) 12446 Web({ src: 'www.example.com', controller: this.controller }) 12447 } 12448 } 12449} 12450``` 12451 12452### getCurrentSpeed<sup>11+</sup> 12453 12454getCurrentSpeed(): number 12455 12456Obtains the download speed, in bytes per second. 12457 12458**System capability**: SystemCapability.Web.Webview.Core 12459 12460**Return value** 12461 12462| Type | Description | 12463| ------ | ------------------------- | 12464| number | Download speed, in bytes per second.| 12465 12466**Example** 12467 12468```ts 12469// xxx.ets 12470import { webview } from '@kit.ArkWeb'; 12471import { BusinessError } from '@kit.BasicServicesKit'; 12472 12473@Entry 12474@Component 12475struct WebComponent { 12476 controller: webview.WebviewController = new webview.WebviewController(); 12477 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12478 12479 build() { 12480 Column() { 12481 Button('setDownloadDelegate') 12482 .onClick(() => { 12483 try { 12484 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12485 console.log("will start a download."); 12486 // Pass in a download path and start the download. 12487 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12488 }) 12489 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12490 console.log("download update current speed: " + webDownloadItem.getCurrentSpeed()); 12491 }) 12492 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12493 console.log("download failed guid: " + webDownloadItem.getGuid()); 12494 }) 12495 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12496 console.log("download finish guid: " + webDownloadItem.getGuid()); 12497 }) 12498 this.controller.setDownloadDelegate(this.delegate); 12499 } catch (error) { 12500 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12501 } 12502 }) 12503 Button('startDownload') 12504 .onClick(() => { 12505 try { 12506 this.controller.startDownload('https://www.example.com'); 12507 } catch (error) { 12508 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12509 } 12510 }) 12511 Web({ src: 'www.example.com', controller: this.controller }) 12512 } 12513 } 12514} 12515``` 12516 12517### getPercentComplete<sup>11+</sup> 12518 12519getPercentComplete(): number 12520 12521Obtains the download progress. The value **100** indicates that the download is complete. 12522 12523**System capability**: SystemCapability.Web.Webview.Core 12524 12525**Return value** 12526 12527| Type | Description | 12528| ------ | ------------------------- | 12529| number | Download progress. The value **100** indicates that the download is complete.| 12530 12531**Example** 12532 12533```ts 12534// xxx.ets 12535import { webview } from '@kit.ArkWeb'; 12536import { BusinessError } from '@kit.BasicServicesKit'; 12537 12538@Entry 12539@Component 12540struct WebComponent { 12541 controller: webview.WebviewController = new webview.WebviewController(); 12542 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12543 12544 build() { 12545 Column() { 12546 Button('setDownloadDelegate') 12547 .onClick(() => { 12548 try { 12549 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12550 console.log("will start a download."); 12551 // Pass in a download path and start the download. 12552 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12553 }) 12554 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12555 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12556 }) 12557 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12558 console.log("download failed guid: " + webDownloadItem.getGuid()); 12559 }) 12560 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12561 console.log("download finish guid: " + webDownloadItem.getGuid()); 12562 }) 12563 this.controller.setDownloadDelegate(this.delegate); 12564 } catch (error) { 12565 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12566 } 12567 }) 12568 Button('startDownload') 12569 .onClick(() => { 12570 try { 12571 this.controller.startDownload('https://www.example.com'); 12572 } catch (error) { 12573 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12574 } 12575 }) 12576 Web({ src: 'www.example.com', controller: this.controller }) 12577 } 12578 } 12579} 12580``` 12581 12582### getTotalBytes<sup>11+</sup> 12583 12584getTotalBytes(): number 12585 12586Obtains the total length of the file to be downloaded. 12587 12588**System capability**: SystemCapability.Web.Webview.Core 12589 12590**Return value** 12591 12592| Type | Description | 12593| ------ | ------------------------- | 12594| number | Total length of the file to be downloaded.| 12595 12596**Example** 12597 12598```ts 12599// xxx.ets 12600import { webview } from '@kit.ArkWeb'; 12601import { BusinessError } from '@kit.BasicServicesKit'; 12602 12603@Entry 12604@Component 12605struct WebComponent { 12606 controller: webview.WebviewController = new webview.WebviewController(); 12607 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12608 12609 build() { 12610 Column() { 12611 Button('setDownloadDelegate') 12612 .onClick(() => { 12613 try { 12614 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12615 console.log("will start a download."); 12616 // Pass in a download path and start the download. 12617 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12618 }) 12619 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12620 console.log("download update total bytes: " + webDownloadItem.getTotalBytes()); 12621 }) 12622 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12623 console.log("download failed guid: " + webDownloadItem.getGuid()); 12624 }) 12625 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12626 console.log("download finish guid: " + webDownloadItem.getGuid()); 12627 }) 12628 this.controller.setDownloadDelegate(this.delegate); 12629 } catch (error) { 12630 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12631 } 12632 }) 12633 Button('startDownload') 12634 .onClick(() => { 12635 try { 12636 this.controller.startDownload('https://www.example.com'); 12637 } catch (error) { 12638 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12639 } 12640 }) 12641 Web({ src: 'www.example.com', controller: this.controller }) 12642 } 12643 } 12644} 12645``` 12646 12647### getState<sup>11+</sup> 12648 12649getState(): WebDownloadState 12650 12651Obtains the download state. 12652 12653**System capability**: SystemCapability.Web.Webview.Core 12654 12655**Return value** 12656 12657| Type | Description | 12658| ------ | ------------------------- | 12659| [WebDownloadState](#webdownloadstate11) | Download state.| 12660 12661**Example** 12662 12663```ts 12664// xxx.ets 12665import { webview } from '@kit.ArkWeb'; 12666import { BusinessError } from '@kit.BasicServicesKit'; 12667 12668@Entry 12669@Component 12670struct WebComponent { 12671 controller: webview.WebviewController = new webview.WebviewController(); 12672 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12673 12674 build() { 12675 Column() { 12676 Button('setDownloadDelegate') 12677 .onClick(() => { 12678 try { 12679 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12680 console.log("will start a download."); 12681 // Pass in a download path and start the download. 12682 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12683 }) 12684 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12685 console.log("download update download state: " + webDownloadItem.getState()); 12686 }) 12687 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12688 console.log("download failed guid: " + webDownloadItem.getGuid()); 12689 }) 12690 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12691 console.log("download finish guid: " + webDownloadItem.getGuid()); 12692 }) 12693 this.controller.setDownloadDelegate(this.delegate); 12694 } catch (error) { 12695 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12696 } 12697 }) 12698 Button('startDownload') 12699 .onClick(() => { 12700 try { 12701 this.controller.startDownload('https://www.example.com'); 12702 } catch (error) { 12703 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12704 } 12705 }) 12706 Web({ src: 'www.example.com', controller: this.controller }) 12707 } 12708 } 12709} 12710``` 12711 12712### getLastErrorCode<sup>11+</sup> 12713 12714getLastErrorCode(): WebDownloadErrorCode 12715 12716Obtains the download error code. 12717 12718**System capability**: SystemCapability.Web.Webview.Core 12719 12720**Return value** 12721 12722| Type | Description | 12723| ------ | ------------------------- | 12724| [WebDownloadErrorCode](#webdownloaderrorcode11) | Error code returned when the download error occurs.| 12725 12726**Example** 12727 12728```ts 12729// xxx.ets 12730import { webview } from '@kit.ArkWeb'; 12731import { BusinessError } from '@kit.BasicServicesKit'; 12732 12733@Entry 12734@Component 12735struct WebComponent { 12736 controller: webview.WebviewController = new webview.WebviewController(); 12737 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12738 12739 build() { 12740 Column() { 12741 Button('setDownloadDelegate') 12742 .onClick(() => { 12743 try { 12744 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12745 console.log("will start a download."); 12746 // Pass in a download path and start the download. 12747 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12748 }) 12749 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12750 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12751 }) 12752 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12753 console.log("download failed guid: " + webDownloadItem.getGuid()); 12754 console.log("download error code: " + webDownloadItem.getLastErrorCode()); 12755 }) 12756 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12757 console.log("download finish guid: " + webDownloadItem.getGuid()); 12758 }) 12759 this.controller.setDownloadDelegate(this.delegate); 12760 } catch (error) { 12761 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12762 } 12763 }) 12764 Button('startDownload') 12765 .onClick(() => { 12766 try { 12767 this.controller.startDownload('https://www.example.com'); 12768 } catch (error) { 12769 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12770 } 12771 }) 12772 Web({ src: 'www.example.com', controller: this.controller }) 12773 } 12774 } 12775} 12776``` 12777 12778### getMethod<sup>11+</sup> 12779 12780getMethod(): string 12781 12782Obtains the request mode of this download task. 12783 12784**System capability**: SystemCapability.Web.Webview.Core 12785 12786**Return value** 12787 12788| Type | Description | 12789| ------ | ------------------------- | 12790| string | Request mode of the download task.| 12791 12792**Example** 12793 12794```ts 12795// xxx.ets 12796import { webview } from '@kit.ArkWeb'; 12797import { BusinessError } from '@kit.BasicServicesKit'; 12798 12799@Entry 12800@Component 12801struct WebComponent { 12802 controller: webview.WebviewController = new webview.WebviewController(); 12803 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12804 12805 build() { 12806 Column() { 12807 Button('setDownloadDelegate') 12808 .onClick(() => { 12809 try { 12810 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12811 console.log("Download will start. Method:" + webDownloadItem.getMethod()); 12812 // Pass in a download path and start the download. 12813 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12814 }) 12815 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12816 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12817 }) 12818 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12819 console.log("download failed guid: " + webDownloadItem.getGuid()); 12820 }) 12821 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12822 console.log("download finish guid: " + webDownloadItem.getGuid()); 12823 }) 12824 this.controller.setDownloadDelegate(this.delegate); 12825 } catch (error) { 12826 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12827 } 12828 }) 12829 Button('startDownload') 12830 .onClick(() => { 12831 try { 12832 this.controller.startDownload('https://www.example.com'); 12833 } catch (error) { 12834 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12835 } 12836 }) 12837 Web({ src: 'www.example.com', controller: this.controller }) 12838 } 12839 } 12840} 12841``` 12842 12843### getMimeType<sup>11+</sup> 12844 12845getMimeType(): string 12846 12847Obtains 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). 12848 12849**System capability**: SystemCapability.Web.Webview.Core 12850 12851**Return value** 12852 12853| Type | Description | 12854| ------ | ------------------------- | 12855| string | MIME type (for example, audio/ogg for a sound file, and image/png for an image file).| 12856 12857**Example** 12858 12859```ts 12860// xxx.ets 12861import { webview } from '@kit.ArkWeb'; 12862import { BusinessError } from '@kit.BasicServicesKit'; 12863 12864@Entry 12865@Component 12866struct WebComponent { 12867 controller: webview.WebviewController = new webview.WebviewController(); 12868 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12869 12870 build() { 12871 Column() { 12872 Button('setDownloadDelegate') 12873 .onClick(() => { 12874 try { 12875 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12876 console.log("Download will start. MIME type:" + webDownloadItem.getMimeType()); 12877 // Pass in a download path and start the download. 12878 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12879 }) 12880 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12881 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12882 }) 12883 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12884 console.log("download failed guid: " + webDownloadItem.getGuid()); 12885 }) 12886 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12887 console.log("download finish guid: " + webDownloadItem.getGuid()); 12888 }) 12889 this.controller.setDownloadDelegate(this.delegate); 12890 } catch (error) { 12891 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12892 } 12893 }) 12894 Button('startDownload') 12895 .onClick(() => { 12896 try { 12897 this.controller.startDownload('https://www.example.com'); 12898 } catch (error) { 12899 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12900 } 12901 }) 12902 Web({ src: 'www.example.com', controller: this.controller }) 12903 } 12904 } 12905} 12906``` 12907 12908### getUrl<sup>11+</sup> 12909 12910getUrl(): string 12911 12912Obtains the download request URL. 12913 12914**System capability**: SystemCapability.Web.Webview.Core 12915 12916**Return value** 12917 12918| Type | Description | 12919| ------ | ------------------------- | 12920| string | Download request URL.| 12921 12922**Example** 12923 12924```ts 12925// xxx.ets 12926import { webview } from '@kit.ArkWeb'; 12927import { BusinessError } from '@kit.BasicServicesKit'; 12928 12929@Entry 12930@Component 12931struct WebComponent { 12932 controller: webview.WebviewController = new webview.WebviewController(); 12933 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12934 12935 build() { 12936 Column() { 12937 Button('setDownloadDelegate') 12938 .onClick(() => { 12939 try { 12940 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 12941 console.log("will start a download, url:" + webDownloadItem.getUrl()); 12942 // Pass in a download path and start the download. 12943 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 12944 }) 12945 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 12946 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 12947 }) 12948 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 12949 console.log("download failed guid: " + webDownloadItem.getGuid()); 12950 }) 12951 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 12952 console.log("download finish guid: " + webDownloadItem.getGuid()); 12953 }) 12954 this.controller.setDownloadDelegate(this.delegate); 12955 } catch (error) { 12956 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12957 } 12958 }) 12959 Button('startDownload') 12960 .onClick(() => { 12961 try { 12962 this.controller.startDownload('https://www.example.com'); 12963 } catch (error) { 12964 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 12965 } 12966 }) 12967 Web({ src: 'www.example.com', controller: this.controller }) 12968 } 12969 } 12970} 12971``` 12972 12973### getSuggestedFileName<sup>11+</sup> 12974 12975getSuggestedFileName(): string 12976 12977Obtains the suggested file name for this download task. 12978 12979**System capability**: SystemCapability.Web.Webview.Core 12980 12981**Return value** 12982 12983| Type | Description | 12984| ------ | ------------------------- | 12985| string | Suggested file name.| 12986 12987**Example** 12988 12989```ts 12990// xxx.ets 12991import { webview } from '@kit.ArkWeb'; 12992import { BusinessError } from '@kit.BasicServicesKit'; 12993 12994@Entry 12995@Component 12996struct WebComponent { 12997 controller: webview.WebviewController = new webview.WebviewController(); 12998 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 12999 13000 build() { 13001 Column() { 13002 Button('setDownloadDelegate') 13003 .onClick(() => { 13004 try { 13005 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13006 console.log("will start a download, suggest name:" + webDownloadItem.getSuggestedFileName()); 13007 // Pass in a download path and start the download. 13008 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13009 }) 13010 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13011 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13012 }) 13013 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13014 console.log("download failed guid: " + webDownloadItem.getGuid()); 13015 }) 13016 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13017 console.log("download finish guid: " + webDownloadItem.getGuid()); 13018 }) 13019 this.controller.setDownloadDelegate(this.delegate); 13020 } catch (error) { 13021 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13022 } 13023 }) 13024 Button('startDownload') 13025 .onClick(() => { 13026 try { 13027 this.controller.startDownload('https://www.example.com'); 13028 } catch (error) { 13029 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13030 } 13031 }) 13032 Web({ src: 'www.example.com', controller: this.controller }) 13033 } 13034 } 13035} 13036``` 13037 13038### getReceivedBytes<sup>11+</sup> 13039 13040getReceivedBytes(): number 13041 13042Obtains the number of received bytes. 13043 13044**System capability**: SystemCapability.Web.Webview.Core 13045 13046**Return value** 13047 13048| Type | Description | 13049| ------ | ------------------------- | 13050| number | Number of received bytes.| 13051 13052**Example** 13053 13054```ts 13055// xxx.ets 13056import { webview } from '@kit.ArkWeb'; 13057import { BusinessError } from '@kit.BasicServicesKit'; 13058 13059@Entry 13060@Component 13061struct WebComponent { 13062 controller: webview.WebviewController = new webview.WebviewController(); 13063 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13064 13065 build() { 13066 Column() { 13067 Button('setDownloadDelegate') 13068 .onClick(() => { 13069 try { 13070 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13071 console.log("will start a download."); 13072 // Pass in a download path and start the download. 13073 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13074 }) 13075 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13076 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13077 console.log("download update received bytes: " + webDownloadItem.getReceivedBytes()); 13078 }) 13079 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13080 console.log("download failed guid: " + webDownloadItem.getGuid()); 13081 }) 13082 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13083 console.log("download finish guid: " + webDownloadItem.getGuid()); 13084 }) 13085 this.controller.setDownloadDelegate(this.delegate); 13086 } catch (error) { 13087 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13088 } 13089 }) 13090 Button('startDownload') 13091 .onClick(() => { 13092 try { 13093 this.controller.startDownload('https://www.example.com'); 13094 } catch (error) { 13095 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13096 } 13097 }) 13098 Web({ src: 'www.example.com', controller: this.controller }) 13099 } 13100 } 13101} 13102``` 13103 13104### getFullPath<sup>11+</sup> 13105 13106getFullPath(): string 13107 13108Obtains the full path of the downloaded file on the disk. 13109 13110**System capability**: SystemCapability.Web.Webview.Core 13111 13112**Return value** 13113 13114| Type | Description | 13115| ------ | ------------------------- | 13116| string | Full path of the downloaded file on the disk.| 13117 13118**Example** 13119 13120```ts 13121// xxx.ets 13122import { webview } from '@kit.ArkWeb'; 13123import { BusinessError } from '@kit.BasicServicesKit'; 13124 13125@Entry 13126@Component 13127struct WebComponent { 13128 controller: webview.WebviewController = new webview.WebviewController(); 13129 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13130 13131 build() { 13132 Column() { 13133 Button('setDownloadDelegate') 13134 .onClick(() => { 13135 try { 13136 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13137 console.log("will start a download."); 13138 // Pass in a download path and start the download. 13139 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13140 }) 13141 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13142 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13143 }) 13144 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13145 console.log("download failed guid: " + webDownloadItem.getGuid()); 13146 }) 13147 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13148 console.log("download finish guid: " + webDownloadItem.getGuid()); 13149 console.log("download finish full path: " + webDownloadItem.getFullPath()); 13150 }) 13151 this.controller.setDownloadDelegate(this.delegate); 13152 } catch (error) { 13153 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13154 } 13155 }) 13156 Button('startDownload') 13157 .onClick(() => { 13158 try { 13159 this.controller.startDownload('https://www.example.com'); 13160 } catch (error) { 13161 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13162 } 13163 }) 13164 Web({ src: 'www.example.com', controller: this.controller }) 13165 } 13166 } 13167} 13168``` 13169 13170### serialize<sup>11+</sup> 13171 13172serialize(): Uint8Array 13173 13174Serializes the failed download to a byte array. 13175 13176**System capability**: SystemCapability.Web.Webview.Core 13177 13178**Return value** 13179 13180| Type | Description | 13181| ------ | ------------------------- | 13182| Uint8Array | Byte array into which the failed download is serialized.| 13183 13184**Example** 13185 13186```ts 13187// xxx.ets 13188import { webview } from '@kit.ArkWeb'; 13189import { BusinessError } from '@kit.BasicServicesKit'; 13190 13191@Entry 13192@Component 13193struct WebComponent { 13194 controller: webview.WebviewController = new webview.WebviewController(); 13195 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13196 failedData: Uint8Array = new Uint8Array(); 13197 13198 build() { 13199 Column() { 13200 Button('setDownloadDelegate') 13201 .onClick(() => { 13202 try { 13203 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13204 console.log("will start a download."); 13205 // Pass in a download path and start the download. 13206 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13207 }) 13208 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13209 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13210 }) 13211 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13212 console.log("download failed guid: " + webDownloadItem.getGuid()); 13213 // Serialize the failed download to a byte array. 13214 this.failedData = webDownloadItem.serialize(); 13215 }) 13216 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13217 console.log("download finish guid: " + webDownloadItem.getGuid()); 13218 }) 13219 this.controller.setDownloadDelegate(this.delegate); 13220 } catch (error) { 13221 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13222 } 13223 }) 13224 Button('startDownload') 13225 .onClick(() => { 13226 try { 13227 this.controller.startDownload('https://www.example.com'); 13228 } catch (error) { 13229 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13230 } 13231 }) 13232 Web({ src: 'www.example.com', controller: this.controller }) 13233 } 13234 } 13235} 13236``` 13237 13238### deserialize<sup>11+</sup> 13239 13240static deserialize(serializedData: Uint8Array): WebDownloadItem 13241 13242Deserializes the serialized byte array into a **WebDownloadItem** object. 13243 13244**System capability**: SystemCapability.Web.Webview.Core 13245 13246**Parameters** 13247 13248| Name | Type | Mandatory | Description| 13249| ------------------ | ------- | ---- | ------------- | 13250| serializedData | Uint8Array | Yes | Byte array into which the download is serialized.| 13251 13252**Return value** 13253 13254| Type | Description | 13255| ------ | ------------------------- | 13256| [WebDownloadItem](#webdownloaditem11) | **WebDownloadItem** object.| 13257 13258**Error codes** 13259 13260For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 13261 13262| ID| Error Message | 13263| -------- | ------------------------------------------------------------ | 13264| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. 2. Parameter verification failed. | 13265 13266**Example** 13267 13268```ts 13269// xxx.ets 13270import { webview } from '@kit.ArkWeb'; 13271import { BusinessError } from '@kit.BasicServicesKit'; 13272 13273@Entry 13274@Component 13275struct WebComponent { 13276 controller: webview.WebviewController = new webview.WebviewController(); 13277 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13278 failedData: Uint8Array = new Uint8Array(); 13279 13280 build() { 13281 Column() { 13282 Button('setDownloadDelegate') 13283 .onClick(() => { 13284 try { 13285 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13286 console.log("will start a download."); 13287 // Pass in a download path and start the download. 13288 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13289 }) 13290 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13291 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13292 }) 13293 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13294 console.log("download failed guid: " + webDownloadItem.getGuid()); 13295 // Serialize the failed download to a byte array. 13296 this.failedData = webDownloadItem.serialize(); 13297 }) 13298 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13299 console.log("download finish guid: " + webDownloadItem.getGuid()); 13300 }) 13301 this.controller.setDownloadDelegate(this.delegate); 13302 } catch (error) { 13303 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13304 } 13305 }) 13306 Button('startDownload') 13307 .onClick(() => { 13308 try { 13309 this.controller.startDownload('https://www.example.com'); 13310 } catch (error) { 13311 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13312 } 13313 }) 13314 Button('resumeDownload') 13315 .onClick(() => { 13316 try { 13317 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13318 } catch (error) { 13319 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13320 } 13321 }) 13322 Web({ src: 'www.example.com', controller: this.controller }) 13323 } 13324 } 13325} 13326``` 13327 13328### start<sup>11+</sup> 13329 13330start(downloadPath: string): void 13331 13332Starts a download to a specified directory. 13333 13334> **NOTE** 13335> 13336>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. 13337 13338**System capability**: SystemCapability.Web.Webview.Core 13339 13340**Parameters** 13341 13342| Name| Type | Mandatory| Description | 13343| ------ | ---------------------- | ---- | ------------------------------| 13344| downloadPath | string | Yes | Path (including the file name) of the file to download.| 13345 13346**Error codes** 13347 13348For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 13349 13350| ID| Error Message | 13351| -------- | ------------------------------------------------------------ | 13352| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. 2. Parameter verification failed. | 13353 13354**Example** 13355 13356```ts 13357// xxx.ets 13358import { webview } from '@kit.ArkWeb'; 13359import { BusinessError } from '@kit.BasicServicesKit'; 13360 13361@Entry 13362@Component 13363struct WebComponent { 13364 controller: webview.WebviewController = new webview.WebviewController(); 13365 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13366 failedData: Uint8Array = new Uint8Array(); 13367 13368 build() { 13369 Column() { 13370 Button('setDownloadDelegate') 13371 .onClick(() => { 13372 try { 13373 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13374 console.log("will start a download."); 13375 // Pass in a download path and start the download. 13376 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13377 }) 13378 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13379 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13380 }) 13381 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13382 console.log("download failed guid: " + webDownloadItem.getGuid()); 13383 // Serialize the failed download to a byte array. 13384 this.failedData = webDownloadItem.serialize(); 13385 }) 13386 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13387 console.log("download finish guid: " + webDownloadItem.getGuid()); 13388 }) 13389 this.controller.setDownloadDelegate(this.delegate); 13390 } catch (error) { 13391 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13392 } 13393 }) 13394 Button('startDownload') 13395 .onClick(() => { 13396 try { 13397 this.controller.startDownload('https://www.example.com'); 13398 } catch (error) { 13399 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13400 } 13401 }) 13402 Button('resumeDownload') 13403 .onClick(() => { 13404 try { 13405 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13406 } catch (error) { 13407 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13408 } 13409 }) 13410 Web({ src: 'www.example.com', controller: this.controller }) 13411 } 13412 } 13413} 13414``` 13415 13416### cancel<sup>11+</sup> 13417 13418cancel(): void 13419 13420Cancels a download task. 13421 13422**System capability**: SystemCapability.Web.Webview.Core 13423 13424**Example** 13425 13426```ts 13427// xxx.ets 13428import { webview } from '@kit.ArkWeb'; 13429import { BusinessError } from '@kit.BasicServicesKit'; 13430 13431@Entry 13432@Component 13433struct WebComponent { 13434 controller: webview.WebviewController = new webview.WebviewController(); 13435 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13436 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13437 failedData: Uint8Array = new Uint8Array(); 13438 13439 build() { 13440 Column() { 13441 Button('setDownloadDelegate') 13442 .onClick(() => { 13443 try { 13444 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13445 console.log("will start a download."); 13446 // Pass in a download path and start the download. 13447 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13448 }) 13449 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13450 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13451 this.download = webDownloadItem; 13452 }) 13453 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13454 console.log("download failed guid: " + webDownloadItem.getGuid()); 13455 // Serialize the failed download to a byte array. 13456 this.failedData = webDownloadItem.serialize(); 13457 }) 13458 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13459 console.log("download finish guid: " + webDownloadItem.getGuid()); 13460 }) 13461 this.controller.setDownloadDelegate(this.delegate); 13462 } catch (error) { 13463 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13464 } 13465 }) 13466 Button('startDownload') 13467 .onClick(() => { 13468 try { 13469 this.controller.startDownload('https://www.example.com'); 13470 } catch (error) { 13471 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13472 } 13473 }) 13474 Button('resumeDownload') 13475 .onClick(() => { 13476 try { 13477 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13478 } catch (error) { 13479 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13480 } 13481 }) 13482 Button('cancel') 13483 .onClick(() => { 13484 try { 13485 this.download.cancel(); 13486 } catch (error) { 13487 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13488 } 13489 }) 13490 Web({ src: 'www.example.com', controller: this.controller }) 13491 } 13492 } 13493} 13494``` 13495 13496### pause<sup>11+</sup> 13497 13498pause(): void 13499 13500Pauses a download task. 13501 13502**System capability**: SystemCapability.Web.Webview.Core 13503 13504**Error codes** 13505 13506For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 13507 13508| ID | Error Message | 13509| -------- | ------------------------------------------------------------ | 13510| 17100019 | The download task is not started yet. | 13511 13512**Example** 13513 13514```ts 13515// xxx.ets 13516import { webview } from '@kit.ArkWeb'; 13517import { BusinessError } from '@kit.BasicServicesKit'; 13518 13519@Entry 13520@Component 13521struct WebComponent { 13522 controller: webview.WebviewController = new webview.WebviewController(); 13523 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13524 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13525 failedData: Uint8Array = new Uint8Array(); 13526 13527 build() { 13528 Column() { 13529 Button('setDownloadDelegate') 13530 .onClick(() => { 13531 try { 13532 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13533 console.log("will start a download."); 13534 // Pass in a download path and start the download. 13535 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13536 }) 13537 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13538 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13539 this.download = webDownloadItem; 13540 }) 13541 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13542 console.log("download failed guid: " + webDownloadItem.getGuid()); 13543 // Serialize the failed download to a byte array. 13544 this.failedData = webDownloadItem.serialize(); 13545 }) 13546 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13547 console.log("download finish guid: " + webDownloadItem.getGuid()); 13548 }) 13549 this.controller.setDownloadDelegate(this.delegate); 13550 } catch (error) { 13551 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13552 } 13553 }) 13554 Button('startDownload') 13555 .onClick(() => { 13556 try { 13557 this.controller.startDownload('https://www.example.com'); 13558 } catch (error) { 13559 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13560 } 13561 }) 13562 Button('resumeDownload') 13563 .onClick(() => { 13564 try { 13565 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13566 } catch (error) { 13567 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13568 } 13569 }) 13570 Button('cancel') 13571 .onClick(() => { 13572 try { 13573 this.download.cancel(); 13574 } catch (error) { 13575 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13576 } 13577 }) 13578 Button('pause') 13579 .onClick(() => { 13580 try { 13581 this.download.pause(); 13582 } catch (error) { 13583 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13584 } 13585 }) 13586 Web({ src: 'www.example.com', controller: this.controller }) 13587 } 13588 } 13589} 13590``` 13591 13592### resume<sup>11+</sup> 13593 13594resume(): void 13595 13596Resumes a download task. 13597 13598**System capability**: SystemCapability.Web.Webview.Core 13599 13600**Error codes** 13601 13602For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 13603 13604| ID | Error Message | 13605| -------- | ------------------------------------------------------------ | 13606| 17100016 | The download task is not paused. | 13607 13608**Example** 13609 13610```ts 13611// xxx.ets 13612import { webview } from '@kit.ArkWeb'; 13613import { BusinessError } from '@kit.BasicServicesKit'; 13614 13615@Entry 13616@Component 13617struct WebComponent { 13618 controller: webview.WebviewController = new webview.WebviewController(); 13619 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13620 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13621 failedData: Uint8Array = new Uint8Array(); 13622 13623 build() { 13624 Column() { 13625 Button('setDownloadDelegate') 13626 .onClick(() => { 13627 try { 13628 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13629 console.log("will start a download."); 13630 // Pass in a download path and start the download. 13631 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13632 }) 13633 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13634 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13635 this.download = webDownloadItem; 13636 }) 13637 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13638 console.log("download failed guid: " + webDownloadItem.getGuid()); 13639 // Serialize the failed download to a byte array. 13640 this.failedData = webDownloadItem.serialize(); 13641 }) 13642 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13643 console.log("download finish guid: " + webDownloadItem.getGuid()); 13644 }) 13645 this.controller.setDownloadDelegate(this.delegate); 13646 } catch (error) { 13647 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13648 } 13649 }) 13650 Button('startDownload') 13651 .onClick(() => { 13652 try { 13653 this.controller.startDownload('https://www.example.com'); 13654 } catch (error) { 13655 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13656 } 13657 }) 13658 Button('resumeDownload') 13659 .onClick(() => { 13660 try { 13661 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13662 } catch (error) { 13663 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13664 } 13665 }) 13666 Button('cancel') 13667 .onClick(() => { 13668 try { 13669 this.download.cancel(); 13670 } catch (error) { 13671 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13672 } 13673 }) 13674 Button('pause') 13675 .onClick(() => { 13676 try { 13677 this.download.pause(); 13678 } catch (error) { 13679 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13680 } 13681 }) 13682 Button('resume') 13683 .onClick(() => { 13684 try { 13685 this.download.resume(); 13686 } catch (error) { 13687 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13688 } 13689 }) 13690 Web({ src: 'www.example.com', controller: this.controller }) 13691 } 13692 } 13693} 13694``` 13695 13696## WebDownloadDelegate<sup>11+</sup> 13697 13698 Implements a **WebDownloadDelegate** class. You can use the callbacks of this class to notify users of the download state. 13699 13700### onBeforeDownload<sup>11+</sup> 13701 13702onBeforeDownload(callback: Callback\<WebDownloadItem>): void 13703 13704Invoked 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. 13705 13706> **NOTE** 13707> 13708>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. 13709 13710**System capability**: SystemCapability.Web.Webview.Core 13711 13712**Parameters** 13713 13714| Name | Type | Mandatory| Description | 13715| ------- | ------ | ---- | :------------- | 13716| callback | Callback\<[WebDownloadItem](#webdownloaditem11)> | Yes | Callback for triggering a download.| 13717 13718**Example** 13719 13720```ts 13721// xxx.ets 13722import { webview } from '@kit.ArkWeb'; 13723import { BusinessError } from '@kit.BasicServicesKit'; 13724 13725@Entry 13726@Component 13727struct WebComponent { 13728 controller: webview.WebviewController = new webview.WebviewController(); 13729 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13730 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13731 failedData: Uint8Array = new Uint8Array(); 13732 13733 build() { 13734 Column() { 13735 Button('setDownloadDelegate') 13736 .onClick(() => { 13737 try { 13738 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13739 console.log("will start a download."); 13740 // Pass in a download path and start the download. 13741 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13742 }) 13743 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13744 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13745 this.download = webDownloadItem; 13746 }) 13747 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13748 console.log("download failed guid: " + webDownloadItem.getGuid()); 13749 // Serialize the failed download to a byte array. 13750 this.failedData = webDownloadItem.serialize(); 13751 }) 13752 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13753 console.log("download finish guid: " + webDownloadItem.getGuid()); 13754 }) 13755 this.controller.setDownloadDelegate(this.delegate); 13756 } catch (error) { 13757 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13758 } 13759 }) 13760 Button('startDownload') 13761 .onClick(() => { 13762 try { 13763 this.controller.startDownload('https://www.example.com'); 13764 } catch (error) { 13765 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13766 } 13767 }) 13768 Button('resumeDownload') 13769 .onClick(() => { 13770 try { 13771 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13772 } catch (error) { 13773 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13774 } 13775 }) 13776 Button('cancel') 13777 .onClick(() => { 13778 try { 13779 this.download.cancel(); 13780 } catch (error) { 13781 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13782 } 13783 }) 13784 Button('pause') 13785 .onClick(() => { 13786 try { 13787 this.download.pause(); 13788 } catch (error) { 13789 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13790 } 13791 }) 13792 Button('resume') 13793 .onClick(() => { 13794 try { 13795 this.download.resume(); 13796 } catch (error) { 13797 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13798 } 13799 }) 13800 Web({ src: 'www.example.com', controller: this.controller }) 13801 } 13802 } 13803} 13804``` 13805 13806### onDownloadUpdated<sup>11+</sup> 13807 13808onDownloadUpdated(callback: Callback\<WebDownloadItem>): void 13809 13810Invoked when the download progress is updated. 13811 13812**System capability**: SystemCapability.Web.Webview.Core 13813 13814**Parameters** 13815 13816| Name | Type | Mandatory| Description | 13817| ------- | ------ | ---- | :------------- | 13818| callback | Callback\<[WebDownloadItem](#webdownloaditem11)> | Yes | Callback invoked when the downloaded progress is updated.| 13819 13820**Example** 13821 13822```ts 13823// xxx.ets 13824import { webview } from '@kit.ArkWeb'; 13825import { BusinessError } from '@kit.BasicServicesKit'; 13826 13827@Entry 13828@Component 13829struct WebComponent { 13830 controller: webview.WebviewController = new webview.WebviewController(); 13831 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13832 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13833 failedData: Uint8Array = new Uint8Array(); 13834 13835 build() { 13836 Column() { 13837 Button('setDownloadDelegate') 13838 .onClick(() => { 13839 try { 13840 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13841 console.log("will start a download."); 13842 // Pass in a download path and start the download. 13843 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13844 }) 13845 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13846 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13847 this.download = webDownloadItem; 13848 }) 13849 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13850 console.log("download failed guid: " + webDownloadItem.getGuid()); 13851 // Serialize the failed download to a byte array. 13852 this.failedData = webDownloadItem.serialize(); 13853 }) 13854 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13855 console.log("download finish guid: " + webDownloadItem.getGuid()); 13856 }) 13857 this.controller.setDownloadDelegate(this.delegate); 13858 } catch (error) { 13859 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13860 } 13861 }) 13862 Button('startDownload') 13863 .onClick(() => { 13864 try { 13865 this.controller.startDownload('https://www.example.com'); 13866 } catch (error) { 13867 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13868 } 13869 }) 13870 Button('resumeDownload') 13871 .onClick(() => { 13872 try { 13873 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13874 } catch (error) { 13875 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13876 } 13877 }) 13878 Button('cancel') 13879 .onClick(() => { 13880 try { 13881 this.download.cancel(); 13882 } catch (error) { 13883 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13884 } 13885 }) 13886 Button('pause') 13887 .onClick(() => { 13888 try { 13889 this.download.pause(); 13890 } catch (error) { 13891 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13892 } 13893 }) 13894 Button('resume') 13895 .onClick(() => { 13896 try { 13897 this.download.resume(); 13898 } catch (error) { 13899 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13900 } 13901 }) 13902 Web({ src: 'www.example.com', controller: this.controller }) 13903 } 13904 } 13905} 13906``` 13907 13908### onDownloadFinish<sup>11+</sup> 13909 13910onDownloadFinish(callback: Callback\<WebDownloadItem>): void 13911 13912Invoked when the download is complete. 13913 13914**System capability**: SystemCapability.Web.Webview.Core 13915 13916**Parameters** 13917 13918| Name | Type | Mandatory| Description | 13919| ------- | ------ | ---- | :------------- | 13920| callback | Callback\<[WebDownloadItem](#webdownloaditem11)> | Yes | Callback invoked when the download is complete.| 13921 13922**Example** 13923 13924```ts 13925// xxx.ets 13926import { webview } from '@kit.ArkWeb'; 13927import { BusinessError } from '@kit.BasicServicesKit'; 13928 13929@Entry 13930@Component 13931struct WebComponent { 13932 controller: webview.WebviewController = new webview.WebviewController(); 13933 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 13934 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 13935 failedData: Uint8Array = new Uint8Array(); 13936 13937 build() { 13938 Column() { 13939 Button('setDownloadDelegate') 13940 .onClick(() => { 13941 try { 13942 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 13943 console.log("will start a download."); 13944 // Pass in a download path and start the download. 13945 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 13946 }) 13947 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 13948 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 13949 this.download = webDownloadItem; 13950 }) 13951 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 13952 console.log("download failed guid: " + webDownloadItem.getGuid()); 13953 // Serialize the failed download to a byte array. 13954 this.failedData = webDownloadItem.serialize(); 13955 }) 13956 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 13957 console.log("download finish guid: " + webDownloadItem.getGuid()); 13958 }) 13959 this.controller.setDownloadDelegate(this.delegate); 13960 } catch (error) { 13961 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13962 } 13963 }) 13964 Button('startDownload') 13965 .onClick(() => { 13966 try { 13967 this.controller.startDownload('https://www.example.com'); 13968 } catch (error) { 13969 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13970 } 13971 }) 13972 Button('resumeDownload') 13973 .onClick(() => { 13974 try { 13975 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 13976 } catch (error) { 13977 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13978 } 13979 }) 13980 Button('cancel') 13981 .onClick(() => { 13982 try { 13983 this.download.cancel(); 13984 } catch (error) { 13985 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13986 } 13987 }) 13988 Button('pause') 13989 .onClick(() => { 13990 try { 13991 this.download.pause(); 13992 } catch (error) { 13993 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 13994 } 13995 }) 13996 Button('resume') 13997 .onClick(() => { 13998 try { 13999 this.download.resume(); 14000 } catch (error) { 14001 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14002 } 14003 }) 14004 Web({ src: 'www.example.com', controller: this.controller }) 14005 } 14006 } 14007} 14008``` 14009 14010### onDownloadFailed<sup>11+</sup> 14011 14012onDownloadFailed(callback: Callback\<WebDownloadItem>): void 14013 14014Invoked when the download fails. 14015 14016**System capability**: SystemCapability.Web.Webview.Core 14017 14018**Parameters** 14019 14020| Name | Type | Mandatory| Description | 14021| ------- | ------ | ---- | :------------- | 14022| callback | Callback\<[WebDownloadItem](#webdownloaditem11)> | Yes | Callback invoked when the download fails.| 14023 14024**Example** 14025 14026```ts 14027// xxx.ets 14028import { webview } from '@kit.ArkWeb'; 14029import { BusinessError } from '@kit.BasicServicesKit'; 14030 14031@Entry 14032@Component 14033struct WebComponent { 14034 controller: webview.WebviewController = new webview.WebviewController(); 14035 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 14036 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 14037 failedData: Uint8Array = new Uint8Array(); 14038 14039 build() { 14040 Column() { 14041 Button('setDownloadDelegate') 14042 .onClick(() => { 14043 try { 14044 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 14045 console.log("will start a download."); 14046 // Pass in a download path and start the download. 14047 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 14048 }) 14049 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 14050 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 14051 this.download = webDownloadItem; 14052 }) 14053 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 14054 console.log("download failed guid: " + webDownloadItem.getGuid()); 14055 // Serialize the failed download to a byte array. 14056 this.failedData = webDownloadItem.serialize(); 14057 }) 14058 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 14059 console.log("download finish guid: " + webDownloadItem.getGuid()); 14060 }) 14061 this.controller.setDownloadDelegate(this.delegate); 14062 } catch (error) { 14063 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14064 } 14065 }) 14066 Button('startDownload') 14067 .onClick(() => { 14068 try { 14069 this.controller.startDownload('https://www.example.com'); 14070 } catch (error) { 14071 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14072 } 14073 }) 14074 Button('resumeDownload') 14075 .onClick(() => { 14076 try { 14077 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 14078 } catch (error) { 14079 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14080 } 14081 }) 14082 Button('cancel') 14083 .onClick(() => { 14084 try { 14085 this.download.cancel(); 14086 } catch (error) { 14087 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14088 } 14089 }) 14090 Button('pause') 14091 .onClick(() => { 14092 try { 14093 this.download.pause(); 14094 } catch (error) { 14095 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14096 } 14097 }) 14098 Button('resume') 14099 .onClick(() => { 14100 try { 14101 this.download.resume(); 14102 } catch (error) { 14103 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14104 } 14105 }) 14106 Web({ src: 'www.example.com', controller: this.controller }) 14107 } 14108 } 14109} 14110``` 14111 14112## WebDownloadManager<sup>11+</sup> 14113 14114Implements a **WebDownloadManager** class. You can use the APIs of this class to resume failed download tasks. 14115 14116### setDownloadDelegate<sup>11+</sup> 14117 14118static setDownloadDelegate(delegate: WebDownloadDelegate): void 14119 14120Sets the delegate used to receive download progress triggered from **WebDownloadManager**. 14121 14122**System capability**: SystemCapability.Web.Webview.Core 14123 14124**Parameters** 14125 14126| Name | Type | Mandatory | Description | 14127| ---------------| ------- | ---- | ------------- | 14128| delegate | [WebDownloadDelegate](#webdownloaddelegate11) | Yes | Delegate used to receive the download progress.| 14129 14130**Example** 14131 14132```ts 14133// xxx.ets 14134import { webview } from '@kit.ArkWeb'; 14135import { BusinessError } from '@kit.BasicServicesKit'; 14136 14137@Entry 14138@Component 14139struct WebComponent { 14140 controller: webview.WebviewController = new webview.WebviewController(); 14141 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 14142 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 14143 failedData: Uint8Array = new Uint8Array(); 14144 14145 build() { 14146 Column() { 14147 Button('setDownloadDelegate') 14148 .onClick(() => { 14149 try { 14150 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 14151 console.log("will start a download."); 14152 // Pass in a download path and start the download. 14153 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 14154 }) 14155 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 14156 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 14157 this.download = webDownloadItem; 14158 }) 14159 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 14160 console.log("download failed guid: " + webDownloadItem.getGuid()); 14161 // Serialize the failed download to a byte array. 14162 this.failedData = webDownloadItem.serialize(); 14163 }) 14164 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 14165 console.log("download finish guid: " + webDownloadItem.getGuid()); 14166 }) 14167 this.controller.setDownloadDelegate(this.delegate); 14168 webview.WebDownloadManager.setDownloadDelegate(this.delegate); 14169 } catch (error) { 14170 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14171 } 14172 }) 14173 Button('startDownload') 14174 .onClick(() => { 14175 try { 14176 this.controller.startDownload('https://www.example.com'); 14177 } catch (error) { 14178 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14179 } 14180 }) 14181 Button('resumeDownload') 14182 .onClick(() => { 14183 try { 14184 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 14185 } catch (error) { 14186 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14187 } 14188 }) 14189 Button('cancel') 14190 .onClick(() => { 14191 try { 14192 this.download.cancel(); 14193 } catch (error) { 14194 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14195 } 14196 }) 14197 Button('pause') 14198 .onClick(() => { 14199 try { 14200 this.download.pause(); 14201 } catch (error) { 14202 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14203 } 14204 }) 14205 Button('resume') 14206 .onClick(() => { 14207 try { 14208 this.download.resume(); 14209 } catch (error) { 14210 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14211 } 14212 }) 14213 Web({ src: 'www.example.com', controller: this.controller }) 14214 } 14215 } 14216} 14217``` 14218 14219### resumeDownload<sup>11+</sup> 14220 14221static resumeDownload(webDownloadItem: WebDownloadItem): void 14222 14223Resumes a failed download task. 14224 14225**System capability**: SystemCapability.Web.Webview.Core 14226 14227**Parameters** 14228 14229| Name | Type | Mandatory | Description | 14230| ---------------| ------- | ---- | ------------- | 14231| webDownloadItem | [WebDownloadItem](#webdownloaditem11) | Yes | Download task to resume.| 14232 14233**Error codes** 14234 14235For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14236 14237| ID| Error Message | 14238| -------- | ------------------------------------- | 14239| 17100018 | No WebDownloadDelegate has been set yet. | 14240 14241**Example** 14242 14243```ts 14244// xxx.ets 14245import { webview } from '@kit.ArkWeb'; 14246import { BusinessError } from '@kit.BasicServicesKit'; 14247 14248@Entry 14249@Component 14250struct WebComponent { 14251 controller: webview.WebviewController = new webview.WebviewController(); 14252 delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); 14253 download: webview.WebDownloadItem = new webview.WebDownloadItem(); 14254 failedData: Uint8Array = new Uint8Array(); 14255 14256 build() { 14257 Column() { 14258 Button('setDownloadDelegate') 14259 .onClick(() => { 14260 try { 14261 this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { 14262 console.log("will start a download."); 14263 // Pass in a download path and start the download. 14264 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); 14265 }) 14266 this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { 14267 console.log("download update percent complete: " + webDownloadItem.getPercentComplete()); 14268 this.download = webDownloadItem; 14269 }) 14270 this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { 14271 console.log("download failed guid: " + webDownloadItem.getGuid()); 14272 // Serialize the failed download to a byte array. 14273 this.failedData = webDownloadItem.serialize(); 14274 }) 14275 this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { 14276 console.log("download finish guid: " + webDownloadItem.getGuid()); 14277 }) 14278 this.controller.setDownloadDelegate(this.delegate); 14279 webview.WebDownloadManager.setDownloadDelegate(this.delegate); 14280 } catch (error) { 14281 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14282 } 14283 }) 14284 Button('startDownload') 14285 .onClick(() => { 14286 try { 14287 this.controller.startDownload('https://www.example.com'); 14288 } catch (error) { 14289 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14290 } 14291 }) 14292 Button('resumeDownload') 14293 .onClick(() => { 14294 try { 14295 webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData)); 14296 } catch (error) { 14297 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14298 } 14299 }) 14300 Button('cancel') 14301 .onClick(() => { 14302 try { 14303 this.download.cancel(); 14304 } catch (error) { 14305 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14306 } 14307 }) 14308 Button('pause') 14309 .onClick(() => { 14310 try { 14311 this.download.pause(); 14312 } catch (error) { 14313 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14314 } 14315 }) 14316 Button('resume') 14317 .onClick(() => { 14318 try { 14319 this.download.resume(); 14320 } catch (error) { 14321 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14322 } 14323 }) 14324 Web({ src: 'www.example.com', controller: this.controller }) 14325 } 14326 } 14327} 14328``` 14329 14330## WebHttpBodyStream<sup>12+</sup> 14331 14332Represents 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. 14333 14334### initialize<sup>12+</sup> 14335 14336initialize(): Promise\<void\> 14337 14338Initializes this **WebHttpBodyStream** instance. 14339 14340**System capability**: SystemCapability.Web.Webview.Core 14341 14342**Return value** 14343 14344| Type | Description | 14345| ------ | ------------------------- | 14346| Promise\<void\> | Promise used to return the result.| 14347 14348**Error codes** 14349 14350For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14351 14352| ID| Error Message | 14353| -------- | ------------------------------------- | 14354| 17100022 | Failed to initialize the HTTP body stream. | 14355 14356**Example** 14357 14358```ts 14359// xxx.ets 14360import { webview } from '@kit.ArkWeb'; 14361import { BusinessError } from '@kit.BasicServicesKit'; 14362import { buffer } from '@kit.ArkTS'; 14363import { WebNetErrorList } from '@ohos.web.netErrorList' 14364 14365@Entry 14366@Component 14367struct WebComponent { 14368 controller: webview.WebviewController = new webview.WebviewController(); 14369 schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); 14370 htmlData: string = "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>"; 14371 14372 build() { 14373 Column() { 14374 Button('postUrl') 14375 .onClick(() => { 14376 try { 14377 let postData = buffer.from(this.htmlData); 14378 this.controller.postUrl('https://www.example.com', postData.buffer); 14379 } catch (error) { 14380 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14381 } 14382 }) 14383 Web({ src: 'https://www.example.com', controller: this.controller }) 14384 .onControllerAttached(() => { 14385 try { 14386 this.schemeHandler.onRequestStart((request: webview.WebSchemeHandlerRequest, resourceHandler: webview.WebResourceHandler) => { 14387 console.log("[schemeHandler] onRequestStart"); 14388 try { 14389 let stream = request.getHttpBodyStream(); 14390 if (stream) { 14391 stream.initialize().then(() => { 14392 if (!stream) { 14393 return; 14394 } 14395 console.log("[schemeHandler] onRequestStart postDataStream size:" + stream.getSize()); 14396 console.log("[schemeHandler] onRequestStart postDataStream position:" + stream.getPosition()); 14397 console.log("[schemeHandler] onRequestStart postDataStream isChunked:" + stream.isChunked()); 14398 console.log("[schemeHandler] onRequestStart postDataStream isEof:" + stream.isEof()); 14399 console.log("[schemeHandler] onRequestStart postDataStream isInMemory:" + stream.isInMemory()); 14400 stream.read(stream.getSize()).then((buffer) => { 14401 if (!stream) { 14402 return; 14403 } 14404 console.log("[schemeHandler] onRequestStart postDataStream readlength:" + buffer.byteLength); 14405 console.log("[schemeHandler] onRequestStart postDataStream isEof:" + stream.isEof()); 14406 console.log("[schemeHandler] onRequestStart postDataStream position:" + stream.getPosition()); 14407 }).catch((error: BusinessError) => { 14408 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 14409 }) 14410 }).catch((error: BusinessError) => { 14411 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 14412 }) 14413 } else { 14414 console.log("[schemeHandler] onRequestStart has no http body stream"); 14415 } 14416 } catch (error) { 14417 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14418 } 14419 14420 return false; 14421 }) 14422 14423 this.schemeHandler.onRequestStop((request: webview.WebSchemeHandlerRequest) => { 14424 console.log("[schemeHandler] onRequestStop"); 14425 }); 14426 14427 this.controller.setWebSchemeHandler('https', this.schemeHandler); 14428 } catch (error) { 14429 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14430 } 14431 }) 14432 .javaScriptAccess(true) 14433 .domStorageAccess(true) 14434 } 14435 } 14436} 14437 14438``` 14439 14440### read<sup>12+</sup> 14441 14442read(size: number): Promise\<ArrayBuffer\> 14443 14444Reads data from this **WebHttpBodyStream** instance. 14445 14446**System capability**: SystemCapability.Web.Webview.Core 14447 14448**Parameters** 14449 14450| Name | Type | Mandatory | Description | 14451| --------| ------- | ---- | ---------------------------| 14452| size | number | Yes | Number of bytes obtained from the **WebHttpBodyStream** instance.| 14453 14454**Return value** 14455 14456| Type | Description | 14457| ------ | ------------------------- | 14458| Promise\<ArrayBuffer\> | Promise used to return the result.| 14459 14460**Error codes** 14461 14462For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14463 14464| ID| Error Message | 14465| -------- | ------------------------------------- | 14466| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 14467 14468**Example** 14469 14470For the complete sample code, see [initialize](#initialize12)). 14471 14472### getSize<sup>12+</sup> 14473 14474getSize(): number 14475 14476Obtains the size of data in this **WebHttpBodyStream** instance. This API always returns zero when chunked transfer is used. 14477 14478**System capability**: SystemCapability.Web.Webview.Core 14479 14480**Return value** 14481 14482| Type | Description | 14483| ------ | ------------------------- | 14484| number | Size of data in the current **WebHttpBodyStream** instance.| 14485 14486**Example** 14487 14488For the complete sample code, see [initialize](#initialize12)). 14489 14490### getPosition<sup>12+</sup> 14491 14492getPosition(): number 14493 14494Reads the current read position in this **WebHttpBodyStream** instance. 14495 14496**System capability**: SystemCapability.Web.Webview.Core 14497 14498**Return value** 14499 14500| Type | Description | 14501| ------ | ------------------------- | 14502| number | Current read position in the **WebHttpBodyStream** instance.| 14503 14504**Example** 14505 14506For the complete sample code, see [initialize](#initialize12)). 14507 14508### isChunked<sup>12+</sup> 14509 14510isChunked(): boolean 14511 14512Checks whether this **WebHttpBodyStream** instance is transmitted by chunk. 14513 14514**System capability**: SystemCapability.Web.Webview.Core 14515 14516**Return value** 14517 14518| Type | Description | 14519| ------ | ------------------------- | 14520| boolean | Whether the **WebHttpBodyStream** instance is transmitted by chunk.| 14521 14522**Example** 14523 14524For the complete sample code, see [initialize](#initialize12)). 14525 14526### isEof<sup>12+</sup> 14527 14528isEof(): boolean 14529 14530Checks 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. 14531 14532**System capability**: SystemCapability.Web.Webview.Core 14533 14534**Return value** 14535 14536| Type | Description | 14537| ------ | ------------------------- | 14538| boolean | Whether all data in the **WebHttpBodyStream** instance has been read.| 14539 14540**Example** 14541 14542For the complete sample code, see [initialize](#initialize12)). 14543 14544### isInMemory<sup>12+</sup> 14545 14546isInMemory(): boolean 14547 14548Checks 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. 14549 14550**System capability**: SystemCapability.Web.Webview.Core 14551 14552**Return value** 14553 14554| Type | Description | 14555| ------ | ------------------------- | 14556| boolean | Whether the uploaded data in the **WebHttpBodyStream** instance is stored in memory.| 14557 14558**Example** 14559 14560For the complete sample code, see [initialize](#initialize12)). 14561 14562## WebSchemeHandlerRequest<sup>12+</sup> 14563 14564Represents a request intercepted by the **WebSchemeHandler** object. 14565 14566### getHeader<sup>12+</sup> 14567 14568getHeader(): Array\<WebHeader\> 14569 14570Obtains the information about the resource request header. 14571 14572**System capability**: SystemCapability.Web.Webview.Core 14573 14574**Return value** 14575 14576| Type | Description | 14577| -------------------------- | ---------- | 14578| Array\<[WebHeader](#webheader)\> | Information about the resource request header.| 14579 14580**Example** 14581 14582For the complete sample code, see [onRequestStart](#onrequeststart12). 14583 14584### getRequestUrl<sup>12+</sup> 14585 14586getRequestUrl(): string 14587 14588Obtains the URL of the resource request. 14589 14590**System capability**: SystemCapability.Web.Webview.Core 14591 14592**Return value** 14593 14594| Type | Description | 14595| ------ | ------------- | 14596| string | URL of the resource request.| 14597 14598**Example** 14599 14600For the complete sample code, see [onRequestStart](#onrequeststart12). 14601 14602### getRequestMethod<sup>12+</sup> 14603 14604getRequestMethod(): string 14605 14606Obtains the request method. 14607 14608**System capability**: SystemCapability.Web.Webview.Core 14609 14610**Return value** 14611 14612| Type | Description | 14613| ------ | ------------- | 14614| string | Request method.| 14615 14616**Example** 14617 14618For the complete sample code, see [onRequestStart](#onrequeststart12). 14619 14620### getReferrer<sup>12+</sup> 14621 14622getReferrer(): string 14623 14624Obtains the referrer. 14625 14626**System capability**: SystemCapability.Web.Webview.Core 14627 14628**Return value** 14629 14630| Type | Description | 14631| ------ | ------------- | 14632| string | Obtained referrer.| 14633 14634**Example** 14635 14636For the complete sample code, see [onRequestStart](#onrequeststart12). 14637 14638### isMainFrame<sup>12+</sup> 14639 14640isMainFrame(): boolean 14641 14642Checks whether the resource request is for the main frame. 14643 14644**System capability**: SystemCapability.Web.Webview.Core 14645 14646**Return value** 14647 14648| Type | Description | 14649| ------ | ------------- | 14650| boolean | Whether the resource request is for the main frame.| 14651 14652**Example** 14653 14654For the complete sample code, see [onRequestStart](#onrequeststart12). 14655 14656### hasGesture<sup>12+</sup> 14657 14658hasGesture(): boolean 14659 14660Checks whether the resource request is associated with a gesture (for example, a tap). 14661 14662**System capability**: SystemCapability.Web.Webview.Core 14663 14664**Return value** 14665 14666| Type | Description | 14667| ------ | ------------- | 14668| boolean | Whether the resource request is associated with a gesture (for example, a tap).| 14669 14670**Example** 14671 14672For the complete sample code, see [onRequestStart](#onrequeststart12). 14673 14674### getHttpBodyStream<sup>12+</sup> 14675 14676getHttpBodyStream(): WebHttpBodyStream | null 14677 14678Obtains the **WebHttpBodyStream** instance in this resource request. 14679 14680**System capability**: SystemCapability.Web.Webview.Core 14681 14682**Return value** 14683 14684| Type | Description | 14685| ------ | ------------- | 14686| [WebHttpBodyStream](#webhttpbodystream12) \| null | **WebHttpBodyStream** instance in the resource request. If there is no **WebHttpBodyStream** instance, **null** is returned.| 14687 14688**Example** 14689 14690For the complete sample code, see [onRequestStart](#onrequeststart12). 14691 14692### getRequestResourceType<sup>12+</sup> 14693 14694getRequestResourceType(): WebResourceType 14695 14696Obtains the resource type of this resource request. 14697 14698**System capability**: SystemCapability.Web.Webview.Core 14699 14700**Return value** 14701 14702| Type | Description | 14703| ------ | ------------- | 14704| [WebResourceType](#webresourcetype12) | Resource type of the resource request.| 14705 14706**Example** 14707 14708For the complete sample code, see [onRequestStart](#onrequeststart12). 14709 14710### getFrameUrl<sup>12+</sup> 14711 14712getFrameUrl(): string 14713 14714Obtains the URL of the frame that triggers this request. 14715 14716**System capability**: SystemCapability.Web.Webview.Core 14717 14718**Return value** 14719 14720| Type | Description | 14721| ------ | ------------- | 14722| string | URL of the frame that triggers the request.| 14723 14724**Example** 14725 14726For the complete sample code, see [onRequestStart](#onrequeststart12). 14727 14728## WebSchemeHandlerResponse<sup>12+</sup> 14729 14730Represents a request response. You can create a response for an intercepted request, fill in custom content, and return the response to the **Web** component. 14731 14732### constructor<sup>12+</sup> 14733 14734constructor() 14735 14736A constructor used to create a **Response** object. 14737 14738**System capability**: SystemCapability.Web.Webview.Core 14739 14740**Example** 14741 14742```ts 14743// xxx.ets 14744import { webview } from '@kit.ArkWeb'; 14745import { BusinessError } from '@kit.BasicServicesKit'; 14746import { WebNetErrorList } from '@ohos.web.netErrorList'; 14747 14748@Entry 14749@Component 14750struct WebComponent { 14751 controller: webview.WebviewController = new webview.WebviewController(); 14752 schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); 14753 14754 build() { 14755 Column() { 14756 Button('response').onClick(() => { 14757 let response = new webview.WebSchemeHandlerResponse(); 14758 try { 14759 response.setUrl("http://www.example.com") 14760 response.setStatus(200) 14761 response.setStatusText("OK") 14762 response.setMimeType("text/html") 14763 response.setEncoding("utf-8") 14764 response.setHeaderByName("header1", "value1", false) 14765 response.setNetErrorCode(WebNetErrorList.NET_OK) 14766 console.log("[schemeHandler] getUrl:" + response.getUrl()) 14767 console.log("[schemeHandler] getStatus:" + response.getStatus()) 14768 console.log("[schemeHandler] getStatusText:" + response.getStatusText()) 14769 console.log("[schemeHandler] getMimeType:" + response.getMimeType()) 14770 console.log("[schemeHandler] getEncoding:" + response.getEncoding()) 14771 console.log("[schemeHandler] getHeaderByValue:" + response.getHeaderByName("header1")) 14772 console.log("[schemeHandler] getNetErrorCode:" + response.getNetErrorCode()) 14773 14774 } catch (error) { 14775 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 14776 } 14777 }) 14778 Web({ src: 'https://www.example.com', controller: this.controller }) 14779 } 14780 } 14781} 14782 14783``` 14784 14785### setUrl<sup>12+</sup> 14786 14787setUrl(url: string): void 14788 14789Sets 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. 14790 14791**System capability**: SystemCapability.Web.Webview.Core 14792 14793**Parameters** 14794 14795| Name | Type | Mandatory | Description | 14796| --------| ------- | ---- | ---------------------------| 14797| url | string | Yes | URL to be redirected to.| 14798 14799**Example** 14800 14801For the complete sample code, see [constructor](#constructor12). 14802 14803**Error codes** 14804 14805For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14806 14807| ID| Error Message | 14808| -------- | ----------------------- | 14809| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 14810 14811### setNetErrorCode<sup>12+</sup> 14812 14813setNetErrorCode(code: WebNetErrorList): void 14814 14815Sets the network error code for this response. 14816 14817**System capability**: SystemCapability.Web.Webview.Core 14818 14819**Parameters** 14820 14821| Name | Type | Mandatory | Description | 14822| --------| ------- | ---- | ---------------------------| 14823| code | [WebNetErrorList](js-apis-netErrorList.md#webneterrorlist) | Yes | Network error code.| 14824 14825**Error codes** 14826 14827For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14828 14829| ID| Error Message | 14830| -------- | ----------------------- | 14831| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 14832 14833**Example** 14834 14835For the complete sample code, see [constructor](#constructor12). 14836 14837### setStatus<sup>12+</sup> 14838 14839setStatus(code: number): void 14840 14841Sets the HTTP status code for this response. 14842 14843**System capability**: SystemCapability.Web.Webview.Core 14844 14845**Parameters** 14846 14847| Name | Type | Mandatory | Description | 14848| --------| ------- | ---- | ---------------------------| 14849| code | number | Yes | HTTP status code.| 14850 14851**Error codes** 14852 14853For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14854 14855| ID| Error Message | 14856| -------- | ----------------------- | 14857| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 14858 14859**Example** 14860 14861For the complete sample code, see [constructor](#constructor12). 14862 14863### setStatusText<sup>12+</sup> 14864 14865setStatusText(text: string): void 14866 14867Sets the status text for this response. 14868 14869**System capability**: SystemCapability.Web.Webview.Core 14870 14871**Parameters** 14872 14873| Name | Type | Mandatory | Description | 14874| --------| ------- | ---- | ---------------------------| 14875| text | string | Yes | Status text.| 14876 14877**Error codes** 14878 14879For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14880 14881| ID| Error Message | 14882| -------- | ----------------------- | 14883| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 14884 14885**Example** 14886 14887For the complete sample code, see [constructor](#constructor12). 14888 14889### setMimeType<sup>12+</sup> 14890 14891setMimeType(type: string): void 14892 14893Sets the MIME type for this response. 14894 14895**System capability**: SystemCapability.Web.Webview.Core 14896 14897**Parameters** 14898 14899| Name | Type | Mandatory | Description | 14900| --------| ------- | ---- | ---------------------------| 14901| type | string | Yes | MIME type.| 14902 14903**Error codes** 14904 14905For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14906 14907| ID| Error Message | 14908| -------- | ----------------------- | 14909| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 14910 14911**Example** 14912 14913For the complete sample code, see [constructor](#constructor12). 14914 14915### setEncoding<sup>12+</sup> 14916 14917setEncoding(encoding: string): void 14918 14919Sets the character set for this response. 14920 14921**System capability**: SystemCapability.Web.Webview.Core 14922 14923**Parameters** 14924 14925| Name | Type | Mandatory | Description | 14926| --------| ------- | ---- | ---------------------------| 14927| encoding | string | Yes | Character set.| 14928 14929**Error codes** 14930 14931For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14932 14933| ID| Error Message | 14934| -------- | ----------------------- | 14935| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 14936 14937**Example** 14938 14939For the complete sample code, see [constructor](#constructor12). 14940 14941### setHeaderByName<sup>12+</sup> 14942 14943setHeaderByName(name: string, value: string, overwrite: boolean): void 14944 14945Sets the header information for this response. 14946 14947**System capability**: SystemCapability.Web.Webview.Core 14948 14949**Parameters** 14950 14951| Name | Type | Mandatory | Description | 14952| --------| ------- | ---- | ---------------------------| 14953| name | string | Yes | Name of the header.| 14954| value | string | Yes | Value of the header.| 14955| overwrite | boolean | Yes | Whether to override the existing header. The value **true** means to override the existing header, and **false** means the opposite.| 14956 14957**Error codes** 14958 14959For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 14960 14961| ID| Error Message | 14962| -------- | ----------------------- | 14963| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 14964 14965**Example** 14966 14967For the complete sample code, see [constructor](#constructor12). 14968 14969### getUrl<sup>12+</sup> 14970 14971getUrl(): string 14972 14973Obtains the redirection URL or the URL changed due to HSTS. 14974Caution: To obtain the URL for JavaScriptProxy communication API authentication, use [getLastJavascriptProxyCallingFrameUrl<sup>12+</sup>](#getlastjavascriptproxycallingframeurl12). 14975 14976**System capability**: SystemCapability.Web.Webview.Core 14977 14978**Return value** 14979 14980| Type | Description | 14981| ------- | --------------------------------------- | 14982| string | Redirection URL or the URL changed due to HSTS.| 14983 14984**Example** 14985 14986For the complete sample code, see [constructor](#constructor12). 14987 14988### getNetErrorCode<sup>12+</sup> 14989 14990getNetErrorCode(): WebNetErrorList 14991 14992Obtains the network error code of this response. 14993 14994**System capability**: SystemCapability.Web.Webview.Core 14995 14996**Return value** 14997 14998| Type | Description | 14999| ------- | --------------------------------------- | 15000| [WebNetErrorList](js-apis-netErrorList.md#webneterrorlist) | Network error code of the response.| 15001 15002**Example** 15003 15004For the complete sample code, see [constructor](#constructor12). 15005 15006### getStatus<sup>12+</sup> 15007 15008getStatus(): number 15009 15010Obtains the HTTP status code of this response. 15011 15012**System capability**: SystemCapability.Web.Webview.Core 15013 15014**Return value** 15015 15016| Type | Description | 15017| ------- | --------------------------------------- | 15018| number | HTTP status code of the response.| 15019 15020**Example** 15021 15022For the complete sample code, see [constructor](#constructor12). 15023 15024### getStatusText<sup>12+</sup> 15025 15026getStatusText(): string 15027 15028Obtains the status text of this response. 15029 15030**System capability**: SystemCapability.Web.Webview.Core 15031 15032**Return value** 15033 15034| Type | Description | 15035| ------- | --------------------------------------- | 15036| string | Status text.| 15037 15038**Example** 15039 15040For the complete sample code, see [constructor](#constructor12). 15041 15042### getMimeType<sup>12+</sup> 15043 15044getMimeType(): string 15045 15046Obtains the MIME type of this response. 15047 15048**System capability**: SystemCapability.Web.Webview.Core 15049 15050**Return value** 15051 15052| Type | Description | 15053| ------- | --------------------------------------- | 15054| string | MIME type.| 15055 15056**Example** 15057 15058For the complete sample code, see [constructor](#constructor12). 15059 15060### getEncoding<sup>12+</sup> 15061 15062getEncoding(): string 15063 15064Obtains the character set of this response. 15065 15066**System capability**: SystemCapability.Web.Webview.Core 15067 15068**Return value** 15069 15070| Type | Description | 15071| ------- | --------------------------------------- | 15072| string | Character set.| 15073 15074**Example** 15075 15076For the complete sample code, see [constructor](#constructor12). 15077 15078### getHeaderByName<sup>12+</sup> 15079 15080getHeaderByName(name: string): string 15081 15082Obtains the character set of this response. 15083 15084**System capability**: SystemCapability.Web.Webview.Core 15085 15086**Parameters** 15087 15088| Name | Type | Mandatory| Description | 15089| ------- | ---------------- | ---- | -------------------- | 15090| name | string | Yes | Name of the header. | 15091 15092 15093**Return value** 15094 15095| Type | Description | 15096| ------- | --------------------------------------- | 15097| string | Value of the header.| 15098 15099**Example** 15100 15101For the complete sample code, see [constructor](#constructor12). 15102 15103## WebResourceHandler<sup>12+</sup> 15104 15105Represents a **WebResourceHandler** object, which can return custom response headers and response bodies to the **Web** component. 15106 15107### didReceiveResponse<sup>12+</sup> 15108 15109didReceiveResponse(response: WebSchemeHandlerResponse): void 15110 15111Sends a response header for this request. 15112 15113**System capability**: SystemCapability.Web.Webview.Core 15114 15115**Parameters** 15116 15117| Name | Type | Mandatory | Description | 15118| ---------------| ------- | ---- | ------------- | 15119| response | [WebSchemeHandlerResponse](#webschemehandlerresponse12) | Yes | Response to send.| 15120 15121**Error codes** 15122 15123For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15124 15125| ID| Error Message | 15126| -------- | ------------------------------------- | 15127| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 15128| 17100021 | The resource handler is invalid. | 15129 15130**Example** 15131 15132See [OnRequestStart](#onrequeststart12). 15133 15134### didReceiveResponseBody<sup>12+</sup> 15135 15136didReceiveResponseBody(data: ArrayBuffer): void 15137 15138Sends a response body for this request. 15139 15140**System capability**: SystemCapability.Web.Webview.Core 15141 15142**Parameters** 15143 15144| Name | Type | Mandatory | Description | 15145| ---------------| ------- | ---- | ------------- | 15146| data | ArrayBuffer | Yes | Response body.| 15147 15148**Error codes** 15149 15150For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15151 15152| ID| Error Message | 15153| -------- | ------------------------------------- | 15154| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | 15155| 17100021 | The resource handler is invalid. | 15156 15157**Example** 15158 15159See [OnRequestStart](#onrequeststart12). 15160 15161### didFinish<sup>12+</sup> 15162 15163didFinish(): void 15164 15165Notifies 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. 15166 15167**System capability**: SystemCapability.Web.Webview.Core 15168 15169**Error codes** 15170 15171For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15172 15173| ID| Error Message | 15174| -------- | ------------------------------------- | 15175| 17100021 | The resource handler is invalid. | 15176 15177**Example** 15178 15179See [OnRequestStart](#onrequeststart12). 15180 15181### didFail<sup>12+</sup> 15182 15183didFail(code: WebNetErrorList): void 15184 15185Notifies the ArkWeb kernel that this request fails. Before calling this API, call [didReceiveResponse](#didreceiveresponse12) to send a response header to this request. 15186 15187**System capability**: SystemCapability.Web.Webview.Core 15188 15189**Parameters** 15190 15191| Name | Type | Mandatory | Description | 15192| --------| ------- | ---- | ---------------------------| 15193| code | [WebNetErrorList](js-apis-netErrorList.md#webneterrorlist) | Yes | Network error code.| 15194 15195**Error codes** 15196 15197For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15198 15199| ID| Error Message | 15200| -------- | ------------------------------------- | 15201| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | 15202| 17100021 | The resource handler is invalid. | 15203 15204**System capability**: SystemCapability.Web.Webview.Core 15205 15206**Example** 15207 15208See [OnRequestStart](#onrequeststart12). 15209 15210## WebSchemeHandler<sup>12+</sup> 15211 15212Represents a **WebSchemeHandler** object used to intercept requests for a specific scheme. 15213 15214### onRequestStart<sup>12+</sup> 15215 15216onRequestStart(callback: (request: WebSchemeHandlerRequest, handler: WebResourceHandler) => boolean): void 15217 15218Called 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. 15219 15220**System capability**: SystemCapability.Web.Webview.Core 15221 15222**Parameters** 15223 15224| Name | Type | Mandatory| Description | 15225| -------- | -------------------- | ---- | ---------- | 15226| 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.| 15227 15228**Error codes** 15229 15230For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15231 15232| ID| Error Message | 15233| -------- | ------------------------------------- | 15234| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 15235 15236**Example** 15237 15238```ts 15239// xxx.ets 15240import { webview } from '@kit.ArkWeb'; 15241import { BusinessError } from '@kit.BasicServicesKit'; 15242import { buffer } from '@kit.ArkTS'; 15243import { WebNetErrorList } from '@ohos.web.netErrorList'; 15244 15245@Entry 15246@Component 15247struct WebComponent { 15248 controller: webview.WebviewController = new webview.WebviewController(); 15249 schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); 15250 htmlData: string = "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>"; 15251 15252 build() { 15253 Column() { 15254 Web({ src: 'https://www.example.com', controller: this.controller }) 15255 .onControllerAttached(() => { 15256 try { 15257 this.schemeHandler.onRequestStart((request: webview.WebSchemeHandlerRequest, resourceHandler: webview.WebResourceHandler) => { 15258 console.log("[schemeHandler] onRequestStart"); 15259 try { 15260 console.log("[schemeHandler] onRequestStart url:" + request.getRequestUrl()); 15261 console.log("[schemeHandler] onRequestStart method:" + request.getRequestMethod()); 15262 console.log("[schemeHandler] onRequestStart referrer:" + request.getReferrer()); 15263 console.log("[schemeHandler] onRequestStart isMainFrame:" + request.isMainFrame()); 15264 console.log("[schemeHandler] onRequestStart hasGesture:" + request.hasGesture()); 15265 console.log("[schemeHandler] onRequestStart header size:" + request.getHeader().length); 15266 console.log("[schemeHandler] onRequestStart resource type:" + request.getRequestResourceType()); 15267 console.log("[schemeHandler] onRequestStart frame url:" + request.getFrameUrl()); 15268 let header = request.getHeader(); 15269 for (let i = 0; i < header.length; i++) { 15270 console.log("[schemeHandler] onRequestStart header:" + header[i].headerKey + " " + header[i].headerValue); 15271 } 15272 let stream = request.getHttpBodyStream(); 15273 if (stream) { 15274 console.log("[schemeHandler] onRequestStart has http body stream"); 15275 } else { 15276 console.log("[schemeHandler] onRequestStart has no http body stream"); 15277 } 15278 } catch (error) { 15279 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 15280 } 15281 15282 if (request.getRequestUrl().endsWith("example.com")) { 15283 return false; 15284 } 15285 15286 let response = new webview.WebSchemeHandlerResponse(); 15287 try { 15288 response.setNetErrorCode(WebNetErrorList.NET_OK); 15289 response.setStatus(200); 15290 response.setStatusText("OK"); 15291 response.setMimeType("text/html"); 15292 response.setEncoding("utf-8"); 15293 response.setHeaderByName("header1", "value1", false); 15294 } catch (error) { 15295 console.error(`[schemeHandler] ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 15296 } 15297 15298 // Before calling didFinish or didFail, call didReceiveResponse to send a response header to this request. 15299 let buf = buffer.from(this.htmlData) 15300 try { 15301 if (buf.length == 0) { 15302 console.log("[schemeHandler] length 0"); 15303 resourceHandler.didReceiveResponse(response); 15304 // If the value of buf.length is 0 in normal cases, call resourceHandler.didFinish(). Otherwise, call resourceHandler.didFail(). 15305 resourceHandler.didFail(WebNetErrorList.ERR_FAILED); 15306 } else { 15307 console.log("[schemeHandler] length 1"); 15308 resourceHandler.didReceiveResponse(response); 15309 resourceHandler.didReceiveResponseBody(buf.buffer); 15310 resourceHandler.didFinish(); 15311 } 15312 } catch (error) { 15313 console.error(`[schemeHandler] ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 15314 } 15315 return true; 15316 }) 15317 15318 this.schemeHandler.onRequestStop((request: webview.WebSchemeHandlerRequest) => { 15319 console.log("[schemeHandler] onRequestStop"); 15320 }); 15321 15322 this.controller.setWebSchemeHandler('https', this.schemeHandler); 15323 } catch (error) { 15324 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 15325 } 15326 }) 15327 .javaScriptAccess(true) 15328 .domStorageAccess(true) 15329 } 15330 } 15331} 15332``` 15333### onRequestStop<sup>12+</sup> 15334 15335onRequestStop(callback: Callback\<WebSchemeHandlerRequest\>): void 15336 15337Called 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: 15338 153391. The **WebResourceHandler** object calls **didFail** or **didFinish**. 15340 153412. The request is interrupted due to other reasons. 15342 15343**System capability**: SystemCapability.Web.Webview.Core 15344 15345**Parameters** 15346 15347| Name | Type | Mandatory| Description | 15348| -------- | -------------------- | ---- | ---------- | 15349| callback | Callback\<[WebSchemeHandlerRequest](#webschemehandlerrequest12)\> | Yes | Callback invoked when the request is complete.| 15350 15351**Error codes** 15352 15353For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 15354 15355| ID| Error Message | 15356| -------- | ------------------------------------- | 15357| 401 | Invalid input parameter. | 15358 15359**Example** 15360 15361For the complete sample code, see [onRequestStart](#onrequeststart12). 15362 15363## CacheOptions<sup>12+</sup> 15364 15365Represents 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. 15366 15367**System capability**: SystemCapability.Web.Webview.Core 15368 15369| Name | Type | Readable| Writable|Description | 15370| ----------- | ------ | -----|------|------------------- | 15371| 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. | 15372 15373## PlaybackStatus<sup>12+</sup> 15374 15375Represents the playback status of the player, functioning as a parameter in [handleStatusChanged](#handlestatuschanged12). 15376 15377**System capability**: SystemCapability.Web.Webview.Core 15378 15379| Name| Value| Description| 15380|------|----|------| 15381| PAUSED | 0 | Playing.| 15382| PLAYING | 1 | Paused.| 15383 15384## NetworkState<sup>12+<sup> 15385 15386Describes the network status of the player. 15387 15388**System capability**: SystemCapability.Web.Webview.Core 15389 15390| Name| Value| Description| 15391|------|----|------| 15392| EMPTY | 0 | The player has not started downloading data.| 15393| 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.| 15394| LOADING | 2 | The player is downloading media data.| 15395| NETWORK_ERROR | 3 | A network error occurs.| 15396 15397## ReadyState<sup>12+<sup> 15398 15399Enumerates the cache states of the player. 15400 15401**System capability**: SystemCapability.Web.Webview.Core 15402 15403| Name| Value| Description| 15404|------|----|------| 15405| HAVE_NOTHING | 0 | There is no data cached.| 15406| HAVE_METADATA | 1 | Only media metadata is cached.| 15407| HAVE_CURRENT_DATA | 2 | Data up to the current playback position is cached.| 15408| HAVE_FUTURE_DATA | 3 | Data beyond the current playback position is cached, but there might still be stutters during playback.| 15409| HAVE_ENOUGH_DATA | 4 | Sufficient data has been cached to ensure smooth playback.| 15410 15411## MediaError<sup>12+<sup> 15412 15413Enumerates the error types of the player. 15414 15415**System capability**: SystemCapability.Web.Webview.Core 15416 15417| Name| Value| Description| 15418|------|----|------| 15419| NETWORK_ERROR | 1 | Network error.| 15420| FORMAT_ERROR | 2 | Media format error.| 15421| DECODE_ERROR | 3 | Decoding error.| 15422 15423## NativeMediaPlayerHandler<sup>12+<sup> 15424 15425Represents a **NativeMediaPlayerHandler** object used as the parameter of the [CreateNativeMediaPlayerCallback](#createnativemediaplayercallback12) callback. 15426The application uses this object to report the player status to the ArkWeb engine. 15427 15428### handleStatusChanged<sup>12+<sup> 15429 15430handleStatusChanged(status: PlaybackStatus): void 15431 15432Called to notify the ArkWeb engine of the playback status of the player when the playback status changes. 15433 15434**System capability**: SystemCapability.Web.Webview.Core 15435 15436**Parameters** 15437 15438| Name| Type| Mandatory| Description| 15439|--------|------|------|------| 15440| status | [PlaybackStatus](#playbackstatus12) | Yes| Player status.| 15441 15442**Example** 15443 15444For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15445 15446### handleVolumeChanged<sup>12+<sup> 15447 15448handleVolumeChanged(volume: number): void 15449 15450Called to notify the ArkWeb engine of the volume of the player when the volume changes. 15451 15452**System capability**: SystemCapability.Web.Webview.Core 15453 15454**Parameters** 15455 15456| Name| Type| Mandatory| Description| 15457|--------|------|------|------| 15458| volume | number | Yes| Volume of the player.| 15459 15460**Example** 15461 15462For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15463 15464### handleMutedChanged<sup>12+<sup> 15465 15466handleMutedChanged(muted: boolean): void 15467 15468Called to notify the ArkWeb engine of the muted status of the player when the muted status changes. 15469 15470**System capability**: SystemCapability.Web.Webview.Core 15471 15472**Parameters** 15473 15474| Name| Type| Mandatory| Description| 15475|--------|------|------|------| 15476| muted | boolean | Yes| Whether the player is muted.| 15477 15478**Example** 15479 15480For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15481 15482### handlePlaybackRateChanged<sup>12+<sup> 15483 15484handlePlaybackRateChanged(playbackRate: number): void 15485 15486Called to notify the ArkWeb engine of the playback rate of the player when the playback rate changes. 15487 15488**System capability**: SystemCapability.Web.Webview.Core 15489 15490**Parameters** 15491 15492| Name| Type| Mandatory| Description| 15493|--------|------|------|------| 15494| playbackRate | number | Yes| Playback rate.| 15495 15496**Example** 15497 15498For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15499 15500### handleDurationChanged<sup>12+<sup> 15501 15502handleDurationChanged(duration: number): void 15503 15504Called to notify the ArkWeb engine of the total duration of the media. 15505 15506**System capability**: SystemCapability.Web.Webview.Core 15507 15508**Parameters** 15509 15510| Name| Type| Mandatory| Description| 15511|--------|------|------|------| 15512| duration | number | Yes| Total duration of the media. Unit: second.| 15513 15514**Example** 15515 15516For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15517 15518### handleTimeUpdate<sup>12+<sup> 15519 15520handleTimeUpdate(currentPlayTime: number): void 15521 15522Called to notify the ArkWeb engine of the playback progress when the playback progress changes. 15523 15524**System capability**: SystemCapability.Web.Webview.Core 15525 15526**Parameters** 15527 15528| Name| Type| Mandatory| Description| 15529|--------|------|------|------| 15530| currentPlayTime | number | Yes| Current progress. Unit: second. | 15531 15532**Example** 15533 15534For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15535 15536### handleBufferedEndTimeChanged<sup>12+<sup> 15537 15538handleBufferedEndTimeChanged(bufferedEndTime: number): void 15539 15540Called to notify the ArkWeb engine of the buffer time when the buffer time changes. 15541 15542**System capability**: SystemCapability.Web.Webview.Core 15543 15544**Parameters** 15545 15546| Name| Type| Mandatory| Description| 15547|--------|------|------|------| 15548| bufferedEndTime | number | Yes| Duration of media data in the buffer.| 15549 15550**Example** 15551 15552For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15553 15554### handleEnded<sup>12+<sup> 15555 15556handleEnded(): void 15557 15558Called to notify the ArkWeb engine that the media playback ends. 15559 15560**System capability**: SystemCapability.Web.Webview.Core 15561 15562**Example** 15563 15564For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15565 15566### handleNetworkStateChanged<sup>12+<sup> 15567 15568handleNetworkStateChanged(state: NetworkState): void 15569 15570Called to notify the ArkWeb engine of the network status of the player when the network status changes. 15571 15572**System capability**: SystemCapability.Web.Webview.Core 15573 15574**Parameters** 15575 15576| Name| Type| Mandatory| Description| 15577|--------|------|------|------| 15578| state | [NetworkState](#networkstate12) | Yes| Network status of the player.| 15579 15580**Example** 15581 15582For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15583 15584### handleReadyStateChanged<sup>12+<sup> 15585 15586handleReadyStateChanged(state: ReadyState): void 15587 15588Called to notify the ArkWeb engine of the cache status of the player when the cache status changes. 15589 15590**System capability**: SystemCapability.Web.Webview.Core 15591 15592**Parameters** 15593 15594| Name| Type| Mandatory| Description| 15595|--------|------|------|------| 15596| state | [ReadyState](#readystate12) | Yes| Cache status of the player.| 15597 15598**Example** 15599 15600For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15601 15602### handleFullscreenChanged<sup>12+<sup> 15603 15604handleFullscreenChanged(fullscreen: boolean): void 15605 15606Called to notify the ArkWeb engine of the full screen status of the player when the full screen status changes. 15607 15608**System capability**: SystemCapability.Web.Webview.Core 15609 15610**Parameters** 15611 15612| Name| Type| Mandatory| Description| 15613|--------|------|------|------| 15614| fullscreen | boolean | Yes| Whether the player is in full screen.| 15615 15616**Example** 15617 15618For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15619 15620### handleSeeking<sup>12+<sup> 15621 15622handleSeeking(): void 15623 15624Called to notify the ArkWeb engine that the player enters the seek state. 15625 15626**System capability**: SystemCapability.Web.Webview.Core 15627 15628**Example** 15629 15630For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15631 15632### handleSeekFinished<sup>12+<sup> 15633 15634handleSeekFinished(): void 15635 15636Called to notify the ArkWeb engine that the seek operation is complete. 15637 15638**System capability**: SystemCapability.Web.Webview.Core 15639 15640**Example** 15641 15642For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15643 15644### handleError<sup>12+<sup> 15645 15646handleError(error: MediaError, errorMessage: string): void 15647 15648Called to notify the ArkWeb engine that an error occurs with the player. 15649 15650**System capability**: SystemCapability.Web.Webview.Core 15651 15652**Parameters** 15653 15654| Name| Type| Mandatory| Description| 15655|--------|------|------|------| 15656| error | [MediaError](#mediaerror12) | Yes| Error object type.| 15657| errorMessage | string | Yes| Error message.| 15658 15659**Example** 15660 15661For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15662 15663### handleVideoSizeChanged<sup>12+<sup> 15664 15665handleVideoSizeChanged(width: number, height: number): void 15666 15667Called to notify the ArkWeb engine of the video size of the player. 15668 15669**System capability**: SystemCapability.Web.Webview.Core 15670 15671**Parameters** 15672 15673| Name| Type| Mandatory| Description| 15674|--------|------|------|------| 15675| width | number | Yes| Video width.| 15676| height | number | Yes| Video height.| 15677 15678**Example** 15679 15680For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15681 15682## SuspendType<sup>12+<sup> 15683 15684Enumerates the suspension types of the player. 15685 15686**System capability**: SystemCapability.Web.Webview.Core 15687 15688| Name| Value| Description| 15689|------|----|------| 15690| ENTER_BACK_FORWARD_CACHE | 0 | The page enters the BFCache.| 15691| ENTER_BACKGROUND | 1 | The page is displayed in the background.| 15692| AUTO_CLEANUP | 2 | The page is automatically cleaned up by the system.| 15693 15694## NativeMediaPlayerBridge<sup>12+<sup> 15695 15696Implements a **NativeMediaPlayerBridge** object, which is the return value of the [CreateNativeMediaPlayerCallback](#createnativemediaplayercallback12) callback. 15697It is an interface class that acts as a bridge between the web media player and the ArkWeb kernel. 15698The ArkWeb engine uses an object of this interface class to control the player created by the application to take over web page media. 15699 15700### updateRect<sup>12+<sup> 15701 15702updateRect(x: number, y: number, width: number, height: number): void 15703 15704Updates the surface position information. 15705 15706**System capability**: SystemCapability.Web.Webview.Core 15707 15708**Parameters** 15709 15710| Name| Type| Mandatory| Description| 15711|--------|------|------|------| 15712| x | number | Yes| X coordinate of the surface relative to the web component.| 15713| y | number | Yes| Y coordinate of the surface relative to the web component.| 15714| width | number | Yes| Width of the surface.| 15715| height | number | Yes| Height of the surface.| 15716 15717**Example** 15718 15719For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15720 15721### play<sup>12+<sup> 15722 15723play(): void 15724 15725Plays this video. 15726 15727**System capability**: SystemCapability.Web.Webview.Core 15728 15729**Example** 15730 15731For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15732 15733### pause<sup>12+<sup> 15734 15735pause(): void 15736 15737Pauses playback. 15738 15739**System capability**: SystemCapability.Web.Webview.Core 15740 15741**Example** 15742 15743For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15744 15745### seek<sup>12+<sup> 15746 15747seek(targetTime: number): void 15748 15749Seeks to a specific time point in the media. 15750 15751**System capability**: SystemCapability.Web.Webview.Core 15752 15753**Parameters** 15754 15755| Name| Type| Mandatory| Description| 15756|--------|------|------|------| 15757| targetTime | number | Yes| Target time point. Unit: second.| 15758 15759**Example** 15760 15761For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15762 15763### setVolume<sup>12+<sup> 15764 15765setVolume(volume: number): void 15766 15767Sets the playback volume. 15768The value range is [0, 1.0]. 15769 15770**Parameters** 15771 15772| Name| Type| Mandatory| Description| 15773|--------|------|------|------| 15774| 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.| 15775 15776**System capability**: SystemCapability.Web.Webview.Core 15777 15778**Example** 15779 15780For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15781 15782### setMuted<sup>12+<sup> 15783 15784setMuted(muted: boolean): void 15785 15786Sets the muted status. 15787 15788**System capability**: SystemCapability.Web.Webview.Core 15789 15790**Parameters** 15791 15792| Name| Type| Mandatory| Description| 15793|--------|------|------|------| 15794| muted | boolean | Yes| Whether to mute the player.| 15795 15796**Example** 15797 15798For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15799 15800### setPlaybackRate<sup>12+<sup> 15801 15802setPlaybackRate(playbackRate: number): void 15803 15804Sets the playback rate. 15805The value range is [0, 10.0]. 15806 15807**System capability**: SystemCapability.Web.Webview.Core 15808 15809**Parameters** 15810 15811| Name| Type| Mandatory| Description| 15812|--------|------|------|------| 15813| playbackRate | number | Yes| Playback rate. The value range is [0, 10.0]. The value **1** indicates the original speed of playback.| 15814 15815**Example** 15816 15817For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15818 15819### release<sup>12+<sup> 15820 15821release(): void 15822 15823Releases this player. 15824 15825**System capability**: SystemCapability.Web.Webview.Core 15826 15827**Example** 15828 15829For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15830 15831### enterFullscreen<sup>12+<sup> 15832 15833enterFullscreen(): void 15834 15835Enables the player to enter full screen mode. 15836 15837**System capability**: SystemCapability.Web.Webview.Core 15838 15839**Example** 15840 15841For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15842 15843### exitFullscreen<sup>12+<sup> 15844 15845exitFullscreen(): void 15846 15847Enables the player to exit full screen mode. 15848 15849**System capability**: SystemCapability.Web.Webview.Core 15850 15851**Example** 15852 15853For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15854 15855### resumePlayer<sup>12+<sup> 15856 15857resumePlayer?(): void 15858 15859Resumes the player and its status information. 15860 15861**System capability**: SystemCapability.Web.Webview.Core 15862 15863**Example** 15864 15865For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15866 15867### suspendPlayer<sup>12+<sup> 15868 15869suspendPlayer?(type: SuspendType): void 15870 15871Suspends the player and save its status information. 15872 15873**System capability**: SystemCapability.Web.Webview.Core 15874 15875**Parameters** 15876 15877| Name| Type| Mandatory| Description| 15878|--------|------|------|------| 15879| type | [SuspendType](#suspendtype12) | Yes| Suspension type of the player.| 15880 15881**Example** 15882 15883For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15884 15885## MediaType<sup>12+<sup> 15886 15887Enumerates the media types. 15888 15889**System capability**: SystemCapability.Web.Webview.Core 15890 15891| Name| Value| Description| 15892|------|----|------| 15893| VIDEO | 0 | Video.| 15894| AUDIO | 1 | Audio.| 15895 15896## SourceType<sup>12+<sup> 15897 15898Enumerates the media source types. 15899 15900**System capability**: SystemCapability.Web.Webview.Core 15901 15902| Name| Value| Description| 15903|------|----|------| 15904| URL | 0 | URL.| 15905| MSE | 1 | Blob.| 15906 15907## MediaSourceInfo<sup>12+<sup> 15908 15909Provides the information about the media source. 15910 15911**System capability**: SystemCapability.Web.Webview.Core 15912 15913| Name| Type| Mandatory| Description| 15914|------|------|------|------| 15915| type | [SourceType](#sourcetype12) | Yes| Type of the media source.| 15916| source | string | Yes| Address of the media source.| 15917| format | string | Yes| Format of the media source, which may be empty. You need to determine the format by yourself.| 15918 15919## NativeMediaPlayerSurfaceInfo<sup>12+<sup> 15920 15921Provides 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). 15922 15923**System capability**: SystemCapability.Web.Webview.Core 15924 15925| Name| Type| Mandatory| Description| 15926|------|------|------|------| 15927| 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).| 15928| rect | [RectEvent](#rectevent12) | Yes| Position of the surface.| 15929 15930## Preload<sup>12+<sup> 15931 15932Defines how the player preloads media data. 15933 15934**System capability**: SystemCapability.Web.Webview.Core 15935 15936| Name| Value| Description| 15937|------|----|------| 15938| NONE | 0 | No media data is preloaded.| 15939| METADATA | 1 | Only the metadata of the media is preloaded.| 15940| AUTO | 2 | A sufficient amount of media data is preloaded to ensure smooth playback| 15941 15942## MediaInfo<sup>12+<sup> 15943 15944Represents a **MediaInfo** object used as a parameter of the [CreateNativeMediaPlayerCallback](#createnativemediaplayercallback12) callback. 15945The 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 . 15946 15947**System capability**: SystemCapability.Web.Webview.Core 15948 15949| Name| Type| Mandatory| Description| 15950|------|------|------|------| 15951| embedID | string | Yes| ID of **\<video>** or **\<audio>** on the web page.| 15952| mediaType | [MediaType](#mediatype12) | Yes| Type of the media.| 15953| mediaSrcList | [MediaSourceInfo](#mediasourceinfo12)[] | Yes| Source of the media. There may be multiple sources. The application needs to select a supported source to play.| 15954| surfaceInfo | [NativeMediaPlayerSurfaceInfo](#nativemediaplayersurfaceinfo12) | Yes| Surface information used for same-layer rendering.| 15955| controlsShown | boolean | Yes| Whether the **controls** attribute exists in **\<video>** or **\<audio>**.| 15956| controlList | string[] | Yes| Value of the **controlslist** attribute in **\<video>** or **\<audio>**.| 15957| muted | boolean | Yes| Whether to mute the player.| 15958| posterUrl | string | Yes| URL of a poster.| 15959| preload | [Preload](#preload12) | Yes| Whether preloading is required.| 15960| headers | Record\<string, string\> | Yes| HTTP headers that need to be included in the player's request for media resources.| 15961| attributes | Record\<string, string\> | Yes| Attributes in **\<video>** or **\<audio>**.| 15962 15963 15964## CreateNativeMediaPlayerCallback<sup>12+<sup> 15965 15966type CreateNativeMediaPlayerCallback = (handler: NativeMediaPlayerHandler, mediaInfo: MediaInfo) => NativeMediaPlayerBridge 15967 15968Represents a **CreateNativeMediaPlayerCallback** object used as a parameter of the [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12) callback. 15969This object is used to create a player to take over media playback of the web page. 15970 15971**System capability**: SystemCapability.Web.Webview.Core 15972 15973**Parameters** 15974 15975| Name| Type| Mandatory| Description| 15976|--------|------|------|------| 15977| handler | [NativeMediaPlayerHandler](#nativemediaplayerhandler12) | Yes| Object used to report the player status to the ArkWeb engine.| 15978| mediaInfo | [MediaInfo](#mediainfo12) | Yes| Information about the media on the web page.| 15979 15980**Return value** 15981 15982| Type| Description| 15983|------|------| 15984| [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.| 15985 15986**Example** 15987 15988For the complete sample code, see [onCreateNativeMediaPlayer](#oncreatenativemediaplayer12). 15989 15990## OfflineResourceMap<sup>12+</sup> 15991 15992Implements 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. 15993 15994**System capability**: SystemCapability.Web.Webview.Core 15995 15996| Name | Type | Readable| Writable|Description | 15997| ----------- | ------ | -----|------|------------------- | 15998| 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. | 15999| resource | Uint8Array | Yes | Yes | Content of a local offline resource. | 16000| 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**. | 16001| type | [OfflineResourceType](#offlineresourcetype12) | Yes | Yes | Resource type. Currently, only the JavaScript, image, and CSS types are supported. | 16002 16003## OfflineResourceType<sup>12+</sup> 16004 16005Represents the local offline resource type corresponding to an [OfflineResourceMap](#offlineresourcemap12) object. 16006 16007**System capability**: SystemCapability.Web.Webview.Core 16008 16009| Name | Value| Description | 16010| ------------ | -- |--------------------------------- | 16011| IMAGE | 0 | Resource of the image type.| 16012| CSS | 1 | Resource of the CSS type.| 16013| CLASSIC_JS | 2 | Javascript resource loaded through the <script src="" /\> tag.| 16014| MODULE_JS | 3 |Javascript resource loaded through the <script src="" type="module" /\> tag.| 16015 16016## WebResourceType<sup>12+</sup> 16017 16018Enumerates the types of requested resources. 16019 16020**System capability**: SystemCapability.Web.Webview.Core 16021 16022| Name | Value| Description | 16023| ------------ | -- |--------------------------------- | 16024| MAIN_FRAME | 0 | Top-level page.| 16025| SUB_FRAME | 1 | Frame or Iframe.| 16026| STYLE_SHEET | 2 | CSS style sheet.| 16027| SCRIPT | 3 | External script.| 16028| IMAGE | 4 | Image (JPG, GIF, PNG, or other format).| 16029| FONT_RESOURCE | 5 | Font.| 16030| SUB_RESOURCE | 6 | Other sub-resource. If the type is unknown, it is used as the default type.| 16031| OBJECT | 7 | Object (or embed) tag of the plug-in, or the resource requested by the plug-in.| 16032| MEDIA | 8 | Media resource.| 16033| WORKER | 9 | Main resource of a dedicated worker thread.| 16034| SHARED_WORKER | 10 | Main resource of a shared worker thread.| 16035| PREFETCH | 11 | Explicit prefetch request.| 16036| FAVICON | 12 | Website icon.| 16037| XHR | 13 | XMLHttpRequest.| 16038| PING | 14 | <a ping\>/sendBeacon ping request.| 16039| SERVICE_WORKER | 15 | Main resource of a service worker.| 16040| CSP_REPORT | 16 | Report of Content Security Policy violation.| 16041| PLUGIN_RESOURCE | 17 | Resource requested by the plug-in.| 16042| NAVIGATION_PRELOAD_MAIN_FRAME | 19 | Main frame redirection request that triggers service worker preloading.| 16043| NAVIGATION_PRELOAD_SUB_FRAME | 20 | Subframe redirection request that triggers service worker preloading.| 16044 16045## RectEvent<sup>12+<sup> 16046 16047Defines a rectangle. 16048 16049**System capability**: SystemCapability.Web.Webview.Core 16050 16051| Name | Type | Readable| Writable| Description | 16052| -------------- | --------- | ---- | ---- | ---------------------------- | 16053| x | number | Yes | Yes | X-axis coordinate of the upper left corner of the rectangle. | 16054| y | number | Yes | Yes | Y-axis coordinate of the upper left corner of the rectangle. | 16055| width | number | Yes | Yes | Width of the rectangle. | 16056| height | number | Yes | Yes | Height of the rectangle. | 16057 16058## BackForwardCacheSupportedFeatures<sup>12+<sup> 16059 16060Adds a page that uses any of the following features to the back-forward cache. For the complete sample code, see [enableBackForwardCache](#enablebackforwardcache12). 16061 16062**System capability**: SystemCapability.Web.Webview.Core 16063 16064| Name| Type| Mandatory| Description| 16065|------|------|------|------| 16066| 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.| 16067| 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.| 16068 16069### constructor<sup>12+</sup> 16070 16071constructor() 16072 16073Constructs a **BackForwardCacheSupportedFeatures** instance. 16074 16075**System capability**: SystemCapability.Web.Webview.Core 16076 16077## BackForwardCacheOptions<sup>12+<sup> 16078 16079Implements a **BackForwardCacheOptions** object to set back-forward cache options of the **Web** component. For the complete sample code, see [BackForwardCacheOptions](#backforwardcacheoptions12). 16080 16081**System capability**: SystemCapability.Web.Webview.Core 16082 16083| Name| Type| Mandatory| Description| 16084|------|------|------|------| 16085| 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.| 16086| 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.| 16087 16088### constructor<sup>12+</sup> 16089 16090constructor() 16091 16092Constructs a **BackForwardCacheOptions** instance. 16093 16094**System capability**: SystemCapability.Web.Webview.Core 16095 16096## AdsBlockManager<sup>12+</sup> 16097 16098Implements 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. 16099 16100### setAdsBlockRules<sup>12+</sup> 16101 16102static setAdsBlockRules(rulesFile: string, replace: boolean): void 16103 16104Sets a custom ad blocking rule file that conforms to the universal EasyList syntax in the **Web** components. 16105 16106> **NOTE** 16107> 16108> 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. 16109 16110**System capability**: SystemCapability.Web.Webview.Core 16111 16112**Parameters** 16113 16114| Name | Type | Mandatory| Description | 16115| ---------- | ------ | ---- | -------------------------------- | 16116| 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.| 16117| 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.| 16118 16119**Error codes** 16120 16121For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 16122 16123| ID| Error Message | 16124| -------- | ----------------------- | 16125| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 16126 16127**Example** 16128 16129```ts 16130// xxx.ets 16131import { webview } from '@kit.ArkWeb'; 16132import { picker, fileUri } from '@kit.CoreFileKit'; 16133 16134// 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. 16135@Entry 16136@Component 16137struct WebComponent { 16138 controller: webview.WebviewController = new webview.WebviewController(); 16139 16140 build() { 16141 Row() { 16142 Flex() { 16143 Button({ type: ButtonType.Capsule }) { 16144 Text("setAdsBlockRules") 16145 } 16146 .onClick(() => { 16147 try { 16148 let documentSelectionOptions: ESObject = new picker.DocumentSelectOptions(); 16149 let documentPicker: ESObject = new picker.DocumentViewPicker(); 16150 documentPicker.select(documentSelectionOptions).then((documentSelectResult: ESObject) => { 16151 if (documentSelectResult && documentSelectResult.length > 0) { 16152 let fileRealPath = new fileUri.FileUri(documentSelectResult[0]); 16153 console.info('DocumentViewPicker.select successfully, uri: ' + fileRealPath); 16154 webview.AdsBlockManager.setAdsBlockRules(fileRealPath.path, true); 16155 } 16156 }) 16157 } catch (err) { 16158 console.error('DocumentViewPicker.select failed with err:' + err); 16159 } 16160 }) 16161 } 16162 } 16163 } 16164} 16165``` 16166 16167### addAdsBlockDisallowedList<sup>12+</sup> 16168 16169static addAdsBlockDisallowedList(domainSuffixes: Array\<string\>): void 16170 16171Adds 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. 16172 16173> **NOTE** 16174> 16175> The domain name set by this API is not persistent; they need to be set again after the application is restarted. 16176> 16177> 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**. 16178 16179**System capability**: SystemCapability.Web.Webview.Core 16180 16181**Parameters** 16182 16183| Name | Type | Mandatory| Description | 16184| ---------- | ------ | ---- | -------------------------------- | 16185| domainSuffixes | Array\<string\> | Yes | Array of domain names, for example, ['example.com', 'abcd.efg.com'].| 16186 16187**Error codes** 16188 16189For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 16190 16191| ID| Error Message | 16192| -------- | ----------------------- | 16193| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 16194 16195**Example** 16196 16197```ts 16198// xxx.ets 16199import { webview } from '@kit.ArkWeb'; 16200 16201// This example demonstrates how to click a button to add an array of domain names to the disallowed list. 16202@Entry 16203@Component 16204struct WebComponent { 16205 main_url: string = 'https://www.example.com'; 16206 text_input_controller: TextInputController = new TextInputController(); 16207 controller: webview.WebviewController = new webview.WebviewController(); 16208 @State input_text: string = 'https://www.example.com'; 16209 16210 build() { 16211 Column() { 16212 Row() { 16213 Flex() { 16214 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 16215 .id("input_url") 16216 .height(40) 16217 .margin(5) 16218 .borderColor(Color.Blue) 16219 .onChange((value: string) => { 16220 this.input_text = value; 16221 }) 16222 16223 Button({type: ButtonType.Capsule}) { Text("Go") } 16224 .onClick(() => { 16225 this.controller.loadUrl(this.input_text); 16226 }) 16227 16228 Button({type: ButtonType.Capsule}) { Text("addAdsBlockDisallowedList") } 16229 .onClick(() => { 16230 let arrDomainSuffixes = new Array<string>(); 16231 arrDomainSuffixes.push('example.com'); 16232 arrDomainSuffixes.push('abcdefg.cn'); 16233 webview.AdsBlockManager.addAdsBlockDisallowedList(arrDomainSuffixes); 16234 }) 16235 } 16236 } 16237 Web({ src: this.main_url, controller: this.controller }) 16238 .onControllerAttached(()=>{ 16239 this.controller.enableAdsBlock(true); 16240 }) 16241 } 16242 } 16243} 16244``` 16245 16246### removeAdsBlockDisallowedList<sup>12+</sup> 16247 16248static removeAdsBlockDisallowedList(domainSuffixes: Array\<string\>): void 16249 16250Removes an array of domain names from the disallowed list of this **AdsBlockManager** object. 16251 16252> **NOTE** 16253> 16254> 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. 16255 16256**System capability**: SystemCapability.Web.Webview.Core 16257 16258**Parameters** 16259 16260| Name | Type | Mandatory| Description | 16261| ---------- | ------ | ---- | -------------------------------- | 16262| domainSuffixes | Array\<string\> | Yes | Array of domain names, for example, ['example.com', 'abcd.efg.com'].| 16263 16264**Error codes** 16265 16266For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 16267 16268| ID| Error Message | 16269| -------- | ----------------------- | 16270| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 16271 16272**Example** 16273 16274```ts 16275// xxx.ets 16276import { webview } from '@kit.ArkWeb'; 16277 16278// This example demonstrates how to click a button to remove an array of domain names from the disallowed list. 16279@Entry 16280@Component 16281struct WebComponent { 16282 main_url: string = 'https://www.example.com'; 16283 text_input_controller: TextInputController = new TextInputController(); 16284 controller: webview.WebviewController = new webview.WebviewController(); 16285 @State input_text: string = 'https://www.example.com'; 16286 16287 build() { 16288 Column() { 16289 Row() { 16290 Flex() { 16291 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 16292 .id("input_url") 16293 .height(40) 16294 .margin(5) 16295 .borderColor(Color.Blue) 16296 .onChange((value: string) => { 16297 this.input_text = value; 16298 }) 16299 16300 Button({type: ButtonType.Capsule}) { Text("Go") } 16301 .onClick(() => { 16302 this.controller.loadUrl(this.input_text); 16303 }) 16304 16305 Button({type: ButtonType.Capsule}) { Text("removeAdsBlockDisallowedList") } 16306 .onClick(() => { 16307 let arrDomainSuffixes = new Array<string>(); 16308 arrDomainSuffixes.push('example.com'); 16309 arrDomainSuffixes.push('abcdefg.cn'); 16310 webview.AdsBlockManager.removeAdsBlockDisallowedList(arrDomainSuffixes); 16311 }) 16312 } 16313 } 16314 Web({ src: this.main_url, controller: this.controller }) 16315 .onControllerAttached(()=>{ 16316 this.controller.enableAdsBlock(true); 16317 }) 16318 } 16319 } 16320} 16321``` 16322 16323### clearAdsBlockDisallowedList<sup>12+</sup> 16324 16325static clearAdsBlockDisallowedList(): void 16326 16327Clears the disallowed list of this **AdsBlockManager** object. 16328 16329**System capability**: SystemCapability.Web.Webview.Core 16330 16331**Example** 16332 16333```ts 16334// xxx.ets 16335import { webview } from '@kit.ArkWeb'; 16336 16337@Entry 16338@Component 16339struct WebComponent { 16340 main_url: string = 'https://www.example.com'; 16341 text_input_controller: TextInputController = new TextInputController(); 16342 controller: webview.WebviewController = new webview.WebviewController(); 16343 @State input_text: string = 'https://www.example.com'; 16344 16345 build() { 16346 Column() { 16347 Row() { 16348 Flex() { 16349 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 16350 .id("input_url") 16351 .height(40) 16352 .margin(5) 16353 .borderColor(Color.Blue) 16354 .onChange((value: string) => { 16355 this.input_text = value; 16356 }) 16357 16358 Button({type: ButtonType.Capsule}) { Text("Go") } 16359 .onClick(() => { 16360 this.controller.loadUrl(this.input_text); 16361 }) 16362 16363 Button({type: ButtonType.Capsule}) { Text("clearAdsBlockDisallowedList") } 16364 .onClick(() => { 16365 webview.AdsBlockManager.clearAdsBlockDisallowedList(); 16366 }) 16367 } 16368 } 16369 Web({ src: this.main_url, controller: this.controller }) 16370 .onControllerAttached(()=>{ 16371 this.controller.enableAdsBlock(true); 16372 }) 16373 } 16374 } 16375} 16376``` 16377 16378### addAdsBlockAllowedList<sup>12+</sup> 16379 16380static addAdsBlockAllowedList(domainSuffixes: Array\<string\>): void 16381 16382Adds 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. 16383 16384> **NOTE** 16385> 16386> The domain name set by this API is not persistent; they need to be set again after the application is restarted. 16387> 16388> 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. 16389 16390**System capability**: SystemCapability.Web.Webview.Core 16391 16392**Parameters** 16393 16394| Name | Type | Mandatory| Description | 16395| ---------- | ------ | ---- | -------------------------------- | 16396| domainSuffixes | Array\<string\> | Yes | Array of domain names, for example, ['example.com', 'abcd.efg.com'].| 16397 16398**Error codes** 16399 16400For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 16401 16402| ID| Error Message | 16403| -------- | ----------------------- | 16404| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 16405 16406**Example** 16407 16408```ts 16409// xxx.ets 16410import { webview } from '@kit.ArkWeb'; 16411 16412// This example demonstrates how to click a button to add an array of domain names to the disallowed list. 16413@Entry 16414@Component 16415struct WebComponent { 16416 main_url: string = 'https://www.example.com'; 16417 text_input_controller: TextInputController = new TextInputController(); 16418 controller: webview.WebviewController = new webview.WebviewController(); 16419 @State input_text: string = 'https://www.example.com'; 16420 16421 build() { 16422 Column() { 16423 Row() { 16424 Flex() { 16425 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 16426 .id("input_url") 16427 .height(40) 16428 .margin(5) 16429 .borderColor(Color.Blue) 16430 .onChange((value: string) => { 16431 this.input_text = value; 16432 }) 16433 16434 Button({type: ButtonType.Capsule}) { Text("Go") } 16435 .onClick(() => { 16436 this.controller.loadUrl(this.input_text); 16437 }) 16438 16439 Button({type: ButtonType.Capsule}) { Text("addAdsBlockAllowedList") } 16440 .onClick(() => { 16441 let arrDisallowDomainSuffixes = new Array<string>(); 16442 arrDisallowDomainSuffixes.push('example.com'); 16443 webview.AdsBlockManager.addAdsBlockDisallowedList(arrDisallowDomainSuffixes); 16444 16445 let arrAllowedDomainSuffixes = new Array<string>(); 16446 arrAllowedDomainSuffixes.push('news.example.com'); 16447 webview.AdsBlockManager.addAdsBlockAllowedList(arrAllowedDomainSuffixes); 16448 }) 16449 } 16450 } 16451 Web({ src: this.main_url, controller: this.controller }) 16452 .onControllerAttached(()=>{ 16453 this.controller.enableAdsBlock(true) 16454 }) 16455 } 16456 } 16457} 16458``` 16459 16460### removeAdsBlockAllowedList<sup>12+</sup> 16461 16462static removeAdsBlockAllowedList(domainSuffixes: Array\<string\>): void 16463 16464Removes an array of domain names from the allowed list of this **AdsBlockManager** object. 16465 16466> **NOTE** 16467> 16468> 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. 16469 16470**System capability**: SystemCapability.Web.Webview.Core 16471 16472**Parameters** 16473 16474| Name | Type | Mandatory| Description | 16475| ---------- | ------ | ---- | -------------------------------- | 16476| domainSuffixes | Array\<string\> | Yes | Array of domain names, for example, ['example.com', 'abcd.efg.com'].| 16477 16478**Error codes** 16479 16480For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 16481 16482| ID| Error Message | 16483| -------- | ----------------------- | 16484| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | 16485 16486**Example** 16487 16488```ts 16489// xxx.ets 16490import { webview } from '@kit.ArkWeb'; 16491 16492// This example demonstrates how to click a button to remove an array of domain names from the disallowed list. 16493@Entry 16494@Component 16495struct WebComponent { 16496 main_url: string = 'https://www.example.com'; 16497 text_input_controller: TextInputController = new TextInputController(); 16498 controller: webview.WebviewController = new webview.WebviewController(); 16499 @State input_text: string = 'https://www.example.com'; 16500 16501 build() { 16502 Column() { 16503 Row() { 16504 Flex() { 16505 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 16506 .id("input_url") 16507 .height(40) 16508 .margin(5) 16509 .borderColor(Color.Blue) 16510 .onChange((value: string) => { 16511 this.input_text = value; 16512 }) 16513 16514 Button({type: ButtonType.Capsule}) { Text("Go") } 16515 .onClick(() => { 16516 this.controller.loadUrl(this.input_text); 16517 }) 16518 16519 Button({type: ButtonType.Capsule}) { Text("removeAdsBlockAllowedList") } 16520 .onClick(() => { 16521 let arrDomainSuffixes = new Array<string>(); 16522 arrDomainSuffixes.push('example.com'); 16523 arrDomainSuffixes.push('abcdefg.cn'); 16524 webview.AdsBlockManager.removeAdsBlockAllowedList(arrDomainSuffixes); 16525 }) 16526 } 16527 } 16528 Web({ src: this.main_url, controller: this.controller }) 16529 .onControllerAttached(()=>{ 16530 this.controller.enableAdsBlock(true); 16531 }) 16532 } 16533 } 16534} 16535``` 16536 16537### clearAdsBlockAllowedList<sup>12+</sup> 16538 16539static clearAdsBlockAllowedList(): void 16540 16541Clears the allowed list of this **AdsBlockManager** object. 16542 16543**System capability**: SystemCapability.Web.Webview.Core 16544 16545**Example** 16546 16547```ts 16548// xxx.ets 16549import { webview } from '@kit.ArkWeb'; 16550 16551@Entry 16552@Component 16553struct WebComponent { 16554 main_url: string = 'https://www.example.com'; 16555 text_input_controller: TextInputController = new TextInputController(); 16556 controller: webview.WebviewController = new webview.WebviewController(); 16557 @State input_text: string = 'https://www.example.com'; 16558 16559 16560 build() { 16561 Column() { 16562 Row() { 16563 Flex() { 16564 TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller}) 16565 .id("input_url") 16566 .height(40) 16567 .margin(5) 16568 .borderColor(Color.Blue) 16569 .onChange((value: string) => { 16570 this.input_text = value; 16571 }) 16572 16573 Button({type: ButtonType.Capsule}) { Text("Go") } 16574 .onClick(() => { 16575 this.controller.loadUrl(this.input_text); 16576 }) 16577 16578 Button({type: ButtonType.Capsule}) { Text("clearAdsBlockAllowedList") } 16579 .onClick(() => { 16580 webview.AdsBlockManager.clearAdsBlockAllowedList(); 16581 }) 16582 } 16583 } 16584 Web({ src: this.main_url, controller: this.controller }) 16585 .onControllerAttached(()=>{ 16586 this.controller.enableAdsBlock(true); 16587 }) 16588 } 16589 } 16590} 16591``` 16592 16593## SnapshotInfo<sup>12+</sup> 16594 16595Provides information used to obtain a full drawing result. 16596 16597**System capability**: SystemCapability.Web.Webview.Core 16598 16599| Name| Type| Mandatory| Description| 16600|------|------|------|------| 16601| id | string | No| Snapshot ID.| 16602| 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.| 16603 16604## SnapshotResult<sup>12+</sup> 16605 16606Represents a full drawing result. 16607 16608**System capability**: SystemCapability.Web.Webview.Core 16609 16610| Name| Type| Mandatory| Description| 16611|------|------|--|---------| 16612| id | string | No| Snapshot ID.| 16613| 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.| 16614| 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.| 16615| imagePixelMap | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | No| Full drawing result in image.pixelMap format.| 16616 16617> **NOTE** 16618> 16619> Only static images and texts in the rendering process can be captured. 16620> 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. 16621 16622## ScrollType<sup>12+</sup> 16623 16624Represents a scroll type, which is used in [setScrollable](#setscrollable12). 16625 16626**System capability**: SystemCapability.Web.Webview.Core 16627 16628| Name | Value| Description | 16629| ------------ | -- |--------------------------------- | 16630| EVENT | 0 | Scrolling event, indicating that a web page is scrolled by using a touchscreen, a touchpad, or a mouse.| 16631 16632## PressureLevel<sup>14+</sup> 16633 16634Represents 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. 16635 16636**System capability**: SystemCapability.Web.Webview.Core 16637 16638| Name| Value| Description| 16639| ------------------------------- | - | ---------- | 16640| 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.| 16641| MEMORY_PRESSURE_LEVEL_CRITICAL | 2 | Critical memory pressure level. At this level, the **Web** kernel attempts to release all possible memory caches.| 16642 16643## PdfConfiguration<sup>14+</sup> 16644 16645Specifies the input parameters of **createPdf()**. 16646 16647> **NOTE** 16648> 16649> The number of pixels is calculated as follows: Number of pixels = 96 x Number of inches. 16650 16651**System capability**: SystemCapability.Web.Webview.Core 16652 16653| Name | Type | Mandatory| Description | 16654| --------------------- | ------- | ---- | ------------------------------------------------------------ | 16655| width | number | Yes | Page width, in inches.<br>Recommended value: 8.27 inches of A4 paper width. | 16656| height | number | Yes | Page height, in inches.<br>Recommended value: 11.69 inches of A4 paper height. | 16657| 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**| 16658| 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.| 16659| 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.| 16660| 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.| 16661| 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.| 16662| shouldPrintBackground | boolean | No | Whether to print the background color. The default value is **false**. | 16663 16664## PdfData<sup>14+</sup> 16665 16666Represents the output data stream class of **createPdf()**. 16667 16668> **NOTE** 16669> 16670> When a PDF file is generated on a web page, a data stream is returned, which is encapsulated by the **PdfData** class. 16671 16672### pdfArrayBuffer<sup>14+</sup> 16673 16674pdfArrayBuffer(): Uint8Array 16675 16676Obtains the data stream generated by a web page. For details, see [createPdf](#createpdf14). 16677 16678**System capability**: SystemCapability.Web.Webview.Core 16679 16680**Return value** 16681 16682| Type | Description | 16683| ---------- | -------- | 16684| Uint8Array | Data stream.| 16685 16686## ScrollOffset<sup>13+</sup> 16687 16688Represents the current scrolling offset of a web page. 16689 16690**System capability**: SystemCapability.Web.Webview.Core 16691 16692| Name| Type | Readable| Writable| Description | 16693| ---- | ------ | ---- | ---- | ------------------------------------------------------------ | 16694| 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.| 16695| 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.| 16696 16697<!--no_check-->