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