1# Events 2 3The following universal events are supported: [onAppear](../apis-arkui/arkui-ts/ts-universal-events-show-hide.md#onappear), [onDisAppear](../apis-arkui/arkui-ts/ts-universal-events-show-hide.md#ondisappear), [onBlur](../apis-arkui/arkui-ts/ts-universal-focus-event.md#onblur), [onFocus](../apis-arkui/arkui-ts/ts-universal-focus-event.md#onfocus), [onDragEnd](../apis-arkui/arkui-ts/ts-universal-events-drag-drop.md#ondragend10), [onDragEnter](../apis-arkui/arkui-ts/ts-universal-events-drag-drop.md#ondragenter), [onDragStart](../apis-arkui/arkui-ts/ts-universal-events-drag-drop.md#ondragstart), [onDragMove](../apis-arkui/arkui-ts/ts-universal-events-drag-drop.md#ondragmove), [onDragLeave](../apis-arkui/arkui-ts/ts-universal-events-drag-drop.md#ondragleave), [onDrop](../apis-arkui/arkui-ts/ts-universal-events-drag-drop.md#ondrop), [onHover](../apis-arkui/arkui-ts/ts-universal-events-hover.md#onhover), [onMouse](../apis-arkui/arkui-ts/ts-universal-mouse-key.md#onmouse), [onKeyEvent](../apis-arkui/arkui-ts/ts-universal-events-key.md#onkeyevent), [onTouch](../apis-arkui/arkui-ts/ts-universal-events-touch.md#ontouch), [onVisibleAreaChange](../apis-arkui/arkui-ts/ts-universal-component-visible-area-change-event.md#onvisibleareachange) 4 5> **NOTE** 6> 7> - The initial APIs of this component are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. 8> 9> - You can preview how this component looks on a real device, but not in DevEco Studio Previewer. 10 11## onAlert 12 13onAlert(callback: Callback\<OnAlertEvent, boolean\>) 14 15Triggered when **alert()** is invoked to display an alert dialog box on the web page. 16 17**System capability**: SystemCapability.Web.Webview.Core 18 19**Parameters** 20 21| Name | Type | Mandatory | Description | 22| ------- | --------------------- | ---- | --------------- | 23| callback | Callback\<[OnAlertEvent](./arkts-basic-components-web-i.md#onalertevent12), boolean\> | Yes | Callback used when **alert()** is invoked to display an alert dialog box on the web page.<br>Return value: boolean<br> If the callback returns **true**, the application can use the custom dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **Web** component the confirmation result. If the callback returns **false**, the processing result of the dialog box is regarded as cancel.| 24 25**Example** 26 27 ```ts 28 // xxx.ets 29 import { webview } from '@kit.ArkWeb'; 30 31 @Entry 32 @Component 33 struct WebComponent { 34 controller: webview.WebviewController = new webview.WebviewController(); 35 uiContext: UIContext = this.getUIContext(); 36 37 build() { 38 Column() { 39 Web({ src: $rawfile("index.html"), controller: this.controller }) 40 .onAlert((event) => { 41 if (event) { 42 console.log("event.url:" + event.url); 43 console.log("event.message:" + event.message); 44 this.uiContext.showAlertDialog({ 45 title: 'onAlert', 46 message: 'text', 47 primaryButton: { 48 value: 'ok', 49 action: () => { 50 event.result.handleConfirm(); 51 } 52 }, 53 cancel: () => { 54 event.result.handleCancel(); 55 } 56 }) 57 } 58 return true; 59 }) 60 } 61 } 62 } 63 ``` 64 65 HTML file to be loaded: 66 ```html 67 <!--index.html--> 68 <!DOCTYPE html> 69 <html> 70 <head> 71 <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8"> 72 </head> 73 <body> 74 <h1>WebView onAlert Demo</h1> 75 <button onclick="myFunction()">Click here</button> 76 <script> 77 function myFunction() { 78 alert("Hello World"); 79 } 80 </script> 81 </body> 82 </html> 83 ``` 84 85## onBeforeUnload 86 87onBeforeUnload(callback: Callback\<OnBeforeUnloadEvent, boolean\>) 88 89Triggered when a user is about to leave, refresh, or close this page. This API takes effect only when the page has obtained focus. 90 91**System capability**: SystemCapability.Web.Webview.Core 92 93**Parameters** 94 95| Name | Type | Mandatory | Description | 96| ------- | --------------------- | ---- | --------------- | 97| callback | Callback\<[OnBeforeUnloadEvent](./arkts-basic-components-web-i.md#onbeforeunloadevent12), boolean\> | Yes | Callback triggered when the current page is about to be refreshed or closed.<br>Return value: boolean<br> If the callback returns **true**, the application can use the custom dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **Web** component whether to exit the current page based on the user's operation. The value **false** means that the custom dialog box drawn in the function is ineffective.| 98 99**Example** 100 101 ```ts 102 // xxx.ets 103 import { webview } from '@kit.ArkWeb'; 104 105 @Entry 106 @Component 107 struct WebComponent { 108 controller: webview.WebviewController = new webview.WebviewController(); 109 uiContext: UIContext = this.getUIContext(); 110 111 build() { 112 Column() { 113 Web({ src: $rawfile("index.html"), controller: this.controller }) 114 .onBeforeUnload((event) => { 115 if (event) { 116 console.log("event.url:" + event.url); 117 console.log("event.message:" + event.message); 118 console.log("event.isReload:" + event?.isReload ?? 'false'); 119 this.uiContext.showAlertDialog({ 120 title: 'onBeforeUnload', 121 message: 'text', 122 primaryButton: { 123 value: 'cancel', 124 action: () => { 125 event.result.handleCancel(); 126 } 127 }, 128 secondaryButton: { 129 value: 'ok', 130 action: () => { 131 event.result.handleConfirm(); 132 } 133 }, 134 cancel: () => { 135 event.result.handleCancel(); 136 } 137 }) 138 } 139 return true; 140 }) 141 } 142 } 143 } 144 ``` 145 146 HTML file to be loaded: 147 ```html 148 <!--index.html--> 149 <!DOCTYPE html> 150 <html> 151 <head> 152 <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8"> 153 </head> 154 <body onbeforeunload="return myFunction()"> 155 <h1>WebView onBeforeUnload Demo</h1> 156 <a href="https://www.example.com">Click here</a> 157 <script> 158 function myFunction() { 159 return "onBeforeUnload Event"; 160 } 161 </script> 162 </body> 163 </html> 164 ``` 165 166## onConfirm 167 168onConfirm(callback: Callback\<OnConfirmEvent, boolean\>) 169 170Triggered when **confirm()** is invoked by the web page. 171 172**System capability**: SystemCapability.Web.Webview.Core 173 174**Parameters** 175 176| Name | Type | Mandatory | Description | 177| ------- | --------------------- | ---- | --------------- | 178| callback | Callback\<[OnConfirmEvent](./arkts-basic-components-web-i.md#onconfirmevent12), boolean\> | Yes | Callback triggered when **confirm()** is invoked by the web page.<br>Return value: boolean<br> If the callback returns **true**, the application can use the custom dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **Web** component the confirmation result. If the callback returns **false**, the processing result of the dialog box is regarded as cancel.| 179 180**Example** 181 182 ```ts 183 // xxx.ets 184 import { webview } from '@kit.ArkWeb'; 185 186 @Entry 187 @Component 188 struct WebComponent { 189 controller: webview.WebviewController = new webview.WebviewController(); 190 uiContext: UIContext = this.getUIContext(); 191 192 build() { 193 Column() { 194 Web({ src: $rawfile("index.html"), controller: this.controller }) 195 .onConfirm((event) => { 196 if (event) { 197 console.log("event.url:" + event.url); 198 console.log("event.message:" + event.message); 199 this.uiContext.showAlertDialog({ 200 title: 'onConfirm', 201 message: 'text', 202 primaryButton: { 203 value: 'cancel', 204 action: () => { 205 event.result.handleCancel(); 206 } 207 }, 208 secondaryButton: { 209 value: 'ok', 210 action: () => { 211 event.result.handleConfirm(); 212 } 213 }, 214 cancel: () => { 215 event.result.handleCancel(); 216 } 217 }) 218 } 219 return true; 220 }) 221 } 222 } 223 } 224 ``` 225 226 HTML file to be loaded: 227 ```html 228 <!--index.html--> 229 <!DOCTYPE html> 230 <html> 231 <head> 232 <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8"> 233 </head> 234 235 <body> 236 <h1>WebView onConfirm Demo</h1> 237 <button onclick="myFunction()">Click here</button> 238 <p id="demo"></p> 239 <script> 240 function myFunction() { 241 let x; 242 let r = confirm("click button!"); 243 if (r == true) { 244 x = "ok"; 245 } else { 246 x = "cancel"; 247 } 248 document.getElementById("demo").innerHTML = x; 249 } 250 </script> 251 </body> 252 </html> 253 ``` 254 255## onPrompt<sup>9+</sup> 256 257onPrompt(callback: Callback\<OnPromptEvent, boolean\>) 258 259Triggered when **prompt()** is invoked by the web page. 260 261**System capability**: SystemCapability.Web.Webview.Core 262 263**Parameters** 264 265| Name | Type | Mandatory | Description | 266| ------- | --------------------- | ---- | --------------- | 267| callback | Callback\<[OnPromptEvent](./arkts-basic-components-web-i.md#onpromptevent12), boolean\> | Yes | Callback used when **prompt()** is invoked by the web page.<br>Return value: boolean<br> If the callback returns **true**, the application can use the custom dialog box (allows the confirm, cancel, and input operations) and invoke the **JsResult** API to notify the **Web** component the processing result. If the callback returns **false**, the processing result of the dialog box is regarded as cancel.| 268 269**Example** 270 271 ```ts 272 // xxx.ets 273 import { CustomContentDialog } from '@kit.ArkUI'; 274 import { webview } from '@kit.ArkWeb'; 275 276 @Entry 277 @Component 278 struct WebComponent { 279 @State message: string = 'Hello World'; 280 @State title: string = 'Hello World'; 281 @State result: JsResult | null = null; 282 promptResult: string = ''; 283 webviewController: webview.WebviewController = new webview.WebviewController(); 284 dialogController: CustomDialogController = new CustomDialogController({ 285 builder: CustomContentDialog({ 286 primaryTitle: this.title, 287 contentBuilder: () => { 288 this.buildContent(); 289 }, 290 buttons: [ 291 { 292 value: 'Cancel', 293 buttonStyle: ButtonStyleMode.TEXTUAL, 294 action: () => { 295 console.info('Callback when the button is clicked'); 296 this.result?.handleCancel() 297 } 298 }, 299 { 300 value: 'OK', 301 buttonStyle: ButtonStyleMode.TEXTUAL, 302 action: () => { 303 this.result?.handlePromptConfirm(this.promptResult); 304 } 305 } 306 ], 307 }), 308 onWillDismiss: () => { 309 this.result?.handleCancel(); 310 this.dialogController.close(); 311 } 312 }); 313 314 // Content area of the custom dialog box 315 @Builder 316 buildContent(): void { 317 Column() { 318 Text(this.message) 319 TextInput() 320 .onChange((value) => { 321 this.promptResult = value; 322 }) 323 .defaultFocus(true) 324 } 325 .width('100%') 326 } 327 328 build() { 329 Column() { 330 Web({ src: $rawfile('index.html'), controller: this.webviewController }) 331 .onPrompt((event) => { 332 if (event) { 333 console.log("event.url:" + event.url); 334 console.log("event.message:" + event.message); 335 console.log("event.value:" + event.value); 336 this.title = "Message from" + event.url + ""; 337 this.message = event.message; 338 this.promptResult = event.value; 339 this.result = event.result; 340 this.dialogController.open(); 341 } 342 return true; 343 }) 344 } 345 } 346 } 347 ``` 348 349 HTML file to be loaded: 350 ```html 351 <!--index.html--> 352 <!DOCTYPE html> 353 <html> 354 <head> 355 <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8"> 356 </head> 357 358 <body> 359 <h1>WebView onPrompt Demo</h1> 360 <button onclick="myFunction()">Click here</button> 361 <p id="demo"></p> 362 <script> 363 function myFunction() { 364 let message = prompt("Message info", "Hello World"); 365 if (message != null && message != "") { 366 document.getElementById("demo").innerHTML = message; 367 } 368 } 369 </script> 370 </body> 371 </html> 372 ``` 373 374## onConsole 375 376onConsole(callback: Callback\<OnConsoleEvent, boolean\>) 377 378Triggered to notify the host application of a JavaScript console message. 379 380**System capability**: SystemCapability.Web.Webview.Core 381 382**Parameters** 383 384| Name | Type | Mandatory | Description | 385| ------- | --------------------------------- | ---- | --------- | 386| callback | Callback\<[OnConsoleEvent](./arkts-basic-components-web-i.md#onconsoleevent12), boolean\> | Yes | Callback used when the web page receives a JavaScript console message.<br>Return value: boolean<br> The value **true** means that the message will not be printed to HiLog logs, and **false** means the opposite.| 387 388**Example** 389 390 ```ts 391 // xxx.ets 392 import { webview } from '@kit.ArkWeb'; 393 394 @Entry 395 @Component 396 struct WebComponent { 397 controller: webview.WebviewController = new webview.WebviewController(); 398 399 build() { 400 Column() { 401 Button('onconsole message') 402 .onClick(() => { 403 this.controller.runJavaScript('myFunction()'); 404 }) 405 Web({ src: $rawfile('index.html'), controller: this.controller }) 406 .onConsole((event) => { 407 if (event) { 408 console.log('getMessage:' + event.message.getMessage()); 409 console.log('getSourceId:' + event.message.getSourceId()); 410 console.log('getLineNumber:' + event.message.getLineNumber()); 411 console.log('getMessageLevel:' + event.message.getMessageLevel()); 412 } 413 return false; 414 }) 415 } 416 } 417 } 418 ``` 419 420 HTML file to be loaded: 421 ```html 422 <!-- index.html --> 423 <!DOCTYPE html> 424 <html> 425 <body> 426 <script> 427 function myFunction() { 428 console.log("onconsole printf"); 429 } 430 </script> 431 </body> 432 </html> 433 ``` 434 435## onDownloadStart 436 437onDownloadStart(callback: Callback\<OnDownloadStartEvent\>) 438 439Triggered to instruct the main application to start downloading a file. 440 441**System capability**: SystemCapability.Web.Webview.Core 442 443**Parameters** 444 445| Name | Type | Mandatory | Description | 446| ------------------ | ------ | ---- | ----------------------------------- | 447| callback | Callback\<[OnDownloadStartEvent](./arkts-basic-components-web-i.md#ondownloadstartevent12)\> | Yes | Callback used when a download starts. | 448 449**Example** 450 451 ```ts 452 // xxx.ets 453 import { webview } from '@kit.ArkWeb'; 454 455 @Entry 456 @Component 457 struct WebComponent { 458 controller: webview.WebviewController = new webview.WebviewController(); 459 460 build() { 461 Column() { 462 Web({ src: 'www.example.com', controller: this.controller }) 463 .onDownloadStart((event) => { 464 if (event) { 465 console.log('url:' + event.url) 466 console.log('userAgent:' + event.userAgent) 467 console.log('contentDisposition:' + event.contentDisposition) 468 console.log('contentLength:' + event.contentLength) 469 console.log('mimetype:' + event.mimetype) 470 } 471 }) 472 } 473 } 474 } 475 ``` 476 477## onErrorReceive 478 479onErrorReceive(callback: Callback\<OnErrorReceiveEvent\>) 480 481Triggered when an error occurs during web page loading. The error may occur on the main resource or sub-resource. You can use [isMainFrame](./arkts-basic-components-web-WebResourceRequest.md#ismainframe) to determine whether the error occurs on the main resource. For performance reasons, simplify the implementation logic in the callback. This API is called when there is no network connection. 482 483**System capability**: SystemCapability.Web.Webview.Core 484 485**Parameters** 486 487| Name | Type | Mandatory | Description | 488| ------- | ---------------------------------------- | ---- | --------------- | 489| callback | Callback\<[OnErrorReceiveEvent](./arkts-basic-components-web-i.md#onerrorreceiveevent12)\> | Yes | Callback used when an error occurs during web page loading. | 490 491**Example** 492 493 ```ts 494 // xxx.ets 495 import { webview } from '@kit.ArkWeb'; 496 497 @Entry 498 @Component 499 struct WebComponent { 500 controller: webview.WebviewController = new webview.WebviewController(); 501 502 build() { 503 Column() { 504 Web({ src: 'www.example.com', controller: this.controller }) 505 .onErrorReceive((event) => { 506 if (event) { 507 console.log('getErrorInfo:' + event.error.getErrorInfo()); 508 console.log('getErrorCode:' + event.error.getErrorCode()); 509 console.log('url:' + event.request.getRequestUrl()); 510 console.log('isMainFrame:' + event.request.isMainFrame()); 511 console.log('isRedirect:' + event.request.isRedirect()); 512 console.log('isRequestGesture:' + event.request.isRequestGesture()); 513 console.log('getRequestHeader_headerKey:' + event.request.getRequestHeader().toString()); 514 let result = event.request.getRequestHeader(); 515 console.log('The request header result size is ' + result.length); 516 for (let i of result) { 517 console.log('The request header key is : ' + i.headerKey + ', value is : ' + i.headerValue); 518 } 519 } 520 }) 521 } 522 } 523 } 524 ``` 525 526## onHttpErrorReceive 527 528onHttpErrorReceive(callback: Callback\<OnHttpErrorReceiveEvent\>) 529 530Triggered when an HTTP error (the response code is greater than or equal to 400) occurs during web page resource loading. 531 532**System capability**: SystemCapability.Web.Webview.Core 533 534**Parameters** 535 536| Name | Type | Mandatory | Description | 537| -------- | ---------------------------------------- | ---- | ---------- | 538| callback | Callback\<[OnHttpErrorReceiveEvent](./arkts-basic-components-web-i.md#onhttperrorreceiveevent12)\> | Yes | Triggered when an HTTP error occurs during web page resource loading.| 539 540**Example** 541 542 ```ts 543 // xxx.ets 544 import { webview } from '@kit.ArkWeb'; 545 546 @Entry 547 @Component 548 struct WebComponent { 549 controller: webview.WebviewController = new webview.WebviewController(); 550 551 build() { 552 Column() { 553 Web({ src: 'www.example.com', controller: this.controller }) 554 .onHttpErrorReceive((event) => { 555 if (event) { 556 console.log('url:' + event.request.getRequestUrl()); 557 console.log('isMainFrame:' + event.request.isMainFrame()); 558 console.log('isRedirect:' + event.request.isRedirect()); 559 console.log('isRequestGesture:' + event.request.isRequestGesture()); 560 console.log('getResponseData:' + event.response.getResponseData()); 561 console.log('getResponseEncoding:' + event.response.getResponseEncoding()); 562 console.log('getResponseMimeType:' + event.response.getResponseMimeType()); 563 console.log('getResponseCode:' + event.response.getResponseCode()); 564 console.log('getReasonMessage:' + event.response.getReasonMessage()); 565 let result = event.request.getRequestHeader(); 566 console.log('The request header result size is ' + result.length); 567 for (let i of result) { 568 console.log('The request header key is : ' + i.headerKey + ' , value is : ' + i.headerValue); 569 } 570 let resph = event.response.getResponseHeader(); 571 console.log('The response header result size is ' + resph.length); 572 for (let i of resph) { 573 console.log('The response header key is : ' + i.headerKey + ' , value is : ' + i.headerValue); 574 } 575 } 576 }) 577 } 578 } 579 } 580 ``` 581 582## onPageBegin 583 584onPageBegin(callback: Callback\<OnPageBeginEvent\>) 585 586Triggered when the web page starts to be loaded. This callback is called only for the main frame content, and not for the iframe or frameset content. 587 588**System capability**: SystemCapability.Web.Webview.Core 589 590**Parameters** 591 592| Name | Type | Mandatory | Description | 593| ---- | ------ | ---- | --------- | 594| callback | Callback\<[OnPageBeginEvent](./arkts-basic-components-web-i.md#onpagebeginevent12)\> | Yes | Callback triggered when a web page loading starts.| 595 596**Example** 597 598 ```ts 599 // xxx.ets 600 import { webview } from '@kit.ArkWeb'; 601 602 @Entry 603 @Component 604 struct WebComponent { 605 controller: webview.WebviewController = new webview.WebviewController(); 606 607 build() { 608 Column() { 609 Web({ src: 'www.example.com', controller: this.controller }) 610 .onPageBegin((event) => { 611 if (event) { 612 console.log('url:' + event.url); 613 } 614 }) 615 } 616 } 617 } 618 ``` 619 620## onPageEnd 621 622onPageEnd(callback: Callback\<OnPageEndEvent\>) 623 624Triggered when the web page loading is complete. This callback is triggered only for the main frame content. 625 626**System capability**: SystemCapability.Web.Webview.Core 627 628**Parameters** 629 630| Name | Type | Mandatory | Description | 631| ---- | ------ | ---- | --------- | 632| callback | Callback\<[OnPageEndEvent](./arkts-basic-components-web-i.md#onpageendevent12)\> | Yes | Callback used when the web page loading is complete.| 633 634**Example** 635 636 ```ts 637 // xxx.ets 638 import { webview } from '@kit.ArkWeb'; 639 640 @Entry 641 @Component 642 struct WebComponent { 643 controller: webview.WebviewController = new webview.WebviewController(); 644 645 build() { 646 Column() { 647 Web({ src: 'www.example.com', controller: this.controller }) 648 .onPageEnd((event) => { 649 if (event) { 650 console.log('url:' + event.url); 651 } 652 }) 653 } 654 } 655 } 656 ``` 657 658## onLoadStarted<sup>20+</sup> 659 660onLoadStarted(callback: Callback\<OnLoadStartedEvent\>) 661 662Triggered to notify the host application that the page loading starts. This method is called once each time the main frame content is loaded. Therefore, for pages that contain iframes or frameset, **onLoadStarted** is called only once for the main frame. This means that when the content of the embedded frame changes, for example, a link or a fragment navigation in the iframe is clicked (navigation to **#fragment_id**), **onLoadStarted** is not invoked. 663 664**System capability**: SystemCapability.Web.Webview.Core 665 666**Parameters** 667 668| Name | Type | Mandatory | Description | 669| ---- | ------ | ---- | --------- | 670| callback | Callback\<[OnLoadStartedEvent](./arkts-basic-components-web-i.md#onloadstartedevent20)\> | Yes | Callback triggered when a web page loading starts.| 671 672**Example** 673 674 ```ts 675 // xxx.ets 676 import { webview } from '@kit.ArkWeb'; 677 678 @Entry 679 @Component 680 struct WebComponent { 681 controller: webview.WebviewController = new webview.WebviewController(); 682 683 build() { 684 Column() { 685 Web({ src: 'www.example.com', controller: this.controller }) 686 .onLoadStarted((event) => { 687 if (event) { 688 console.log('url:' + event.url); 689 } 690 }) 691 } 692 } 693 } 694 ``` 695 696## onLoadFinished<sup>20+</sup> 697 698onLoadFinished(callback: Callback\<OnLoadFinishedEvent\>) 699 700Triggered to notify the host application that the page has been loaded. This method is called only when the main frame loading is complete. For fragment navigations (navigations to **#fragment_id**), **onLoadFinished** is also triggered. 701 702**System capability**: SystemCapability.Web.Webview.Core 703 704**Parameters** 705 706| Name | Type | Mandatory | Description | 707| ---- | ------ | ---- | --------- | 708| callback | Callback\<[OnLoadFinishedEvent](./arkts-basic-components-web-i.md#onloadfinishedevent20)\> | Yes | Callback triggered when the web page loading is complete.| 709 710**Example** 711 712 ```ts 713 // xxx.ets 714 import { webview } from '@kit.ArkWeb'; 715 716 @Entry 717 @Component 718 struct WebComponent { 719 controller: webview.WebviewController = new webview.WebviewController(); 720 721 build() { 722 Column() { 723 Web({ src: 'www.example.com', controller: this.controller }) 724 .onLoadFinished((event) => { 725 if (event) { 726 console.log('url:' + event.url); 727 } 728 }) 729 } 730 } 731 } 732 ``` 733 734## onProgressChange 735 736onProgressChange(callback: Callback\<OnProgressChangeEvent\>) 737 738Triggered when the web page loading progress changes. 739 740**System capability**: SystemCapability.Web.Webview.Core 741 742**Parameters** 743 744| Name | Type | Mandatory | Description | 745| ----------- | ------ | ---- | --------------------- | 746| callback | Callback\<[OnProgressChangeEvent](./arkts-basic-components-web-i.md#onprogresschangeevent12)\> | Yes | Callback triggered when the page loading progress changes.| 747 748**Example** 749 750 ```ts 751 // xxx.ets 752 import { webview } from '@kit.ArkWeb'; 753 @Entry 754 @Component 755 struct WebComponent { 756 controller: webview.WebviewController = new webview.WebviewController(); 757 758 build() { 759 Column() { 760 Web({ src: 'www.example.com', controller: this.controller }) 761 .onProgressChange((event) => { 762 if (event) { 763 console.log('newProgress:' + event.newProgress); 764 } 765 }) 766 } 767 } 768 } 769 ``` 770 771## onTitleReceive 772 773onTitleReceive(callback: Callback\<OnTitleReceiveEvent\>) 774 775Triggered to notify the application that the document title of the page is changed. If the **<title\>** element is not set on the page to load, ArkWeb generates a title based on the URL and returns the title to the application. 776 777**System capability**: SystemCapability.Web.Webview.Core 778 779**Parameters** 780 781| Name | Type | Mandatory | Description | 782| ----- | ------ | ---- | ------------- | 783| callback | Callback\<[OnTitleReceiveEvent](./arkts-basic-components-web-i.md#ontitlereceiveevent12)\> | Yes | Callback triggered when the document title of the application page is changed.| 784 785**Example** 786 787 ```ts 788 // xxx.ets 789 import { webview } from '@kit.ArkWeb'; 790 791 @Entry 792 @Component 793 struct WebComponent { 794 controller: webview.WebviewController = new webview.WebviewController(); 795 796 build() { 797 Column() { 798 Web({ src: 'www.example.com', controller: this.controller }) 799 .onTitleReceive((event) => { 800 if (event) { 801 console.log('title:' + event.title); 802 console.log('isRealTitle:' + event.isRealTitle); 803 } 804 }) 805 } 806 } 807 } 808 ``` 809 810## onRefreshAccessedHistory 811 812onRefreshAccessedHistory(callback: Callback\<OnRefreshAccessedHistoryEvent\>) 813 814Triggered for the application to update its access history when the web page loading is complete. 815 816**System capability**: SystemCapability.Web.Webview.Core 817 818**Parameters** 819 820| Name | Type | Mandatory | Description | 821| ----------- | ------- | ---- | ---------------------------------------- | 822| callback | Callback\<[OnRefreshAccessedHistoryEvent](./arkts-basic-components-web-i.md#onrefreshaccessedhistoryevent12)\> | Yes | Callback triggered when the access history of the web page is refreshed. | 823 824**Example** 825 826 ```ts 827 // xxx.ets 828 import { webview } from '@kit.ArkWeb'; 829 830 @Entry 831 @Component 832 struct WebComponent { 833 controller: webview.WebviewController = new webview.WebviewController(); 834 835 build() { 836 Column() { 837 Web({ src: 'www.example.com', controller: this.controller }) 838 .onRefreshAccessedHistory((event) => { 839 if (event) { 840 console.log('url:' + event.url + ' isReload:' + event.isRefreshed); 841 } 842 }) 843 } 844 } 845 } 846 ``` 847 848## onRenderExited<sup>9+</sup> 849 850onRenderExited(callback: Callback\<OnRenderExitedEvent\>) 851 852Triggered when the rendering process exits abnormally. 853 854A rendering process may be shared by multiple **Web** components. Each affected **Web** component triggers this callback. 855 856You can call the bound **webviewController** APIs to restore the web page when this callback is triggered. For example, [refresh](./arkts-apis-webview-WebviewController.md#refresh) and [loadUrl](./arkts-apis-webview-WebviewController.md#loadurl). 857 858For details about the component lifecycle, see [Lifecycle of the Web Components](../../web/web-event-sequence.md). 859 860**System capability**: SystemCapability.Web.Webview.Core 861 862**Parameters** 863 864| Name | Type | Mandatory | Description | 865| ---------------- | ---------------------------------------- | ---- | ---------------- | 866| callback | Callback\<[OnRenderExitedEvent](./arkts-basic-components-web-i.md#onrenderexitedevent12)\> | Yes | Callback triggered when the rendering process exits abnormally.| 867 868**Example** 869 870 ```ts 871 // xxx.ets 872 import { webview } from '@kit.ArkWeb'; 873 874 @Entry 875 @Component 876 struct WebComponent { 877 controller: webview.WebviewController = new webview.WebviewController(); 878 879 build() { 880 Column() { 881 Web({ src: 'chrome://crash/', controller: this.controller }) 882 .onRenderExited((event) => { 883 if (event) { 884 console.log('reason:' + event.renderExitReason); 885 } 886 }) 887 } 888 } 889 } 890 ``` 891## onRenderProcessNotResponding<sup>12+</sup> 892 893onRenderProcessNotResponding(callback: OnRenderProcessNotRespondingCallback) 894 895Triggered when the rendering process does not respond. If the **Web** component cannot process the input event or navigate to a new URL within a proper time range, the web page process is considered unresponsive and the callback is triggered. 896 897If the web page process does not respond, this callback may be triggered until the web page process responds again. In this case, [onRenderProcessResponding](#onrenderprocessresponding12) is triggered. 898 899You can terminate the associated rendering process through [terminateRenderProcess](./arkts-apis-webview-WebviewController.md#terminaterenderprocess12), which may affect other **Web** components in the same rendering process. 900 901**System capability**: SystemCapability.Web.Webview.Core 902 903**Parameters** 904 905| Name | Type | Mandatory | Description | 906| -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | 907| callback | [OnRenderProcessNotRespondingCallback](./arkts-basic-components-web-t.md#onrenderprocessnotrespondingcallback12) | Yes | Callback triggered when the rendering process does not respond.| 908 909**Example** 910 911 ```ts 912 // xxx.ets 913 import { webview } from '@kit.ArkWeb'; 914 915 @Entry 916 @Component 917 struct WebComponent { 918 controller: webview.WebviewController = new webview.WebviewController(); 919 920 build() { 921 Column() { 922 Web({ src: 'www.example.com', controller: this.controller }) 923 .onRenderProcessNotResponding((data) => { 924 console.log("onRenderProcessNotResponding: [jsStack]= " + data.jsStack + 925 ", [process]=" + data.pid + ", [reason]=" + data.reason); 926 }) 927 } 928 } 929 } 930 ``` 931 932## onRenderProcessResponding<sup>12+</sup> 933 934onRenderProcessResponding(callback: OnRenderProcessRespondingCallback) 935 936Triggered when the rendering process transitions back to a normal operating state from an unresponsive state. This callback indicates that the web page was not actually frozen. 937 938**System capability**: SystemCapability.Web.Webview.Core 939 940**Parameters** 941 942| Name | Type | Mandatory | Description | 943| -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | 944| callback | [OnRenderProcessRespondingCallback](./arkts-basic-components-web-t.md#onrenderprocessrespondingcallback12) | Yes | Callback triggered when the rendering process transitions back to a normal operating state from an unresponsive state.| 945 946**Example** 947 948 ```ts 949 // xxx.ets 950 import { webview } from '@kit.ArkWeb'; 951 952 @Entry 953 @Component 954 struct WebComponent { 955 controller: webview.WebviewController = new webview.WebviewController(); 956 957 build() { 958 Column() { 959 Web({ src: 'www.example.com', controller: this.controller }) 960 .onRenderProcessResponding(() => { 961 console.log("onRenderProcessResponding again"); 962 }) 963 } 964 } 965 } 966 ``` 967 968## onShowFileSelector<sup>9+</sup> 969 970onShowFileSelector(callback: Callback\<OnShowFileSelectorEvent, boolean\>) 971 972Triggered to process an HTML form whose input type is **file**. If this function is not called or returns **false**, the **Web** component provides the default **Select file** UI. If it returns **true**, the application can customize the response behavior for **Select file**. 973 974**System capability**: SystemCapability.Web.Webview.Core 975 976**Parameters** 977 978| Name | Type | Mandatory | Description | 979| ------------ | ---------------------------------------- | ---- | ----------------- | 980| callback | Callback\<[OnShowFileSelectorEvent](./arkts-basic-components-web-i.md#onshowfileselectorevent12), boolean\> | Yes | Callback triggered to notify the **Web** component of the file selection result.<br>Return value: boolean<br> The value **true** means that you can invoke the system-provided dialog box. The value **false** means that the custom dialog box drawn in the function is ineffective.| 981 982**Example** 983 9841. Start the file selector. 985 986 ```ts 987 // xxx.ets 988 import { webview } from '@kit.ArkWeb'; 989 import { picker } from '@kit.CoreFileKit'; 990 import { BusinessError } from '@kit.BasicServicesKit'; 991 992 @Entry 993 @Component 994 struct WebComponent { 995 controller: webview.WebviewController = new webview.WebviewController() 996 997 build() { 998 Column() { 999 Web({ src: $rawfile('index.html'), controller: this.controller }) 1000 .onShowFileSelector((event) => { 1001 console.log('MyFileUploader onShowFileSelector invoked') 1002 const documentSelectOptions = new picker.DocumentSelectOptions(); 1003 let uri: string | null = null; 1004 const documentViewPicker = new picker.DocumentViewPicker(); 1005 documentViewPicker.select(documentSelectOptions).then((documentSelectResult) => { 1006 uri = documentSelectResult[0]; 1007 console.info('documentViewPicker.select to file succeed and uri is:' + uri); 1008 if (event) { 1009 event.result.handleFileList([uri]); 1010 } 1011 }).catch((err: BusinessError) => { 1012 console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`); 1013 }) 1014 return true; 1015 }) 1016 } 1017 } 1018 } 1019 ``` 1020 10212. Start the photo selector. 1022 1023 ```ts 1024 // xxx.ets 1025 import { webview } from '@kit.ArkWeb'; 1026 import { picker } from '@kit.CoreFileKit'; 1027 import { photoAccessHelper } from '@kit.MediaLibraryKit'; 1028 1029 @Entry 1030 @Component 1031 struct WebComponent { 1032 controller: webview.WebviewController = new webview.WebviewController() 1033 1034 async selectFile(result: FileSelectorResult): Promise<void> { 1035 let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions(); 1036 let photoPicker = new photoAccessHelper.PhotoViewPicker(); 1037 // Set the mime file type to IMAGE_VIDEO. 1038 photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE; 1039 // Set the maximum number of media files that can be selected. 1040 photoSelectOptions.maxSelectNumber = 5; 1041 let chooseFile: photoAccessHelper.PhotoSelectResult = await photoPicker.select(photoSelectOptions); 1042 // Obtain the list of selected files. 1043 result.handleFileList(chooseFile.photoUris); 1044 } 1045 1046 build() { 1047 Column() { 1048 Web({ src: $rawfile('index.html'), controller: this.controller }) 1049 .onShowFileSelector((event) => { 1050 if (event) { 1051 this.selectFile(event.result); 1052 } 1053 return true; 1054 }) 1055 } 1056 } 1057 } 1058 ``` 1059 10603. Start the camera picker. 1061 1062 ```ts 1063 // xxx.ets 1064 import { webview } from '@kit.ArkWeb'; 1065 import { cameraPicker, camera } from '@kit.CameraKit'; 1066 import { BusinessError } from '@kit.BasicServicesKit'; 1067 import { common } from '@kit.AbilityKit'; 1068 1069 async function openCamera(callback: Callback<string>, uiContext: UIContext) { 1070 let mContext = uiContext.getHostContext() as common.Context; 1071 try { 1072 let pickerProfile: cameraPicker.PickerProfile = { 1073 cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK 1074 }; 1075 let pickerResult: cameraPicker.PickerResult = await cameraPicker.pick(mContext, 1076 [cameraPicker.PickerMediaType.PHOTO, cameraPicker.PickerMediaType.VIDEO], pickerProfile); 1077 callback(pickerResult.resultUri); 1078 } catch (error) { 1079 let err = error as BusinessError; 1080 console.error(`the pick call failed. error code: ${err.code}`); 1081 } 1082 } 1083 1084 @Entry 1085 @Component 1086 struct WebComponent { 1087 controller: webview.WebviewController = new webview.WebviewController(); 1088 1089 build() { 1090 Column() { 1091 Web({ src: $rawfile('index.html'), controller: this.controller }) 1092 .onShowFileSelector((event) => { 1093 openCamera((result) => { 1094 if (event) { 1095 console.log('Title is ' + event.fileSelector.getTitle()); 1096 console.log('Mode is ' + event.fileSelector.getMode()); 1097 console.log('Accept types are ' + event.fileSelector.getAcceptType()); 1098 console.log('Capture is ' + event.fileSelector.isCapture()); 1099 console.log('Mime types are ' + event.fileSelector.getMimeTypes()); 1100 event.result.handleFileList([result]); 1101 } 1102 }, this.getUIContext()) 1103 return true; 1104 }) 1105 } 1106 } 1107 } 1108 ``` 1109 1110 HTML file to be loaded: 1111 ```html 1112 <!DOCTYPE html> 1113 <html> 1114 <head> 1115 <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8"> 1116 </head> 1117 <body> 1118 <form id="upload-form" enctype="multipart/form-data"> 1119 <input type="file" id="upload" name="upload" accept="image/*, video/*"/> 1120 </form> 1121 </body> 1122 </html> 1123 ``` 1124 1125## onResourceLoad<sup>9+</sup> 1126 1127onResourceLoad(callback: Callback\<OnResourceLoadEvent\>) 1128 1129Triggered to notify the **Web** component of the URL of the resource file to load. 1130 1131**System capability**: SystemCapability.Web.Webview.Core 1132 1133**Parameters** 1134 1135| Name | Type | Mandatory | Description | 1136| ------ | ------ | ---- | --------------------- | 1137| callback | Callback\<[OnResourceLoadEvent](./arkts-basic-components-web-i.md#onresourceloadevent12)\> | Yes| Callback triggered when a URL is loaded.| 1138 1139**Example** 1140 1141 ```ts 1142 // xxx.ets 1143 import { webview } from '@kit.ArkWeb'; 1144 1145 @Entry 1146 @Component 1147 struct WebComponent { 1148 controller: webview.WebviewController = new webview.WebviewController(); 1149 1150 build() { 1151 Column() { 1152 Web({ src: 'www.example.com', controller: this.controller }) 1153 .onResourceLoad((event) => { 1154 console.log('onResourceLoad: ' + event.url); 1155 }) 1156 } 1157 } 1158 } 1159 ``` 1160 1161## onScaleChange<sup>9+</sup> 1162 1163onScaleChange(callback: Callback\<OnScaleChangeEvent\>) 1164 1165Triggered when the display scale of this page changes. 1166 1167**System capability**: SystemCapability.Web.Webview.Core 1168 1169**Parameters** 1170 1171| Name | Type | Mandatory | Description | 1172| ------ | ------ | ---- | --------------------- | 1173| callback | Callback\<[OnScaleChangeEvent](./arkts-basic-components-web-i.md#onscalechangeevent12)\> | Yes| Callback invoked when the display scale of the page changes.| 1174 1175**Example** 1176 1177 ```ts 1178 // xxx.ets 1179 import { webview } from '@kit.ArkWeb'; 1180 1181 @Entry 1182 @Component 1183 struct WebComponent { 1184 controller: webview.WebviewController = new webview.WebviewController(); 1185 1186 build() { 1187 Column() { 1188 Web({ src: 'www.example.com', controller: this.controller }) 1189 .onScaleChange((event) => { 1190 console.log('onScaleChange changed from ' + event.oldScale + ' to ' + event.newScale); 1191 }) 1192 } 1193 } 1194 } 1195 ``` 1196 1197## onInterceptRequest<sup>9+</sup> 1198 1199onInterceptRequest(callback: Callback<OnInterceptRequestEvent, WebResourceResponse>) 1200 1201Triggered when the **Web** component is about to access a URL. This API is used to block the URL and return the response data. This API can intercept all URLs, which needs to be determined based on specific services. 1202 1203**System capability**: SystemCapability.Web.Webview.Core 1204 1205**Parameters** 1206 1207| Name | Type | Mandatory | Description | 1208| ------ | ------ | ---- | --------------------- | 1209| callback | Callback\<[OnInterceptRequestEvent](./arkts-basic-components-web-i.md#oninterceptrequestevent12), [WebResourceResponse](./arkts-basic-components-web-WebResourceResponse.md)\> | Yes| Callback invoked when the **Web** component is about to load a URL.<br>The return value is [WebResourceResponse](./arkts-basic-components-web-WebResourceResponse.md). If response data is returned, the data is loaded based on the response data. If no response data is returned, null is returned, indicating that the data is loaded in the original mode.| 1210 1211**Example** 1212 1213 ```ts 1214 // xxx.ets 1215 import { webview } from '@kit.ArkWeb'; 1216 1217 @Entry 1218 @Component 1219 struct WebComponent { 1220 controller: webview.WebviewController = new webview.WebviewController(); 1221 responseWeb: WebResourceResponse = new WebResourceResponse(); 1222 heads: Header[] = new Array(); 1223 webData: string = "<!DOCTYPE html>\n" + 1224 "<html>\n" + 1225 "<head>\n" + 1226 "<title>intercept test</title>\n" + 1227 "</head>\n" + 1228 "<body>\n" + 1229 "<h1>intercept test</h1>\n" + 1230 "</body>\n" + 1231 "</html>"; 1232 1233 build() { 1234 Column() { 1235 Web({ src: 'www.example.com', controller: this.controller }) 1236 .onInterceptRequest((event) => { 1237 if (event) { 1238 console.log('url:' + event.request.getRequestUrl()); 1239 } 1240 let head1: Header = { 1241 headerKey: "Connection", 1242 headerValue: "keep-alive" 1243 } 1244 let head2: Header = { 1245 headerKey: "Cache-Control", 1246 headerValue: "no-cache" 1247 } 1248 // Add a new element to the end of the array and return the length of the new array. 1249 let length = this.heads.push(head1); 1250 length = this.heads.push(head2); 1251 console.log('The response header result length is :' + length); 1252 const promise: Promise<String> = new Promise((resolve: Function, reject: Function) => { 1253 this.responseWeb.setResponseHeader(this.heads); 1254 this.responseWeb.setResponseData(this.webData); 1255 this.responseWeb.setResponseEncoding('utf-8'); 1256 this.responseWeb.setResponseMimeType('text/html'); 1257 this.responseWeb.setResponseCode(200); 1258 this.responseWeb.setReasonMessage('OK'); 1259 resolve("success"); 1260 }) 1261 promise.then(() => { 1262 console.log("prepare response ready"); 1263 this.responseWeb.setResponseIsReady(true); 1264 }) 1265 this.responseWeb.setResponseIsReady(false); 1266 return this.responseWeb; 1267 }) 1268 } 1269 } 1270 } 1271 ``` 1272 1273## onHttpAuthRequest<sup>9+</sup> 1274 1275onHttpAuthRequest(callback: Callback\<OnHttpAuthRequestEvent, boolean\>) 1276 1277Triggered when an HTTP authentication request is received. 1278 1279**System capability**: SystemCapability.Web.Webview.Core 1280 1281**Parameters** 1282 1283| Name | Type | Mandatory | Description | 1284| ------ | ------ | ---- | --------------------- | 1285| callback | Callback\<[OnHttpAuthRequestEvent](./arkts-basic-components-web-i.md#onhttpauthrequestevent12), boolean\> | Yes| Callback invoked when the browser requires user credentials.<br>Return value: boolean<br> The value **true** means that the HTTP authentication is successful, and **false** means the opposite. | 1286 1287**Example** 1288 1289 ```ts 1290 // xxx.ets 1291 import { webview } from '@kit.ArkWeb'; 1292 1293 @Entry 1294 @Component 1295 struct WebComponent { 1296 controller: webview.WebviewController = new webview.WebviewController(); 1297 uiContext: UIContext = this.getUIContext(); 1298 httpAuth: boolean = false; 1299 1300 build() { 1301 Column() { 1302 Web({ src: 'www.example.com', controller: this.controller }) 1303 .onHttpAuthRequest((event) => { 1304 if (event) { 1305 this.uiContext.showAlertDialog({ 1306 title: 'onHttpAuthRequest', 1307 message: 'text', 1308 primaryButton: { 1309 value: 'cancel', 1310 action: () => { 1311 event.handler.cancel(); 1312 } 1313 }, 1314 secondaryButton: { 1315 value: 'ok', 1316 action: () => { 1317 this.httpAuth = event.handler.isHttpAuthInfoSaved(); 1318 if (this.httpAuth == false) { 1319 webview.WebDataBase.saveHttpAuthCredentials( 1320 event.host, 1321 event.realm, 1322 "2222", 1323 "2222" 1324 ) 1325 event.handler.cancel(); 1326 } 1327 } 1328 }, 1329 cancel: () => { 1330 event.handler.cancel(); 1331 } 1332 }) 1333 } 1334 return true; 1335 }) 1336 } 1337 } 1338 } 1339 ``` 1340## onSslErrorEventReceive<sup>9+</sup> 1341 1342onSslErrorEventReceive(callback: Callback\<OnSslErrorEventReceiveEvent\>) 1343 1344Triggered to notify the host application when an SSL error occurs while loading the main-frame resource. 1345To support errors for loading subframe resources, use the [OnSslErrorEvent](./arkts-basic-components-web-events.md#onsslerrorevent12) API. 1346 1347**System capability**: SystemCapability.Web.Webview.Core 1348 1349**Parameters** 1350 1351| Name | Type | Mandatory | Description | 1352| ------ | ------ | ---- | --------------------- | 1353| callback | Callback\<[OnSslErrorEventReceiveEvent](./arkts-basic-components-web-i.md#onsslerroreventreceiveevent12)\> | Yes| Callback invoked when the web page receives an SSL error.| 1354 1355**Example** 1356 1357 ```ts 1358 // xxx.ets 1359 import { webview } from '@kit.ArkWeb'; 1360 import { cert } from '@kit.DeviceCertificateKit'; 1361 1362 function LogCertInfo(certChainData : Array<Uint8Array> | undefined) { 1363 if (!(certChainData instanceof Array)) { 1364 console.log('failed, cert chain data type is not array'); 1365 return; 1366 } 1367 1368 for (let i = 0; i < certChainData.length; i++) { 1369 let encodeBlobData: cert.EncodingBlob = { 1370 data: certChainData[i], 1371 encodingFormat: cert.EncodingFormat.FORMAT_DER 1372 } 1373 cert.createX509Cert(encodeBlobData, (error, x509Cert) => { 1374 if (error) { 1375 console.error('Index : ' + i + ',createX509Cert failed, errCode: ' + error.code + ', errMsg: ' + error.message); 1376 } else { 1377 console.log('createX509Cert success'); 1378 console.log(ParseX509CertInfo(x509Cert)); 1379 } 1380 }); 1381 } 1382 return; 1383 } 1384 1385 function Uint8ArrayToString(dataArray: Uint8Array) { 1386 let dataString = ''; 1387 for (let i = 0; i < dataArray.length; i++) { 1388 dataString += String.fromCharCode(dataArray[i]); 1389 } 1390 return dataString; 1391 } 1392 1393 function ParseX509CertInfo(x509Cert: cert.X509Cert) { 1394 let res: string = 'getCertificate success, ' 1395 + 'issuer name = ' 1396 + Uint8ArrayToString(x509Cert.getIssuerName().data) + ', subject name = ' 1397 + Uint8ArrayToString(x509Cert.getSubjectName().data) + ', valid start = ' 1398 + x509Cert.getNotBeforeTime() 1399 + ', valid end = ' + x509Cert.getNotAfterTime(); 1400 return res; 1401 } 1402 1403 @Entry 1404 @Component 1405 struct WebComponent { 1406 controller: webview.WebviewController = new webview.WebviewController(); 1407 uiContext: UIContext = this.getUIContext(); 1408 1409 build() { 1410 Column() { 1411 Web({ src: 'www.example.com', controller: this.controller }) 1412 .onSslErrorEventReceive((event) => { 1413 LogCertInfo(event.certChainData); 1414 this.uiContext.showAlertDialog({ 1415 title: 'onSslErrorEventReceive', 1416 message: 'text', 1417 primaryButton: { 1418 value: 'confirm', 1419 action: () => { 1420 event.handler.handleConfirm(); 1421 } 1422 }, 1423 secondaryButton: { 1424 value: 'cancel', 1425 action: () => { 1426 event.handler.handleCancel(); 1427 } 1428 }, 1429 cancel: () => { 1430 event.handler.handleCancel(); 1431 } 1432 }) 1433 }) 1434 } 1435 } 1436 } 1437 ``` 1438 1439## onSslErrorEvent<sup>12+</sup> 1440 1441onSslErrorEvent(callback: OnSslErrorEventCallback) 1442 1443Triggered to notify users when an SSL error occurs during the loading of main-frame or subframe resources. To handle SSL errors for loading the main-frame resources, use the [isMainFrame](./arkts-basic-components-web-WebResourceRequest.md#ismainframe) field to distinguish. 1444 1445**System capability**: SystemCapability.Web.Webview.Core 1446 1447**Parameters** 1448 1449| Name | Type | Mandatory | Description | 1450| ------ | ------ | ---- | --------------------- | 1451| callback | [OnSslErrorEventCallback](./arkts-basic-components-web-t.md#onsslerroreventcallback12) | Yes| Callback invoked when an SSL error occurs during resource loading.| 1452 1453**Example** 1454 1455 ```ts 1456 // xxx.ets 1457 import { webview } from '@kit.ArkWeb'; 1458 import { cert } from '@kit.DeviceCertificateKit'; 1459 1460 function LogCertInfo(certChainData : Array<Uint8Array> | undefined) { 1461 if (!(certChainData instanceof Array)) { 1462 console.log('failed, cert chain data type is not array'); 1463 return; 1464 } 1465 1466 for (let i = 0; i < certChainData.length; i++) { 1467 let encodeBlobData: cert.EncodingBlob = { 1468 data: certChainData[i], 1469 encodingFormat: cert.EncodingFormat.FORMAT_DER 1470 } 1471 cert.createX509Cert(encodeBlobData, (error, x509Cert) => { 1472 if (error) { 1473 console.error('Index : ' + i + ',createX509Cert failed, errCode: ' + error.code + ', errMsg: ' + error.message); 1474 } else { 1475 console.log('createX509Cert success'); 1476 console.log(ParseX509CertInfo(x509Cert)); 1477 } 1478 }); 1479 } 1480 return; 1481 } 1482 1483 function Uint8ArrayToString(dataArray: Uint8Array) { 1484 let dataString = ''; 1485 for (let i = 0; i < dataArray.length; i++) { 1486 dataString += String.fromCharCode(dataArray[i]); 1487 } 1488 return dataString; 1489 } 1490 1491 function ParseX509CertInfo(x509Cert: cert.X509Cert) { 1492 let res: string = 'getCertificate success, ' 1493 + 'issuer name = ' 1494 + Uint8ArrayToString(x509Cert.getIssuerName().data) + ', subject name = ' 1495 + Uint8ArrayToString(x509Cert.getSubjectName().data) + ', valid start = ' 1496 + x509Cert.getNotBeforeTime() 1497 + ', valid end = ' + x509Cert.getNotAfterTime(); 1498 return res; 1499 } 1500 1501 @Entry 1502 @Component 1503 struct WebComponent { 1504 controller: webview.WebviewController = new webview.WebviewController(); 1505 uiContext: UIContext = this.getUIContext(); 1506 1507 build() { 1508 Column() { 1509 Web({ src: 'www.example.com', controller: this.controller }) 1510 .onSslErrorEvent((event: SslErrorEvent) => { 1511 console.log("onSslErrorEvent url: " + event.url); 1512 console.log("onSslErrorEvent error: " + event.error); 1513 console.log("onSslErrorEvent originalUrl: " + event.originalUrl); 1514 console.log("onSslErrorEvent referrer: " + event.referrer); 1515 console.log("onSslErrorEvent isFatalError: " + event.isFatalError); 1516 console.log("onSslErrorEvent isMainFrame: " + event.isMainFrame); 1517 LogCertInfo(event.certChainData); 1518 this.uiContext.showAlertDialog({ 1519 title: 'onSslErrorEvent', 1520 message: 'text', 1521 primaryButton: { 1522 value: 'confirm', 1523 action: () => { 1524 event.handler.handleConfirm(); 1525 } 1526 }, 1527 secondaryButton: { 1528 value: 'cancel', 1529 action: () => { 1530 // The value true indicates that the page loading is stopped and the current page is displayed. The value false indicates that the page loading is continued and an error page is displayed. 1531 event.handler.handleCancel(true); 1532 } 1533 }, 1534 cancel: () => { 1535 event.handler.handleCancel(); 1536 } 1537 }) 1538 }) 1539 } 1540 } 1541 } 1542 ``` 1543 1544## onClientAuthenticationRequest<sup>9+</sup> 1545 1546onClientAuthenticationRequest(callback: Callback\<OnClientAuthenticationEvent\>) 1547 1548Triggered when an SSL client certificate request is received. 1549 1550**System capability**: SystemCapability.Web.Webview.Core 1551 1552**Parameters** 1553 1554| Name | Type | Mandatory | Description | 1555| ------ | ------ | ---- | --------------------- | 1556| callback | Callback\<[OnClientAuthenticationEvent](./arkts-basic-components-web-i.md#onclientauthenticationevent12)\> | Yes| Callback invoked when an SSL client certificate is required. | 1557 1558 **Example** 1559 1560 This example shows two-way authentication when interconnection with certificate management is not supported. 1561 1562 ```ts 1563 // xxx.ets API9 1564 import { webview } from '@kit.ArkWeb'; 1565 1566 @Entry 1567 @Component 1568 struct WebComponent { 1569 controller: webview.WebviewController = new webview.WebviewController(); 1570 uiContext: UIContext = this.getUIContext(); 1571 1572 build() { 1573 Column() { 1574 Web({ src: 'www.example.com', controller: this.controller }) 1575 .onClientAuthenticationRequest((event) => { 1576 this.uiContext.showAlertDialog({ 1577 title: 'onClientAuthenticationRequest', 1578 message: 'text', 1579 primaryButton: { 1580 value: 'confirm', 1581 action: () => { 1582 event.handler.confirm("/system/etc/user.pk8", "/system/etc/chain-user.pem"); 1583 } 1584 }, 1585 secondaryButton: { 1586 value: 'cancel', 1587 action: () => { 1588 event.handler.cancel(); 1589 } 1590 }, 1591 cancel: () => { 1592 event.handler.ignore(); 1593 } 1594 }) 1595 }) 1596 } 1597 } 1598 } 1599 ``` 1600 1601 This example shows two-way authentication when interconnection with certificate management is supported. 1602 1603 1. Construct a singleton object **GlobalContext**. 1604 1605 ```ts 1606 // GlobalContext.ets 1607 export class GlobalContext { 1608 private constructor() {} 1609 private static instance: GlobalContext; 1610 private _objects = new Map<string, Object>(); 1611 1612 public static getContext(): GlobalContext { 1613 if (!GlobalContext.instance) { 1614 GlobalContext.instance = new GlobalContext(); 1615 } 1616 return GlobalContext.instance; 1617 } 1618 1619 getObject(value: string): Object | undefined { 1620 return this._objects.get(value); 1621 } 1622 1623 setObject(key: string, objectClass: Object): void { 1624 this._objects.set(key, objectClass); 1625 } 1626 } 1627 ``` 1628 1629 1630 2. Implement two-way authentication. 1631 1632 ```ts 1633 // xxx.ets API10 1634 import { webview } from '@kit.ArkWeb'; 1635 import { common, Want, bundleManager } from '@kit.AbilityKit'; 1636 import { BusinessError } from '@kit.BasicServicesKit'; 1637 import { GlobalContext } from '../GlobalContext'; 1638 1639 let uri = ""; 1640 1641 export default class CertManagerService { 1642 private static sInstance: CertManagerService; 1643 private authUri = ""; 1644 private appUid = ""; 1645 1646 public static getInstance(): CertManagerService { 1647 if (CertManagerService.sInstance == null) { 1648 CertManagerService.sInstance = new CertManagerService(); 1649 } 1650 return CertManagerService.sInstance; 1651 } 1652 1653 async grantAppPm(callback: (message: string) => void) { 1654 let message = ''; 1655 let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION; 1656 // Note: Replace com.example.myapplication with the actual application name. 1657 try { 1658 bundleManager.getBundleInfoForSelf(bundleFlags).then((data) => { 1659 console.info('getBundleInfoForSelf successfully. Data: %{public}s', JSON.stringify(data)); 1660 this.appUid = data.appInfo.uid.toString(); 1661 }).catch((err: BusinessError) => { 1662 console.error('getBundleInfoForSelf failed. Cause: %{public}s', err.message); 1663 }); 1664 } catch (err) { 1665 let message = (err as BusinessError).message; 1666 console.error('getBundleInfoForSelf failed: %{public}s', message); 1667 } 1668 1669 // Note: Add GlobalContext.getContext().setObject("AbilityContext", this.context) to the onCreate function in the MainAbility.ts file. 1670 let abilityContext = GlobalContext.getContext().getObject("AbilityContext") as common.UIAbilityContext 1671 await abilityContext.startAbilityForResult( 1672 { 1673 bundleName: "com.ohos.certmanager", 1674 abilityName: "MainAbility", 1675 uri: "requestAuthorize", 1676 parameters: { 1677 appUid: this.appUid, // Pass the UID of the requesting application. 1678 } 1679 } as Want) 1680 .then((data: common.AbilityResult) => { 1681 if (!data.resultCode && data.want) { 1682 if (data.want.parameters) { 1683 this.authUri = data.want.parameters.authUri as string; // Obtain the returned authUri after successful authorization. 1684 } 1685 } 1686 }) 1687 message += "after grantAppPm authUri: " + this.authUri; 1688 uri = this.authUri; 1689 callback(message) 1690 } 1691 } 1692 1693 @Entry 1694 @Component 1695 struct WebComponent { 1696 controller: webview.WebviewController = new webview.WebviewController(); 1697 @State message: string = 'Hello World' // message is used for debugging and observation. 1698 certManager = CertManagerService.getInstance(); 1699 uiContext: UIContext = this.getUIContext(); 1700 1701 build() { 1702 Row() { 1703 Column() { 1704 Row() { 1705 // Step 1: Perform authorization to obtain the URI. 1706 Button('GrantApp') 1707 .onClick(() => { 1708 this.certManager.grantAppPm((data) => { 1709 this.message = data; 1710 }); 1711 }) 1712 // Step 2: After the authorization, in two-way authentication, the onClientAuthenticationRequest callback is used to send the URI to the web server for authentication. 1713 Button("ClientCertAuth") 1714 .onClick(() => { 1715 this.controller.loadUrl('https://www.example2.com'); // Server website that supports two-way authentication. 1716 }) 1717 } 1718 1719 Web({ src: 'https://www.example1.com', controller: this.controller }) 1720 .fileAccess(true) 1721 .javaScriptAccess(true) 1722 .domStorageAccess(true) 1723 .onlineImageAccess(true) 1724 1725 .onClientAuthenticationRequest((event) => { 1726 this.uiContext.showAlertDialog({ 1727 title: 'ClientAuth', 1728 message: 'Text', 1729 confirm: { 1730 value: 'Confirm', 1731 action: () => { 1732 event.handler.confirm(uri); 1733 } 1734 }, 1735 cancel: () => { 1736 event.handler.cancel(); 1737 } 1738 }) 1739 }) 1740 } 1741 } 1742 .width('100%') 1743 .height('100%') 1744 } 1745 } 1746 ``` 1747 1748## onPermissionRequest<sup>9+</sup> 1749 1750onPermissionRequest(callback: Callback\<OnPermissionRequestEvent\>) 1751 1752Triggered when a permission request is received. To call this API, you need to declare the **ohos.permission.CAMERA** and **ohos.permission.MICROPHONE** permissions. 1753 1754**System capability**: SystemCapability.Web.Webview.Core 1755 1756**Parameters** 1757 1758| Name | Type | Mandatory | Description | 1759| ------ | ------ | ---- | --------------------- | 1760| callback | Callback\<[OnPermissionRequestEvent](./arkts-basic-components-web-i.md#onpermissionrequestevent12)\> | Yes| Callback invoked when a permission request is received.| 1761 1762**Example** 1763 1764 ```ts 1765 // xxx.ets 1766 import { webview } from '@kit.ArkWeb'; 1767 import { BusinessError } from '@kit.BasicServicesKit'; 1768 import { abilityAccessCtrl } from '@kit.AbilityKit'; 1769 1770 @Entry 1771 @Component 1772 struct WebComponent { 1773 controller: webview.WebviewController = new webview.WebviewController(); 1774 uiContext: UIContext = this.getUIContext(); 1775 1776 aboutToAppear() { 1777 // Enable web frontend page debugging. 1778 webview.WebviewController.setWebDebuggingAccess(true); 1779 let atManager = abilityAccessCtrl.createAtManager(); 1780 atManager.requestPermissionsFromUser(this.uiContext.getHostContext(), ['ohos.permission.CAMERA', 'ohos.permission.MICROPHONE']) 1781 .then((data) => { 1782 console.info('data:' + JSON.stringify(data)); 1783 console.info('data permissions:' + data.permissions); 1784 console.info('data authResults:' + data.authResults); 1785 }).catch((error: BusinessError) => { 1786 console.error(`Failed to request permissions from user. Code is ${error.code}, message is ${error.message}`); 1787 }) 1788 } 1789 1790 build() { 1791 Column() { 1792 Web({ src: $rawfile('index.html'), controller: this.controller }) 1793 .onPermissionRequest((event) => { 1794 if (event) { 1795 this.uiContext.showAlertDialog({ 1796 title: 'title', 1797 message: 'text', 1798 primaryButton: { 1799 value: 'deny', 1800 action: () => { 1801 event.request.deny(); 1802 } 1803 }, 1804 secondaryButton: { 1805 value: 'onConfirm', 1806 action: () => { 1807 event.request.grant(event.request.getAccessibleResource()); 1808 } 1809 }, 1810 cancel: () => { 1811 event.request.deny(); 1812 } 1813 }) 1814 } 1815 }) 1816 } 1817 } 1818 } 1819 ``` 1820 1821 HTML file to be loaded: 1822 ```html 1823 <!-- index.html --> 1824 <!DOCTYPE html> 1825 <html> 1826 <head> 1827 <meta charset="UTF-8"> 1828 </head> 1829 <body> 1830 <video id="video" width="500px" height="500px" autoplay="autoplay"></video> 1831 <canvas id="canvas" width="500px" height="500px"></canvas> 1832 <br> 1833 <input type="button" title="HTML5 Camera" value="Enable Camera" onclick="getMedia()"/> 1834 <script> 1835 function getMedia() 1836 { 1837 let constraints = { 1838 video: {width: 500, height: 500}, 1839 audio: true 1840 }; 1841 // Obtain the video camera area. 1842 let video = document.getElementById("video"); 1843 // Returned Promise object. 1844 let promise = navigator.mediaDevices.getUserMedia(constraints); 1845 // then() is asynchronous. Invoke the MediaStream object as a parameter. 1846 promise.then(function (MediaStream) { 1847 video.srcObject = MediaStream; 1848 video.play(); 1849 }); 1850 } 1851 </script> 1852 </body> 1853 </html> 1854 ``` 1855 1856## onContextMenuShow<sup>9+</sup> 1857 1858onContextMenuShow(callback: Callback\<OnContextMenuShowEvent, boolean\>) 1859 1860Triggered when a context menu is displayed after the user clicks the right mouse button or long presses a specific element, such as an image or a link. 1861 1862**System capability**: SystemCapability.Web.Webview.Core 1863 1864**Parameters** 1865 1866| Name | Type | Mandatory | Description | 1867| ------ | ------ | ---- | --------------------- | 1868| callback | Callback\<[OnContextMenuShowEvent](./arkts-basic-components-web-i.md#oncontextmenushowevent12), boolean\> | Yes| Callback invoked during a call to allow for the display of a custom context menu.<br>Return value: boolean<br> The value **true** means that a custom menu is triggered, and **false** means that the custom menu is ineffective. | 1869 1870**Example** 1871 1872 ```ts 1873 // xxx.ets 1874 import { webview } from '@kit.ArkWeb'; 1875 import { pasteboard } from '@kit.BasicServicesKit'; 1876 1877 const TAG = 'ContextMenu'; 1878 1879 @Entry 1880 @Component 1881 struct WebComponent { 1882 controller: webview.WebviewController = new webview.WebviewController(); 1883 private result: WebContextMenuResult | undefined = undefined; 1884 @State linkUrl: string = ''; 1885 @State offsetX: number = 0; 1886 @State offsetY: number = 0; 1887 @State showMenu: boolean = false; 1888 uiContext: UIContext = this.getUIContext(); 1889 1890 @Builder 1891 // Build and trigger a custom menu. 1892 MenuBuilder() { 1893 // A component that is used to present a vertical list of items to the user. 1894 Menu() { 1895 // A component that is used to represent an item in a menu. 1896 MenuItem({ 1897 content: 'Cancel', 1898 }) 1899 .width(100) 1900 .height(50) 1901 .onClick(() => { 1902 this.result?.undo(); 1903 this.showMenu = false; 1904 }) 1905 MenuItem({ 1906 content: 'Redo', 1907 }) 1908 .width(100) 1909 .height(50) 1910 .onClick(() => { 1911 this.result?.redo(); 1912 this.showMenu = false; 1913 }) 1914 MenuItem({ 1915 content: 'Paste as plain text', 1916 }) 1917 .width(100) 1918 .height(50) 1919 .onClick(() => { 1920 this.result?.pasteAndMatchStyle(); 1921 this.showMenu = false; 1922 }) 1923 MenuItem({ 1924 content: 'Copy image', 1925 }) 1926 .width(100) 1927 .height(50) 1928 .onClick(() => { 1929 this.result?.copyImage(); 1930 this.showMenu = false; 1931 }) 1932 MenuItem({ 1933 content: 'Cut', 1934 }) 1935 .width(100) 1936 .height(50) 1937 .onClick(() => { 1938 this.result?.cut(); 1939 this.showMenu = false; 1940 }) 1941 MenuItem({ 1942 content: 'Copy', 1943 }) 1944 .width(100) 1945 .height(50) 1946 .onClick(() => { 1947 this.result?.copy(); 1948 this.showMenu = false; 1949 }) 1950 MenuItem({ 1951 content: 'Paste', 1952 }) 1953 .width(100) 1954 .height(50) 1955 .onClick(() => { 1956 this.result?.paste(); 1957 this.showMenu = false; 1958 }) 1959 MenuItem({ 1960 content: 'Copy link', 1961 }) 1962 .width(100) 1963 .height(50) 1964 .onClick(() => { 1965 let pasteData = pasteboard.createData('text/plain', this.linkUrl); 1966 pasteboard.getSystemPasteboard().setData(pasteData, (error) => { 1967 if (error) { 1968 return; 1969 } 1970 }) 1971 this.showMenu = false; 1972 }) 1973 MenuItem({ 1974 content: 'Select all', 1975 }) 1976 .width(100) 1977 .height(50) 1978 .onClick(() => { 1979 this.result?.selectAll(); 1980 this.showMenu = false; 1981 }) 1982 } 1983 .width(150) 1984 .height(450) 1985 } 1986 1987 build() { 1988 Column() { 1989 Web({ src: $rawfile("index.html"), controller: this.controller }) 1990 // Trigger a custom dialog box. 1991 .onContextMenuShow((event) => { 1992 if (event) { 1993 this.result = event.result 1994 console.info("x coord = " + event.param.x()); 1995 console.info("link url = " + event.param.getLinkUrl()); 1996 this.linkUrl = event.param.getLinkUrl(); 1997 } 1998 console.info(TAG, `x: ${this.offsetX}, y: ${this.offsetY}`); 1999 this.showMenu = true; 2000 this.offsetX = 0; 2001 this.offsetY = Math.max(this.uiContext!.px2vp(event?.param.y() ?? 0) - 0, 0); 2002 return true; 2003 }) 2004 .bindPopup(this.showMenu, 2005 { 2006 builder: this.MenuBuilder(), 2007 enableArrow: false, 2008 placement: Placement.LeftTop, 2009 offset: { x: this.offsetX, y: this.offsetY }, 2010 mask: false, 2011 onStateChange: (e) => { 2012 if (!e.isVisible) { 2013 this.showMenu = false; 2014 this.result!.closeContextMenu(); 2015 } 2016 } 2017 }) 2018 } 2019 } 2020 } 2021 ``` 2022 2023 HTML file to be loaded: 2024 ```html 2025 <!-- index.html --> 2026 <!DOCTYPE html> 2027 <html lang="en"> 2028 <body> 2029 <h1>onContextMenuShow</h1> 2030 <a href="http://www.example.com" style="font-size:27px">URL www.example.com</a> 2031 <!-- Place any image in the rawfile directory and name it example.png. --> 2032 <div><img src="example.png"></div> 2033 <p>Right-click text to display the context menu</p> 2034 </body> 2035 </html> 2036 ``` 2037 2038## onContextMenuHide<sup>11+</sup> 2039 2040onContextMenuHide(callback: OnContextMenuHideCallback) 2041 2042Triggered when a context menu is hidden after the user clicks the right mouse button or long presses a specific element, such as an image or a link. 2043 2044**System capability**: SystemCapability.Web.Webview.Core 2045 2046**Parameters** 2047 2048| Name | Type | Mandatory | Description | 2049| ------ | ------ | ---- | --------------------- | 2050| callback | [OnContextMenuHideCallback](./arkts-basic-components-web-t.md#oncontextmenuhidecallback11) | Yes| Callback related to menus. | 2051 2052**Example** 2053 2054 ```ts 2055 // xxx.ets 2056 import { webview } from '@kit.ArkWeb'; 2057 2058 @Entry 2059 @Component 2060 struct WebComponent { 2061 controller: webview.WebviewController = new webview.WebviewController(); 2062 2063 build() { 2064 Column() { 2065 Web({ src: 'www.example.com', controller: this.controller }) 2066 .onContextMenuHide(() => { 2067 console.log("onContextMenuHide callback"); 2068 }) 2069 } 2070 } 2071 } 2072 ``` 2073 2074## onScroll<sup>9+</sup> 2075 2076onScroll(callback: Callback\<OnScrollEvent\>) 2077 2078Triggered to notify the global scrolling position of the web page. 2079 2080> **NOTE** 2081> 2082> The change of the partial scrolling position cannot trigger this callback. 2083> 2084> To determine whether a page is globally scrolled, print **window.pagYOffset** or **window.pagXOffset** before and after scrolling. 2085> 2086> If the web page is scrolled globally, the value of **window.pagYOffset** or **window.pagXOffset** changes after the web page is scrolled. Otherwise, the value does not change. 2087 2088**System capability**: SystemCapability.Web.Webview.Core 2089 2090**Parameters** 2091 2092| Name | Type | Mandatory | Description | 2093| ------ | ------ | ---- | --------------------- | 2094| callback | Callback\<[OnScrollEvent](./arkts-basic-components-web-i.md#onscrollevent12)\> | Yes| Callback invoked when the scrollbar scrolls to a specified position.| 2095 2096**Example** 2097 2098 ```ts 2099 // xxx.ets 2100 import { webview } from '@kit.ArkWeb'; 2101 2102 @Entry 2103 @Component 2104 struct WebComponent { 2105 controller: webview.WebviewController = new webview.WebviewController(); 2106 2107 build() { 2108 Column() { 2109 Web({ src: 'www.example.com', controller: this.controller }) 2110 .onScroll((event) => { 2111 console.info("x = " + event.xOffset); 2112 console.info("y = " + event.yOffset); 2113 }) 2114 } 2115 } 2116 } 2117 ``` 2118 2119## onGeolocationShow 2120 2121onGeolocationShow(callback: Callback\<OnGeolocationShowEvent\>) 2122 2123Triggered to notify the application when a request to obtain the geolocation information is received. 2124 2125**System capability**: SystemCapability.Web.Webview.Core 2126 2127**Parameters** 2128 2129| Name | Type | Mandatory | Description | 2130| ------ | ------ | ---- | --------------------- | 2131| callback | Callback\<[OnGeolocationShowEvent](./arkts-basic-components-web-i.md#ongeolocationshowevent12)\> | Yes| Callback invoked when a request to obtain the geolocation information is received. | 2132 2133**Example** 2134 2135 ```ts 2136 // xxx.ets 2137 import { webview } from '@kit.ArkWeb'; 2138 2139 @Entry 2140 @Component 2141 struct WebComponent { 2142 controller: webview.WebviewController = new webview.WebviewController(); 2143 uiContext: UIContext = this.getUIContext(); 2144 2145 build() { 2146 Column() { 2147 Web({ src: $rawfile('index.html'), controller: this.controller }) 2148 .geolocationAccess(true) 2149 .onGeolocationShow((event) => { 2150 if (event) { 2151 this.uiContext.showAlertDialog({ 2152 title: 'title', 2153 message: 'text', 2154 confirm: { 2155 value: 'onConfirm', 2156 action: () => { 2157 event.geolocation.invoke(event.origin, true, true); 2158 } 2159 }, 2160 cancel: () => { 2161 event.geolocation.invoke(event.origin, false, true); 2162 } 2163 }) 2164 } 2165 }) 2166 } 2167 } 2168 } 2169 ``` 2170 2171 HTML file to be loaded: 2172 ```html 2173 <!DOCTYPE html> 2174 <html> 2175 <body> 2176 <p id="locationInfo">Location information</p> 2177 <button onclick="getLocation()">Obtain location</button> 2178 <script> 2179 var locationInfo=document.getElementById("locationInfo"); 2180 function getLocation(){ 2181 if (navigator.geolocation) { 2182 <!-- Access the device location on the frontend page --> 2183 navigator.geolocation.getCurrentPosition(showPosition); 2184 } 2185 } 2186 function showPosition(position){ 2187 locationInfo.innerHTML="Latitude: " + position.coords.latitude + "<br />Longitude: " + position.coords.longitude; 2188 } 2189 </script> 2190 </body> 2191 </html> 2192 ``` 2193 2194## onGeolocationHide 2195 2196onGeolocationHide(callback: () => void) 2197 2198Triggered to notify the user that the request for obtaining the geolocation information received when [onGeolocationShow](#ongeolocationshow) is called has been canceled. 2199 2200**System capability**: SystemCapability.Web.Webview.Core 2201 2202**Parameters** 2203 2204| Name | Type | Mandatory | Description | 2205| ------ | ------ | ---- | --------------------- | 2206| callback | () => void | Yes| Callback invoked when the request for obtaining geolocation information has been canceled. | 2207 2208**Example** 2209 2210 ```ts 2211 // xxx.ets 2212 import { webview } from '@kit.ArkWeb'; 2213 2214 @Entry 2215 @Component 2216 struct WebComponent { 2217 controller: webview.WebviewController = new webview.WebviewController(); 2218 2219 build() { 2220 Column() { 2221 Web({ src: 'www.example.com', controller: this.controller }) 2222 .geolocationAccess(true) 2223 .onGeolocationHide(() => { 2224 console.log("onGeolocationHide..."); 2225 }) 2226 } 2227 } 2228 } 2229 ``` 2230 2231## onFullScreenEnter<sup>9+</sup> 2232 2233onFullScreenEnter(callback: OnFullScreenEnterCallback) 2234 2235Triggered when the **Web** component enters full screen mode. 2236 2237**System capability**: SystemCapability.Web.Webview.Core 2238 2239**Parameters** 2240 2241| Name | Type | Mandatory | Description | 2242| ------ | ------ | ---- | --------------------- | 2243| callback | [OnFullScreenEnterCallback](./arkts-basic-components-web-t.md#onfullscreenentercallback12) | Yes| Callback invoked when the **Web** component enters full screen mode.| 2244 2245**Example** 2246 2247 ```ts 2248 // xxx.ets 2249 import { webview } from '@kit.ArkWeb'; 2250 2251 @Entry 2252 @Component 2253 struct WebComponent { 2254 controller: webview.WebviewController = new webview.WebviewController(); 2255 handler: FullScreenExitHandler | null = null; 2256 2257 build() { 2258 Column() { 2259 Web({ src: 'www.example.com', controller: this.controller }) 2260 .onFullScreenEnter((event) => { 2261 console.log("onFullScreenEnter videoWidth: " + event.videoWidth + 2262 ", videoHeight: " + event.videoHeight); 2263 // The application can proactively exit fullscreen mode by calling this.handler.exitFullScreen(). 2264 this.handler = event.handler; 2265 }) 2266 } 2267 } 2268 } 2269 ``` 2270 2271## onFullScreenExit<sup>9+</sup> 2272 2273onFullScreenExit(callback: () => void) 2274 2275Triggered when the **Web** component exits full screen mode. 2276 2277**System capability**: SystemCapability.Web.Webview.Core 2278 2279**Parameters** 2280 2281| Name | Type | Mandatory | Description | 2282| ------ | ------ | ---- | --------------------- | 2283| callback | () => void | Yes| Callback invoked when the component exits full screen mode.| 2284 2285**Example** 2286 2287 ```ts 2288 // xxx.ets 2289 import { webview } from '@kit.ArkWeb'; 2290 2291 @Entry 2292 @Component 2293 struct WebComponent { 2294 controller: webview.WebviewController = new webview.WebviewController(); 2295 handler: FullScreenExitHandler | null = null; 2296 2297 build() { 2298 Column() { 2299 Web({ src: 'www.example.com', controller: this.controller }) 2300 .onFullScreenExit(() => { 2301 console.log("onFullScreenExit...") 2302 if (this.handler) { 2303 this.handler.exitFullScreen(); 2304 } 2305 }) 2306 .onFullScreenEnter((event) => { 2307 this.handler = event.handler; 2308 }) 2309 } 2310 } 2311 } 2312 ``` 2313 2314## onWindowNew<sup>9+</sup> 2315 2316onWindowNew(callback: Callback\<OnWindowNewEvent\>) 2317 2318Triggered to notify the user of a new window creation request, when **multiWindowAccess** is enabled. 2319If the [setWebController](./arkts-basic-components-web-ControllerHandler.md#setwebcontroller9) API is not called, the render process will be blocked. 2320If no new window is created, set this parameter to **null** when invoking the [setWebController](./arkts-basic-components-web-ControllerHandler.md#setwebcontroller9) API to notify the **Web** component that no new window is created. 2321 2322The new window cannot be directly overlaid on the original **Web** component, and its URL (for example, address bar) must be clearly displayed in the same way as the main page to prevent confusion. If visible management of trusted URLs cannot be implemented, consider prohibiting the creation of new windows. 2323Note that the source of a new window request cannot be reliably traced. The request may be initiated by a third-party iframe. By default, the application needs to take defense measures such as sandbox isolation and permission restriction to ensure security. 2324 2325**System capability**: SystemCapability.Web.Webview.Core 2326 2327**Parameters** 2328 2329| Name | Type | Mandatory | Description | 2330| ------ | ------ | ---- | --------------------- | 2331| callback | Callback\<[OnWindowNewEvent](./arkts-basic-components-web-i.md#onwindownewevent12)\> | Yes| Callback invoked when the web page requests the user to create a window. | 2332 2333**Example** 2334 2335 ```ts 2336 // xxx.ets 2337 import { webview } from '@kit.ArkWeb'; 2338 2339 // There are two Web components on the same page. When the WebComponent object opens a new window, the NewWebViewComp object is displayed. 2340 @CustomDialog 2341 struct NewWebViewComp { 2342 controller?: CustomDialogController; 2343 webviewController1: webview.WebviewController = new webview.WebviewController(); 2344 2345 build() { 2346 Column() { 2347 Web({ src: "www.example.com", controller: this.webviewController1 }) 2348 .javaScriptAccess(true) 2349 .multiWindowAccess(false) 2350 .onWindowExit(() => { 2351 console.info("NewWebViewComp onWindowExit"); 2352 if (this.controller) { 2353 this.controller.close(); 2354 } 2355 }) 2356 } 2357 } 2358 } 2359 2360 @Entry 2361 @Component 2362 struct WebComponent { 2363 controller: webview.WebviewController = new webview.WebviewController(); 2364 dialogController: CustomDialogController | null = null; 2365 2366 build() { 2367 Column() { 2368 Web({ src: $rawfile("window.html"), controller: this.controller }) 2369 .javaScriptAccess(true) 2370 // MultiWindowAccess needs to be enabled. 2371 .multiWindowAccess(true) 2372 .allowWindowOpenMethod(true) 2373 .onWindowNew((event) => { 2374 if (this.dialogController) { 2375 this.dialogController.close(); 2376 } 2377 let popController: webview.WebviewController = new webview.WebviewController(); 2378 this.dialogController = new CustomDialogController({ 2379 builder: NewWebViewComp({ webviewController1: popController }) 2380 }) 2381 this.dialogController.open(); 2382 // Return the WebviewController object corresponding to the new window to the web kernel. 2383 // If the event.handler.setWebController API is not called, the render process will be blocked. 2384 // If no new window is created, set the value of event.handler.setWebController to null to notify the Web component that no new window is created. 2385 event.handler.setWebController(popController); 2386 }) 2387 } 2388 } 2389 } 2390 ``` 2391 2392 ```html 2393 <!-- Code of the window.html page --> 2394 <!DOCTYPE html> 2395 <html> 2396 <head> 2397 <meta charset="UTF-8"> 2398 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 2399 </head> 2400 <body> 2401 <a href="#" onclick="openNewWindow('https://www.example.com')">Open a new page</a> 2402 <script type="text/javascript"> 2403 function openNewWindow(url) { 2404 window.open(url, 'example'); 2405 return false; 2406 } 2407 </script> 2408 </body> 2409 </html> 2410 ``` 2411 2412## onActivateContent<sup>20+</sup> 2413 2414onActivateContent(callback: Callback\<void>) 2415 2416Triggered to notify the application of displaying the bound **Web** instance to the frontend. Whether a bound **Web** instance exists is checked based on the name when a web page **triggers window.open(url, name)**. If a bound **Web** instance does not exist, [onWindowNew](#onwindownew9) is triggered to notify the application of creating a new **Web** instance. 2417 2418> **NOTE** 2419> 2420> - Binding a **Web** instance by name: Call the **event.handler.setWebController** method in the [onWindowNew] (#onwindownew9) callback and transfer the controller of the new **Web** instance. 2421> - The name must comply with the regular expression **[a-zA-Z0-9_]+**. When the name is used as the value of the **target** attribute of the \<a> or \<form> tag, the bound **Web** instance also triggers this callback function. 2422 2423**System capability**: SystemCapability.Web.Webview.Core 2424 2425**Parameters** 2426 2427| Name | Type | Mandatory| Description | 2428| ------------- | ---------------- | ---- | --------------------------------- | 2429| callback | Callback\<void> | Yes | Callback triggered on a new page after **window.open** is triggered on the original page.| 2430 2431**Example** 2432 2433 ```ts 2434 // xxx.ets 2435 import { webview } from '@kit.ArkWeb'; 2436 2437 // There are two Web components on the same page. When the WebComponent object opens a new window, the NewWebViewComp object is displayed. 2438 @CustomDialog 2439 struct NewWebViewComp { 2440 controller?: CustomDialogController; 2441 webviewController1: webview.WebviewController = new webview.WebviewController(); 2442 2443 build() { 2444 Column() { 2445 Web({ src: "https://www.example.com", controller: this.webviewController1 }) 2446 .javaScriptAccess(true) 2447 .multiWindowAccess(false) 2448 .onWindowExit(() => { 2449 if (this.controller) { 2450 this.controller.close(); 2451 } 2452 }) 2453 .onActivateContent(() => { 2454 //The Web component needs to be displayed in the front. It is recommended that the application switch between tabs or windows to display the Web component. 2455 console.log("NewWebViewComp onActivateContent") 2456 }) 2457 }.height("50%") 2458 } 2459 } 2460 2461 @Entry 2462 @Component 2463 struct WebComponent { 2464 controller: webview.WebviewController = new webview.WebviewController(); 2465 dialogController: CustomDialogController | null = null; 2466 2467 build() { 2468 Column() { 2469 Web({ src: $rawfile("window.html"), controller: this.controller }) 2470 .javaScriptAccess(true) 2471 .allowWindowOpenMethod(true) 2472 // MultiWindowAccess needs to be enabled. 2473 .multiWindowAccess(true) 2474 .onWindowNew((event) => { 2475 if (this.dialogController) { 2476 this.dialogController.close() 2477 } 2478 let popController: webview.WebviewController = new webview.WebviewController(); 2479 this.dialogController = new CustomDialogController({ 2480 builder: NewWebViewComp({ webviewController1: popController }), 2481 isModal: false 2482 }) 2483 this.dialogController.open(); 2484 // Return the WebviewController object corresponding to the new window to the web kernel. 2485 // If the event.handler.setWebController API is not called, the render process will be blocked. 2486 event.handler.setWebController(popController); 2487 }) 2488 } 2489 } 2490 } 2491 ``` 2492 2493 ```html 2494 <!-- Code of the window.html page --> 2495 <!DOCTYPE html> 2496 <html> 2497 <head> 2498 <meta charset="UTF-8"> 2499 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 2500 <title>ActivateContentEvent</title> 2501 </head> 2502 <body> 2503 <a href="#" onclick="openNewWindow('https://www.example.com')">Open a new page</a> 2504 <script type="text/javascript"> 2505 function openNewWindow(url) { 2506 window.open(url, 'example'); 2507 return false; 2508 } 2509 </script> 2510 </body> 2511 </html> 2512 ``` 2513 2514## onWindowExit<sup>9+</sup> 2515 2516onWindowExit(callback: () => void) 2517 2518Triggered when this window is closed. This API works in the same way as [onWindowNew](#onwindownew9). For security, applications should notify users that the pages they interact with are closed. 2519 2520**System capability**: SystemCapability.Web.Webview.Core 2521 2522**Parameters** 2523 2524| Name | Type | Mandatory | Description | 2525| ------ | ------ | ---- | --------------------- | 2526| callback | () => void | Yes| Callback invoked when the window is closed.| 2527 2528**Example** 2529 2530 ```ts 2531 // xxx.ets 2532 import { webview } from '@kit.ArkWeb'; 2533 2534 @Entry 2535 @Component 2536 struct WebComponent { 2537 controller: webview.WebviewController = new webview.WebviewController(); 2538 2539 build() { 2540 Column() { 2541 Web({ src: 'www.example.com', controller: this.controller }) 2542 .onWindowExit(() => { 2543 console.log("onWindowExit..."); 2544 }) 2545 } 2546 } 2547 } 2548 ``` 2549 2550## onSearchResultReceive<sup>9+</sup> 2551 2552onSearchResultReceive(callback: Callback\<OnSearchResultReceiveEvent\>) 2553 2554Triggered to notify the caller of the search result on the web page. 2555 2556**System capability**: SystemCapability.Web.Webview.Core 2557 2558**Parameters** 2559 2560| Name | Type | Mandatory | Description | 2561| ------ | ------ | ---- | --------------------- | 2562| callback | Callback\<[OnSearchResultReceiveEvent](./arkts-basic-components-web-i.md#onsearchresultreceiveevent12)\> | Yes| Callback invoked to notify the caller of the search result on the web page. | 2563 2564**Example** 2565 2566 ```ts 2567 // xxx.ets 2568 import { webview } from '@kit.ArkWeb'; 2569 2570 @Entry 2571 @Component 2572 struct WebComponent { 2573 controller: webview.WebviewController = new webview.WebviewController(); 2574 2575 build() { 2576 Column() { 2577 Web({ src: 'www.example.com', controller: this.controller }) 2578 .onSearchResultReceive(ret => { 2579 if (ret) { 2580 console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal + 2581 "[total]" + ret.numberOfMatches + "[isDone]" + ret.isDoneCounting); 2582 } 2583 }) 2584 } 2585 } 2586 } 2587 ``` 2588 2589## onDataResubmitted<sup>9+</sup> 2590 2591onDataResubmitted(callback: Callback\<OnDataResubmittedEvent\>) 2592 2593Triggered when the web form data can be resubmitted. 2594 2595**System capability**: SystemCapability.Web.Webview.Core 2596 2597**Parameters** 2598 2599| Name | Type | Mandatory | Description | 2600| ------ | ------ | ---- | --------------------- | 2601| callback | Callback\<[OnDataResubmittedEvent](./arkts-basic-components-web-i.md#ondataresubmittedevent12)\> | Yes| Callback invoked when the web form data can be resubmitted.| 2602 2603**Example** 2604 2605 ```ts 2606 // xxx.ets 2607 import { webview } from '@kit.ArkWeb'; 2608 import { BusinessError } from '@kit.BasicServicesKit'; 2609 2610 @Entry 2611 @Component 2612 struct WebComponent { 2613 controller: webview.WebviewController = new webview.WebviewController(); 2614 2615 build() { 2616 Column() { 2617 // After you click Submit on the web page, you can click Refresh to trigger the function again. 2618 Button('refresh') 2619 .onClick(() => { 2620 try { 2621 this.controller.refresh(); 2622 } catch (error) { 2623 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 2624 } 2625 }) 2626 Web({ src: $rawfile('index.html'), controller: this.controller }) 2627 .onDataResubmitted((event) => { 2628 console.log('onDataResubmitted'); 2629 event.handler.resend(); 2630 }) 2631 } 2632 } 2633 } 2634 ``` 2635 2636 HTML file to be loaded: 2637 ```html 2638 <!-- index.html --> 2639 <!DOCTYPE html> 2640 <html> 2641 <head> 2642 <meta charset="utf-8"> 2643 </head> 2644 <body> 2645 <form action="http://httpbin.org/post" method="post"> 2646 <input type="text" name="username"> 2647 <input type="submit" name="Submit"> 2648 </form> 2649 </body> 2650 </html> 2651 ``` 2652 2653## onPageVisible<sup>9+</sup> 2654 2655onPageVisible(callback: Callback\<OnPageVisibleEvent\>) 2656 2657Triggered when the old page is not displayed and the new page is about to be visible. 2658 2659**System capability**: SystemCapability.Web.Webview.Core 2660 2661**Parameters** 2662 2663| Name | Type | Mandatory | Description | 2664| ------ | ------ | ---- | --------------------- | 2665| callback | Callback\<[OnPageVisibleEvent](./arkts-basic-components-web-i.md#onpagevisibleevent12)\> | Yes| Callback invoked when the old page is not displayed and the new page is about to be visible.| 2666 2667**Example** 2668 2669 ```ts 2670 // xxx.ets 2671 import { webview } from '@kit.ArkWeb'; 2672 2673 @Entry 2674 @Component 2675 struct WebComponent { 2676 controller: webview.WebviewController = new webview.WebviewController(); 2677 2678 build() { 2679 Column() { 2680 Web({ src: 'www.example.com', controller: this.controller }) 2681 .onPageVisible((event) => { 2682 console.log('onPageVisible url:' + event.url); 2683 }) 2684 } 2685 } 2686 } 2687 ``` 2688 2689## onInterceptKeyEvent<sup>9+</sup> 2690 2691onInterceptKeyEvent(callback: (event: KeyEvent) => boolean) 2692 2693Triggered when the key event is intercepted and before it is consumed by the webview. 2694 2695**System capability**: SystemCapability.Web.Webview.Core 2696 2697**Parameters** 2698 2699| Name | Type | Mandatory | Description | 2700| ------ | ------ | ---- | --------------------- | 2701| callback | (event:[KeyEvent](../apis-arkui/arkui-ts/ts-universal-events-key.md#keyevent)) => boolean| Yes| Key event that is triggered.<br>The return value is of the Boolean type. The value **true** means to pass the **KeyEvent** to the web kernel, and **false** means the opposite.| 2702 2703**Example** 2704 2705 ```ts 2706 // xxx.ets 2707 import { webview } from '@kit.ArkWeb'; 2708 2709 @Entry 2710 @Component 2711 struct WebComponent { 2712 controller: webview.WebviewController = new webview.WebviewController(); 2713 2714 build() { 2715 Column() { 2716 Web({ src: 'www.example.com', controller: this.controller }) 2717 .onInterceptKeyEvent((event) => { 2718 if (event.keyCode == 2017 || event.keyCode == 2018) { 2719 console.info(`onInterceptKeyEvent get event.keyCode ${event.keyCode}`); 2720 return true; 2721 } 2722 return false; 2723 }) 2724 } 2725 } 2726 } 2727 ``` 2728 2729## onTouchIconUrlReceived<sup>9+</sup> 2730 2731onTouchIconUrlReceived(callback: Callback\<OnTouchIconUrlReceivedEvent\>) 2732 2733Triggered when an apple-touch-icon URL is received. 2734 2735**System capability**: SystemCapability.Web.Webview.Core 2736 2737**Parameters** 2738 2739| Name | Type | Mandatory | Description | 2740| ------ | ------ | ---- | --------------------- | 2741| callback | Callback\<[OnTouchIconUrlReceivedEvent](./arkts-basic-components-web-i.md#ontouchiconurlreceivedevent12)\> | Yes| Callback invoked when an apple-touch-icon URL is received.| 2742 2743**Example** 2744 2745 ```ts 2746 // xxx.ets 2747 import { webview } from '@kit.ArkWeb'; 2748 2749 @Entry 2750 @Component 2751 struct WebComponent { 2752 controller: webview.WebviewController = new webview.WebviewController(); 2753 2754 build() { 2755 Column() { 2756 Web({ src: 'www.baidu.com', controller: this.controller }) 2757 .onTouchIconUrlReceived((event) => { 2758 console.log('onTouchIconUrlReceived:' + JSON.stringify(event)); 2759 }) 2760 } 2761 } 2762 } 2763 ``` 2764 2765## onFaviconReceived<sup>9+</sup> 2766 2767onFaviconReceived(callback: Callback\<OnFaviconReceivedEvent\>) 2768 2769Triggered when this web page receives a new favicon. 2770 2771**System capability**: SystemCapability.Web.Webview.Core 2772 2773**Parameters** 2774 2775| Name | Type | Mandatory | Description | 2776| ------ | ------ | ---- | --------------------- | 2777| callback | Callback\<[OnFaviconReceivedEvent](./arkts-basic-components-web-i.md#onfaviconreceivedevent12)\> | Yes| Callback invoked when the current web page receives a new favicon.| 2778 2779**Example** 2780 2781 ```ts 2782 // xxx.ets 2783 import { webview } from '@kit.ArkWeb'; 2784 import { image } from '@kit.ImageKit'; 2785 2786 @Entry 2787 @Component 2788 struct WebComponent { 2789 controller: webview.WebviewController = new webview.WebviewController(); 2790 @State icon: image.PixelMap | undefined = undefined; 2791 2792 build() { 2793 Column() { 2794 Web({ src: 'www.example.com', controller: this.controller }) 2795 .onFaviconReceived((event) => { 2796 console.log('onFaviconReceived'); 2797 this.icon = event.favicon; 2798 }) 2799 } 2800 } 2801 } 2802 ``` 2803 2804## onAudioStateChanged<sup>10+</sup> 2805 2806onAudioStateChanged(callback: Callback\<OnAudioStateChangedEvent\>) 2807 2808Triggered when the audio playback status on the web page changes. 2809 2810**System capability**: SystemCapability.Web.Webview.Core 2811 2812**Parameters** 2813 2814| Name | Type | Mandatory | Description | 2815| ------ | ------ | ---- | --------------------- | 2816| callback | Callback\<[OnAudioStateChangedEvent](./arkts-basic-components-web-i.md#onaudiostatechangedevent12)\> | Yes| Callback invoked when the audio playback status on the web page changes.| 2817 2818**Example** 2819 2820 ```ts 2821 // xxx.ets 2822 import { webview } from '@kit.ArkWeb'; 2823 2824 @Entry 2825 @Component 2826 struct WebComponent { 2827 controller: webview.WebviewController = new webview.WebviewController(); 2828 @State playing: boolean = false; 2829 2830 build() { 2831 Column() { 2832 Web({ src: 'www.example.com', controller: this.controller }) 2833 .onAudioStateChanged(event => { 2834 this.playing = event.playing; 2835 console.debug('onAudioStateChanged playing: ' + this.playing); 2836 }) 2837 } 2838 } 2839 } 2840 ``` 2841 2842## onFirstContentfulPaint<sup>10+</sup> 2843 2844 onFirstContentfulPaint(callback: Callback\<OnFirstContentfulPaintEvent\>) 2845 2846Triggered when the first content paint occurs on the web page. 2847 2848**System capability**: SystemCapability.Web.Webview.Core 2849 2850**Parameters** 2851 2852| Name | Type | Mandatory | Description | 2853| ------ | ------ | ---- | --------------------- | 2854| callback | Callback\<[OnFirstContentfulPaintEvent](./arkts-basic-components-web-i.md#onfirstcontentfulpaintevent12)\> | Yes| Callback invoked when the first content paint occurs on the web page. | 2855 2856**Example** 2857 2858 ```ts 2859 // xxx.ets 2860 import { webview } from '@kit.ArkWeb'; 2861 2862 @Entry 2863 @Component 2864 struct WebComponent { 2865 controller: webview.WebviewController = new webview.WebviewController(); 2866 2867 build() { 2868 Column() { 2869 Web({ src: 'www.example.com', controller: this.controller }) 2870 .onFirstContentfulPaint(event => { 2871 if (event) { 2872 console.log("onFirstContentfulPaint:" + "[navigationStartTick]:" + 2873 event.navigationStartTick + ", [firstContentfulPaintMs]:" + 2874 event.firstContentfulPaintMs); 2875 } 2876 }) 2877 } 2878 } 2879 } 2880 ``` 2881 2882## onFirstMeaningfulPaint<sup>12+</sup> 2883 2884onFirstMeaningfulPaint(callback: [OnFirstMeaningfulPaintCallback](./arkts-basic-components-web-t.md#onfirstmeaningfulpaintcallback12)) 2885 2886Triggered when the first meaningful paint occurs on the web page. 2887 2888**System capability**: SystemCapability.Web.Webview.Core 2889 2890**Parameters** 2891 2892| Name | Type | Mandatory | Description | 2893| ------ | ------ | ---- | --------------------- | 2894| callback | [OnFirstMeaningfulPaintCallback](./arkts-basic-components-web-t.md#onfirstmeaningfulpaintcallback12) | Yes| Callback invoked when the First Meaningful Paint occurs on the web page.| 2895 2896**Example** 2897 2898 ```ts 2899 // xxx.ets 2900 import { webview } from '@kit.ArkWeb'; 2901 2902 @Entry 2903 @Component 2904 struct WebComponent { 2905 controller: webview.WebviewController = new webview.WebviewController(); 2906 2907 build() { 2908 Column() { 2909 Web({ src: 'www.example.com', controller: this.controller }) 2910 .onFirstMeaningfulPaint((details) => { 2911 console.log("onFirstMeaningfulPaint: [navigationStartTime]= " + details.navigationStartTime + 2912 ", [firstMeaningfulPaintTime]=" + details.firstMeaningfulPaintTime); 2913 }) 2914 } 2915 } 2916 } 2917 ``` 2918 2919## onLargestContentfulPaint<sup>12+</sup> 2920 2921onLargestContentfulPaint(callback: [OnLargestContentfulPaintCallback](./arkts-basic-components-web-t.md#onlargestcontentfulpaintcallback12)) 2922 2923Triggered when the largest content paint occurs on the web page. 2924 2925**System capability**: SystemCapability.Web.Webview.Core 2926 2927**Parameters** 2928 2929| Name | Type | Mandatory | Description | 2930| ------ | ------ | ---- | --------------------- | 2931| callback | [OnLargestContentfulPaintCallback](./arkts-basic-components-web-t.md#onlargestcontentfulpaintcallback12) | Yes| Callback invoked when the largest content paint occurs on the web page.| 2932 2933**Example** 2934 2935 ```ts 2936 // xxx.ets 2937 import { webview } from '@kit.ArkWeb'; 2938 2939 @Entry 2940 @Component 2941 struct WebComponent { 2942 controller: webview.WebviewController = new webview.WebviewController(); 2943 2944 build() { 2945 Column() { 2946 Web({ src: 'www.example.com', controller: this.controller }) 2947 .onLargestContentfulPaint((details) => { 2948 console.log("onLargestContentfulPaint: [navigationStartTime]= " + details.navigationStartTime + 2949 ", [largestImagePaintTime]=" + details.largestImagePaintTime + 2950 ", [largestTextPaintTime]=" + details.largestTextPaintTime + 2951 ", [largestImageLoadStartTime]=" + details.largestImageLoadStartTime + 2952 ", [largestImageLoadEndTime]=" + details.largestImageLoadEndTime + 2953 ", [imageBPP]=" + details.imageBPP); 2954 }) 2955 } 2956 } 2957 } 2958 ``` 2959 2960## onLoadIntercept<sup>10+</sup> 2961 2962onLoadIntercept(callback: Callback\<OnLoadInterceptEvent, boolean\>) 2963 2964Triggered when the **Web** component is about to access a URL. This API is used to determine whether to block the access. 2965 2966**System capability**: SystemCapability.Web.Webview.Core 2967 2968**Parameters** 2969 2970| Name | Type | Mandatory | Description | 2971| ------ | ------ | ---- | --------------------- | 2972| callback | Callback\<[OnLoadInterceptEvent](./arkts-basic-components-web-i.md#onloadinterceptevent12), boolean\> | Yes| Callback invoked when the **Web** component is about to access a URL.<br>The return value is of the Boolean type. If **true** is returned, the access is blocked. Otherwise, the access is allowed.<br>Default value: **true**.| 2973 2974**Example** 2975 2976 ```ts 2977 // xxx.ets 2978 import { webview } from '@kit.ArkWeb'; 2979 2980 @Entry 2981 @Component 2982 struct WebComponent { 2983 controller: webview.WebviewController = new webview.WebviewController(); 2984 2985 build() { 2986 Column() { 2987 Web({ src: 'www.example.com', controller: this.controller }) 2988 .onLoadIntercept((event) => { 2989 console.log('url:' + event.data.getRequestUrl()); 2990 console.log('isMainFrame:' + event.data.isMainFrame()); 2991 console.log('isRedirect:' + event.data.isRedirect()); 2992 console.log('isRequestGesture:' + event.data.isRequestGesture()); 2993 return true; 2994 }) 2995 } 2996 } 2997 } 2998 ``` 2999 3000## onRequestSelected 3001 3002onRequestSelected(callback: () => void) 3003 3004Triggered when the **Web** component obtains the focus. 3005 3006**System capability**: SystemCapability.Web.Webview.Core 3007 3008**Parameters** 3009 3010| Name | Type | Mandatory | Description | 3011| ------ | ------ | ---- | --------------------- | 3012| callback | () => void | Yes| Callback triggered when a web page obtains the focus.| 3013 3014**Example** 3015 3016 ```ts 3017 // xxx.ets 3018 import { webview } from '@kit.ArkWeb'; 3019 3020 @Entry 3021 @Component 3022 struct WebComponent { 3023 controller: webview.WebviewController = new webview.WebviewController(); 3024 3025 build() { 3026 Column() { 3027 Web({ src: 'www.example.com', controller: this.controller }) 3028 .onRequestSelected(() => { 3029 console.log('onRequestSelected'); 3030 }) 3031 } 3032 } 3033 } 3034 ``` 3035## onScreenCaptureRequest<sup>10+</sup> 3036 3037onScreenCaptureRequest(callback: Callback\<OnScreenCaptureRequestEvent\>) 3038 3039Triggered when a screen capture request is received. 3040 3041**System capability**: SystemCapability.Web.Webview.Core 3042 3043**Parameters** 3044 3045| Name | Type | Mandatory | Description | 3046| ------ | ------ | ---- | --------------------- | 3047| callback | Callback\<[OnScreenCaptureRequestEvent](./arkts-basic-components-web-i.md#onscreencapturerequestevent12)\> | Yes| Callback invoked when a screen capture request is received.| 3048 3049**Example** 3050 3051 ```ts 3052 // xxx.ets 3053 import { webview } from '@kit.ArkWeb'; 3054 3055 @Entry 3056 @Component 3057 struct WebComponent { 3058 controller: webview.WebviewController = new webview.WebviewController(); 3059 uiContext: UIContext = this.getUIContext(); 3060 3061 build() { 3062 Column() { 3063 Web({ src: 'www.example.com', controller: this.controller }) 3064 .onScreenCaptureRequest((event) => { 3065 if (event) { 3066 this.uiContext.showAlertDialog({ 3067 title: 'title: ' + event.handler.getOrigin(), 3068 message: 'text', 3069 primaryButton: { 3070 value: 'deny', 3071 action: () => { 3072 event.handler.deny(); 3073 } 3074 }, 3075 secondaryButton: { 3076 value: 'onConfirm', 3077 action: () => { 3078 event.handler.grant({ captureMode: WebCaptureMode.HOME_SCREEN }); 3079 } 3080 }, 3081 cancel: () => { 3082 event.handler.deny(); 3083 } 3084 }) 3085 } 3086 }) 3087 } 3088 } 3089 } 3090 ``` 3091 3092## onOverScroll<sup>10+</sup> 3093 3094onOverScroll(callback: Callback\<OnOverScrollEvent\>) 3095 3096Triggered when the web page is overscrolled. It is used to notify the application of the overscroll offset. 3097 3098**System capability**: SystemCapability.Web.Webview.Core 3099 3100**Parameters** 3101 3102| Name | Type | Mandatory | Description | 3103| ------ | ------ | ---- | --------------------- | 3104| callback | Callback\<[OnOverScrollEvent](./arkts-basic-components-web-i.md#onoverscrollevent12)\> | Yes| Callback invoked when the web page is overscrolled.| 3105 3106**Example** 3107 3108 ```ts 3109 // xxx.ets 3110 import { webview } from '@kit.ArkWeb'; 3111 3112 @Entry 3113 @Component 3114 struct WebComponent { 3115 controller: webview.WebviewController = new webview.WebviewController(); 3116 3117 build() { 3118 Column() { 3119 Web({ src: 'www.example.com', controller: this.controller }) 3120 .onOverScroll((event) => { 3121 console.info("x = " + event.xOffset); 3122 console.info("y = " + event.yOffset); 3123 }) 3124 } 3125 } 3126 } 3127 ``` 3128 3129## onControllerAttached<sup>10+</sup> 3130 3131onControllerAttached(callback: () => void) 3132 3133Triggered when the controller is successfully bound to the **Web** component. The controller must be **WebviewController**. Do not call APIs related to the **Web** component before this callback event. Otherwise, a js-error exception will be thrown. 3134The web page has not been loaded when the callback is called. Therefore, APIs related to web page operations, such as [zoomIn](./arkts-apis-webview-WebviewController.md#zoomin), [zoomOut](./arkts-apis-webview-WebviewController.md#zoomout), cannot be used in the callback. You can use APIs irrelevant to web page operations, such as [loadUrl](./arkts-apis-webview-WebviewController.md#loadurl), [getWebId](./arkts-apis-webview-WebviewController.md#getwebid). 3135 3136For details about the component lifecycle, see [Lifecycle of the Web Component](../../web/web-event-sequence.md). 3137 3138**System capability**: SystemCapability.Web.Webview.Core 3139 3140**Parameters** 3141 3142| Name | Type | Mandatory | Description | 3143| ------ | ------ | ---- | --------------------- | 3144| callback | () => void | Yes| Callback invoked when the ArkWeb controller is successfully initialized.| 3145 3146**Example** 3147 3148The following example uses **loadUrl** in the callback to load the web page. 3149 ```ts 3150 // xxx.ets 3151 import { webview } from '@kit.ArkWeb'; 3152 3153 @Entry 3154 @Component 3155 struct WebComponent { 3156 controller: webview.WebviewController = new webview.WebviewController(); 3157 3158 build() { 3159 Column() { 3160 Web({ src: '', controller: this.controller }) 3161 .onControllerAttached(() => { 3162 this.controller.loadUrl($rawfile("index.html")); 3163 }) 3164 } 3165 } 3166 } 3167 ``` 3168 3169The following example uses **getWebId** in the callback. 3170 ```ts 3171 // xxx.ets 3172 import { webview } from '@kit.ArkWeb'; 3173 import { BusinessError } from '@kit.BasicServicesKit'; 3174 3175 @Entry 3176 @Component 3177 struct WebComponent { 3178 controller: webview.WebviewController = new webview.WebviewController(); 3179 3180 build() { 3181 Column() { 3182 Web({ src: $rawfile("index.html"), controller: this.controller }) 3183 .onControllerAttached(() => { 3184 try { 3185 let id = this.controller.getWebId(); 3186 console.log("id: " + id); 3187 } catch (error) { 3188 let code = (error as BusinessError).code; 3189 let message = (error as BusinessError).message; 3190 console.error(`ErrorCode: ${code}, Message: ${message}`); 3191 } 3192 }) 3193 } 3194 } 3195 } 3196 ``` 3197 HTML file to be loaded: 3198 ```html 3199 <!-- index.html --> 3200 <!DOCTYPE html> 3201 <html> 3202 <body> 3203 <p>Hello World</p> 3204 </body> 3205 </html> 3206 ``` 3207 3208## onNavigationEntryCommitted<sup>11+</sup> 3209 3210onNavigationEntryCommitted(callback: [OnNavigationEntryCommittedCallback](./arkts-basic-components-web-t.md#onnavigationentrycommittedcallback11)) 3211 3212Triggered when a web page redirection request is submitted. 3213 3214**System capability**: SystemCapability.Web.Webview.Core 3215 3216**Parameters** 3217 3218| Name | Type | Mandatory | Description | 3219| ------ | ------ | ---- | --------------------- | 3220| callback | [OnNavigationEntryCommittedCallback](./arkts-basic-components-web-t.md#onnavigationentrycommittedcallback11) | Yes| Callback invoked when a web page redirection request is submitted.| 3221 3222**Example** 3223 3224 ```ts 3225 // xxx.ets 3226 import { webview } from '@kit.ArkWeb'; 3227 3228 @Entry 3229 @Component 3230 struct WebComponent { 3231 controller: webview.WebviewController = new webview.WebviewController(); 3232 3233 build() { 3234 Column() { 3235 Web({ src: 'www.example.com', controller: this.controller }) 3236 .onNavigationEntryCommitted((details) => { 3237 console.log("onNavigationEntryCommitted: [isMainFrame]= " + details.isMainFrame + 3238 ", [isSameDocument]=" + details.isSameDocument + 3239 ", [didReplaceEntry]=" + details.didReplaceEntry + 3240 ", [navigationType]=" + details.navigationType + 3241 ", [url]=" + details.url); 3242 }) 3243 } 3244 } 3245 } 3246 ``` 3247 3248## onSafeBrowsingCheckResult<sup>11+</sup> 3249 3250onSafeBrowsingCheckResult(callback: OnSafeBrowsingCheckResultCallback) 3251 3252Callback invoked when the safe browsing check result is received. 3253 3254**System capability**: SystemCapability.Web.Webview.Core 3255 3256**Parameters** 3257 3258| Name | Type | Mandatory | Description | 3259| ------ | ------ | ---- | --------------------- | 3260| callback | [OnSafeBrowsingCheckResultCallback](./arkts-basic-components-web-t.md#onsafebrowsingcheckresultcallback11) | Yes| Callback invoked when the safe browsing check result is received.| 3261 3262**Example** 3263 3264 ```ts 3265 // xxx.ets 3266 import { webview } from '@kit.ArkWeb'; 3267 3268 export enum ThreatType { 3269 UNKNOWN = -1, 3270 THREAT_ILLEGAL = 0, 3271 THREAT_FRAUD = 1, 3272 THREAT_RISK = 2, 3273 THREAT_WARNING = 3, 3274 } 3275 3276 export class OnSafeBrowsingCheckResultCallback { 3277 threatType: ThreatType = ThreatType.UNKNOWN; 3278 } 3279 3280 @Entry 3281 @Component 3282 struct WebComponent { 3283 controller: webview.WebviewController = new webview.WebviewController(); 3284 3285 build() { 3286 Column() { 3287 Web({ src: 'www.example.com', controller: this.controller }) 3288 .onSafeBrowsingCheckResult((callback) => { 3289 let jsonData = JSON.stringify(callback); 3290 let json: OnSafeBrowsingCheckResultCallback = JSON.parse(jsonData); 3291 console.log("onSafeBrowsingCheckResult: [threatType]= " + json.threatType); 3292 }) 3293 } 3294 } 3295 } 3296 ``` 3297 3298## onNativeEmbedLifecycleChange<sup>11+</sup> 3299 3300onNativeEmbedLifecycleChange(callback: (event: NativeEmbedDataInfo) => void) 3301 3302Triggered when the lifecycle of the same-layer tag changes. 3303 3304**System capability**: SystemCapability.Web.Webview.Core 3305 3306**Parameters** 3307 3308| Name | Type | Mandatory | Description | 3309| ------ | ------ | ---- | --------------------- | 3310| callback | (event: [NativeEmbedDataInfo](./arkts-basic-components-web-i.md#nativeembeddatainfo11)) => void | Yes| Callback invoked when the lifecycle of the same-layer tag changes.| 3311 3312**Example** 3313 3314```ts 3315// EntryAbility.ets 3316 3317import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 3318import { hilog } from '@kit.PerformanceAnalysisKit'; 3319import { window } from '@kit.ArkUI'; 3320import { webview } from '@kit.ArkWeb'; 3321 3322export default class EntryAbility extends UIAbility { 3323 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 3324 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); 3325 // Added in API version 12: feature to enable the back/forward cache for same-layer rendering. 3326 let features = new webview.BackForwardCacheSupportedFeatures(); 3327 features.nativeEmbed = true; 3328 features.mediaTakeOver = true; 3329 webview.WebviewController.enableBackForwardCache(features); 3330 webview.WebviewController.initializeWebEngine(); 3331 } 3332 3333 onDestroy(): void { 3334 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy'); 3335 } 3336 3337 onWindowStageCreate(windowStage: window.WindowStage): void { 3338 // Main window is created, set main page for this ability 3339 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 3340 3341 windowStage.loadContent('pages/Index', (err) => { 3342 if (err.code) { 3343 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 3344 return; 3345 } 3346 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.'); 3347 }); 3348 } 3349 3350 onWindowStageDestroy(): void { 3351 // Main window is destroyed, release UI related resources 3352 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy'); 3353 } 3354 3355 onForeground(): void { 3356 // Ability has brought to foreground 3357 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); 3358 } 3359 3360 onBackground(): void { 3361 // Ability has back to background 3362 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground'); 3363 } 3364} 3365``` 3366 3367 ```ts 3368 // xxx.ets 3369 import { webview } from '@kit.ArkWeb'; 3370 import { BusinessError } from '@kit.BasicServicesKit'; 3371 3372 @Entry 3373 @Component 3374 struct WebComponent { 3375 @State embedStatus: string = ''; 3376 controller: webview.WebviewController = new webview.WebviewController(); 3377 3378 build() { 3379 Column() { 3380 // Default behavior: Click the button to navigate to a new page, close the index page, and destroy the same-layer tag. 3381 // Added in API version 12: When BFCache is enabled for the page that supports same-layer rendering, clicking the button navigates to a new page, closes the index page, and puts the same-layer tag into BFCache. 3382 Button('Destroy') 3383 .onClick(() => { 3384 try { 3385 this.controller.loadUrl("www.example.com"); 3386 } catch (error) { 3387 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3388 } 3389 }) 3390 3391 // Added in API version 12: When BFCache is enabled for the page that supports same-layer rendering, clicking the button to return to the page causes the same-layer tag to exit BFCache. 3392 Button('backward') 3393 .onClick(() => { 3394 try { 3395 this.controller.backward(); 3396 } catch (error) { 3397 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3398 } 3399 }) 3400 3401 // Added in API version 12: When BFCache is enabled for the page that supports same-layer rendering, clicking a button to advance to the next page causes the same-layer tag to enter BFCache. 3402 Button('forward') 3403 .onClick(() => { 3404 try { 3405 this.controller.forward(); 3406 } catch (error) { 3407 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 3408 } 3409 }) 3410 3411 3412 // Added in API version 12: The web kernel does not allow web pages loaded with non-HTTP and non-HTTPS protocols to enter BFCache. 3413 // Therefore, to test the ENTER_BFCACHE/LEAVE_BFCACHE states, you need to place the index.html on a web server and load it using the HTTP or HTTPS protocol. Example: 3414 // Web({ src: "http://xxxx/index.html", controller: this.controller }) 3415 Web({ src: $rawfile("index.html"), controller: this.controller }) 3416 .enableNativeEmbedMode(true) 3417 .onNativeEmbedLifecycleChange((event) => { 3418 // The Create event is triggered when the same-layer tag is detected on the loaded page. 3419 if (event.status == NativeEmbedStatus.CREATE) { 3420 this.embedStatus = 'Create'; 3421 } 3422 // The Update event is triggered when the same-layer tag on the page is moved or scaled. 3423 if (event.status == NativeEmbedStatus.UPDATE) { 3424 this.embedStatus = 'Update'; 3425 } 3426 // The Destroy event is triggered when a user exit the page. 3427 if (event.status == NativeEmbedStatus.DESTROY) { 3428 this.embedStatus = 'Destroy'; 3429 } 3430 // The Enter BFCache event is triggered when the page with the same-layer tag enters BFCache. 3431 if (event.status == NativeEmbedStatus.ENTER_BFCACHE) { 3432 this.embedStatus = 'Enter BFCache'; 3433 } 3434 // The Leave BFCache event is triggered when the page with the same-layer tag leaves BFCache. 3435 if (event.status == NativeEmbedStatus.LEAVE_BFCACHE) { 3436 this.embedStatus = 'Leave BFCache'; 3437 } 3438 console.log("status = " + this.embedStatus); 3439 console.log("surfaceId = " + event.surfaceId); 3440 console.log("embedId = " + event.embedId); 3441 if (event.info) { 3442 console.log("id = " + event.info.id); 3443 console.log("type = " + event.info.type); 3444 console.log("src = " + event.info.src); 3445 console.log("width = " + event.info.width); 3446 console.log("height = " + event.info.height); 3447 console.log("url = " + event.info.url); 3448 } 3449 }) 3450 } 3451 } 3452 } 3453 ``` 3454 3455 HTML file to be loaded: 3456 ```html 3457 <!-- index.html --> 3458 <!Document> 3459 <html> 3460 <head> 3461 <title>Same-Layer Rendering Test HTML</title> 3462 <meta name="viewport"> 3463 </head> 3464 <body> 3465 <div> 3466 <div id="bodyId"> 3467 <embed id="nativeButton" type = "native/button" width="800" height="800" src="test? params1=1?" style = "background-color:red"/> 3468 </div> 3469 </div> 3470 </body> 3471 </html> 3472 ``` 3473 3474## onNativeEmbedGestureEvent<sup>11+</sup> 3475 3476onNativeEmbedGestureEvent(callback: (event: NativeEmbedTouchInfo) => void) 3477 3478Triggered when a finger touches a same-layer tag. 3479 3480**System capability**: SystemCapability.Web.Webview.Core 3481 3482**Parameters** 3483 3484| Name | Type | Mandatory | Description | 3485| ------ | ------ | ---- | --------------------- | 3486| callback | (event: [NativeEmbedTouchInfo](./arkts-basic-components-web-i.md#nativeembedtouchinfo11)) => void | Yes| Callback invoked when a finger touches a same-layer tag.| 3487 3488**Example** 3489 3490 ```ts 3491 // xxx.ets 3492 import { webview } from '@kit.ArkWeb'; 3493 import { NodeController, BuilderNode, NodeRenderType, FrameNode, UIContext } from "@kit.ArkUI"; 3494 3495 declare class Params { 3496 text: string; 3497 width: number; 3498 height: number; 3499 } 3500 3501 declare class NodeControllerParams { 3502 surfaceId: string; 3503 renderType: NodeRenderType; 3504 width: number; 3505 height: number; 3506 } 3507 3508 class MyNodeController extends NodeController { 3509 private rootNode: BuilderNode<[Params]> | undefined | null; 3510 private surfaceId_: string = ""; 3511 private renderType_: NodeRenderType = NodeRenderType.RENDER_TYPE_DISPLAY; 3512 private width_: number = 0; 3513 private height_: number = 0; 3514 3515 setRenderOption(params: NodeControllerParams) { 3516 this.surfaceId_ = params.surfaceId; 3517 this.renderType_ = params.renderType; 3518 this.width_ = params.width; 3519 this.height_ = params.height; 3520 } 3521 3522 makeNode(uiContext: UIContext): FrameNode | null { 3523 this.rootNode = new BuilderNode(uiContext, { surfaceId: this.surfaceId_, type: this.renderType_ }); 3524 this.rootNode.build(wrapBuilder(ButtonBuilder), { text: "myButton", width: this.width_, height: this.height_ }); 3525 return this.rootNode.getFrameNode(); 3526 } 3527 3528 postEvent(event: TouchEvent | undefined): boolean { 3529 return this.rootNode?.postTouchEvent(event) as boolean; 3530 } 3531 } 3532 3533 @Component 3534 struct ButtonComponent { 3535 @Prop params: Params; 3536 @State bkColor: Color = Color.Red; 3537 3538 build() { 3539 Column() { 3540 Button(this.params.text) 3541 .height(50) 3542 .width(200) 3543 .border({ width: 2, color: Color.Red }) 3544 .backgroundColor(this.bkColor) 3545 3546 } 3547 .width(this.params.width) 3548 .height(this.params.height) 3549 } 3550 } 3551 3552 @Builder 3553 function ButtonBuilder(params: Params) { 3554 ButtonComponent({ params: params }) 3555 .backgroundColor(Color.Green) 3556 } 3557 3558 @Entry 3559 @Component 3560 struct WebComponent { 3561 @State eventType: string = ''; 3562 controller: webview.WebviewController = new webview.WebviewController(); 3563 private nodeController: MyNodeController = new MyNodeController(); 3564 uiContext: UIContext = this.getUIContext(); 3565 3566 build() { 3567 Column() { 3568 Stack() { 3569 NodeContainer(this.nodeController) 3570 Web({ src: $rawfile("index.html"), controller: this.controller }) 3571 .enableNativeEmbedMode(true) 3572 .onNativeEmbedLifecycleChange((embed) => { 3573 if (embed.status == NativeEmbedStatus.CREATE) { 3574 this.nodeController.setRenderOption({ 3575 surfaceId: embed.surfaceId as string, 3576 renderType: NodeRenderType.RENDER_TYPE_TEXTURE, 3577 width: this.uiContext!.px2vp(embed.info?.width), 3578 height: this.uiContext!.px2vp(embed.info?.height) 3579 }); 3580 this.nodeController.rebuild(); 3581 } 3582 }) 3583 .onNativeEmbedGestureEvent((event) => { 3584 if (event && event.touchEvent) { 3585 if (event.touchEvent.type == TouchType.Down) { 3586 this.eventType = 'Down' 3587 } 3588 if (event.touchEvent.type == TouchType.Up) { 3589 this.eventType = 'Up' 3590 } 3591 if (event.touchEvent.type == TouchType.Move) { 3592 this.eventType = 'Move' 3593 } 3594 if (event.touchEvent.type == TouchType.Cancel) { 3595 this.eventType = 'Cancel' 3596 } 3597 let ret = this.nodeController.postEvent(event.touchEvent) 3598 if (event.result) { 3599 event.result.setGestureEventResult(ret, true); 3600 } 3601 console.log("embedId = " + event.embedId); 3602 console.log("touchType = " + this.eventType); 3603 console.log("x = " + event.touchEvent.touches[0].x); 3604 console.log("y = " + event.touchEvent.touches[0].y); 3605 console.log("Component globalPos:(" + event.touchEvent.target.area.globalPosition.x + "," + event.touchEvent.target.area.globalPosition.y + ")"); 3606 console.log("width = " + event.touchEvent.target.area.width); 3607 console.log("height = " + event.touchEvent.target.area.height); 3608 } 3609 }) 3610 } 3611 } 3612 } 3613 } 3614 ``` 3615HTML file to be loaded: 3616 ```html 3617 <!-- index.html --> 3618 <!Document> 3619 <html> 3620 <head> 3621 <title>Same-Layer Rendering Test HTML</title> 3622 <meta name="viewport"> 3623 </head> 3624 <body> 3625 <div> 3626 <div id="bodyId"> 3627 <embed id="nativeButton" type = "native/button" width="800" height="800" src="test?params1=1?" style = "background-color:red"/> 3628 </div> 3629 </div> 3630 </body> 3631 </html> 3632 ``` 3633 3634## onIntelligentTrackingPreventionResult<sup>12+</sup> 3635 3636onIntelligentTrackingPreventionResult(callback: OnIntelligentTrackingPreventionCallback) 3637 3638Triggered when the intelligent tracking prevention feature is enabled and the tracker cookie is blocked. 3639 3640**System capability**: SystemCapability.Web.Webview.Core 3641 3642**Parameters** 3643 3644| Name | Type | Mandatory | Description | 3645| ------ | ------ | ---- | --------------------- | 3646| callback | [OnIntelligentTrackingPreventionCallback](./arkts-basic-components-web-t.md#onintelligenttrackingpreventioncallback12) | Yes| Callback invoked when the intelligent tracking prevention feature is enabled and the tracker cookie is blocked.| 3647 3648**Example** 3649 3650 ```ts 3651 // xxx.ets 3652 import { webview } from '@kit.ArkWeb'; 3653 import { BusinessError } from '@kit.BasicServicesKit'; 3654 3655 @Entry 3656 @Component 3657 struct WebComponent { 3658 controller: webview.WebviewController = new webview.WebviewController(); 3659 3660 build() { 3661 Column() { 3662 // The onIntelligentTrackingPreventionResult callback is triggered only when the intelligent tracking prevention feature is enabled. 3663 Button('enableIntelligentTrackingPrevention') 3664 .onClick(() => { 3665 try { 3666 this.controller.enableIntelligentTrackingPrevention(true); 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 .onIntelligentTrackingPreventionResult((details) => { 3673 console.log("onIntelligentTrackingPreventionResult: [websiteHost]= " + details.host + 3674 ", [trackerHost]=" + details.trackerHost); 3675 }) 3676 } 3677 } 3678 } 3679 ``` 3680 3681## onOverrideUrlLoading<sup>12+</sup> 3682 3683onOverrideUrlLoading(callback: OnOverrideUrlLoadingCallback) 3684 3685Triggered to enable the host application to obtain control when the URL is about to be loaded to this **Web** component. If the callback returns **true**, the **Web** component stops loading the URL. If the callback returns **false**, the **Web** component continues to load the URL. 3686 3687POST requests do not trigger this callback. 3688 3689This callback is triggered when an **iframe** loads the redirection of a non-HTTP(s) protocol, but is not triggered when an **iframe** loads the HTTP(s) protocol or **about:blank** or for the redirection triggered by **loadUrl(String)**. 3690 3691Do not use the same URL to call the **loadUrl(String)** API and then return **true**. Doing so would unnecessarily cancel the current loading and start a new load with the same URL. The correct way to continue loading the given URL is to simply return **false**, rather than calling **loadUrl(String)**. 3692 3693**System capability**: SystemCapability.Web.Webview.Core 3694 3695**Parameters** 3696 3697| Name | Type | Mandatory | Description | 3698| ------ | ------ | ---- | --------------------- | 3699| callback | [OnOverrideUrlLoadingCallback](./arkts-basic-components-web-t.md#onoverrideurlloadingcallback12) | Yes| Callback for **onOverrideUrlLoading**.| 3700 3701**Example** 3702 3703 ```ts 3704 // xxx.ets 3705 import { webview } from '@kit.ArkWeb'; 3706 3707 @Entry 3708 @Component 3709 struct WebComponent { 3710 controller: webview.WebviewController = new webview.WebviewController(); 3711 3712 build() { 3713 Column() { 3714 Web({ src: $rawfile("index.html"), controller: this.controller }) 3715 .onOverrideUrlLoading((webResourceRequest: WebResourceRequest) => { 3716 if (webResourceRequest && webResourceRequest.getRequestUrl() == "about:blank") { 3717 return true; 3718 } 3719 return false; 3720 }) 3721 } 3722 } 3723 } 3724 ``` 3725 3726 HTML file to be loaded: 3727 ```html 3728 <!--index.html--> 3729 <!DOCTYPE html> 3730 <html> 3731 <head> 3732 <title>Test Web Page</title> 3733 </head> 3734 <body> 3735 <h1>onOverrideUrlLoading Demo</h1> 3736 <a href="about:blank">Click here</a>// to visit about:blank. 3737 </body> 3738 </html> 3739 ``` 3740 3741## onViewportFitChanged<sup>12+</sup> 3742 3743onViewportFitChanged(callback: OnViewportFitChangedCallback) 3744 3745Triggered when the **viewport-fit** configuration in the web page's **meta** tag changes. The application can adapt its layout to the viewport within this callback. 3746 3747**System capability**: SystemCapability.Web.Webview.Core 3748 3749**Parameters** 3750 3751| Name | Type | Mandatory | Description | 3752| ------ | ------ | ---- | --------------------- | 3753| callback | [OnViewportFitChangedCallback](./arkts-basic-components-web-t.md#onviewportfitchangedcallback12) | Yes| Callback invoked when the **viewport-fit** configuration in the web page's **meta** tag changes.| 3754 3755**Example** 3756 3757 ```ts 3758 // xxx.ets 3759 import { webview } from '@kit.ArkWeb'; 3760 3761 @Entry 3762 @Component 3763 struct WebComponent { 3764 controller: webview.WebviewController = new webview.WebviewController(); 3765 3766 build() { 3767 Column() { 3768 Web({ src: $rawfile('index.html'), controller: this.controller }) 3769 .onViewportFitChanged((data) => { 3770 let jsonData = JSON.stringify(data); 3771 let viewportFit: ViewportFit = JSON.parse(jsonData).viewportFit; 3772 if (viewportFit === ViewportFit.COVER) { 3773 // The index.html web page supports immersive layout. You can call expandSafeArea to adjust the Web component layout viewport to cover the safe area (status bar or navigation bar). 3774 } else if (viewportFit === ViewportFit.CONTAINS) { 3775 // The index.html web page does not support immersive layout. You can call expandSafeArea to adjust the Web component layout viewport as a safe area. 3776 } else { 3777 // Default value. No processing is required. 3778 } 3779 }) 3780 } 3781 } 3782 } 3783 ``` 3784 3785 HTML file to be loaded: 3786 ```html 3787 <!-- index.html --> 3788 <!DOCTYPE html> 3789 <html> 3790 <head> 3791 <meta name="viewport" content="width=device-width,viewport-fit=cover"> 3792 </head> 3793 <body> 3794 <div style="position: absolute; bottom: 0; margin-bottom: env(safe-area-inset-bottom)"></div> 3795 </body> 3796 </html> 3797 ``` 3798 3799## onInterceptKeyboardAttach<sup>12+</sup> 3800 3801onInterceptKeyboardAttach(callback: WebKeyboardCallback) 3802 3803Triggered before any editable element (such as the **input** tag) on the web page invokes the soft keyboard. The application can use this API to intercept the display of the system's soft keyboard and configure a custom soft keyboard. (With this API, the application can determine whether to use the system's default soft keyboard, a system soft keyboard with a custom Enter key, or a completely application-defined soft keyboard). 3804 3805**System capability**: SystemCapability.Web.Webview.Core 3806 3807**Parameters** 3808 3809| Name | Type | Mandatory | Description | 3810| ------ | ------ | ---- | --------------------- | 3811| callback | [WebKeyboardCallback](./arkts-basic-components-web-t.md#webkeyboardcallback12) | Yes| Callback invoked for intercepting the soft keyboard started by the web page.| 3812 3813**Example** 3814 3815 ```ts 3816 // xxx.ets 3817 import { webview } from '@kit.ArkWeb'; 3818 import { inputMethodEngine } from '@kit.IMEKit'; 3819 3820 @Entry 3821 @Component 3822 struct WebComponent { 3823 controller: webview.WebviewController = new webview.WebviewController(); 3824 webKeyboardController: WebKeyboardController = new WebKeyboardController() 3825 inputAttributeMap: Map<string, number> = new Map([ 3826 ['UNSPECIFIED', inputMethodEngine.ENTER_KEY_TYPE_UNSPECIFIED], 3827 ['GO', inputMethodEngine.ENTER_KEY_TYPE_GO], 3828 ['SEARCH', inputMethodEngine.ENTER_KEY_TYPE_SEARCH], 3829 ['SEND', inputMethodEngine.ENTER_KEY_TYPE_SEND], 3830 ['NEXT', inputMethodEngine.ENTER_KEY_TYPE_NEXT], 3831 ['DONE', inputMethodEngine.ENTER_KEY_TYPE_DONE], 3832 ['PREVIOUS', inputMethodEngine.ENTER_KEY_TYPE_PREVIOUS] 3833 ]) 3834 3835 /** 3836 * Builder for a custom keyboard component. 3837 */ 3838 @Builder 3839 customKeyboardBuilder() { 3840 // Implement a custom keyboard component and connect it to WebKeyboardController to implement operations such as input, deletion, and close. 3841 Row() { 3842 Text("Finish") 3843 .fontSize(20) 3844 .fontColor(Color.Blue) 3845 .onClick(() => { 3846 this.webKeyboardController.close(); 3847 }) 3848 // Insert characters. 3849 Button("insertText").onClick(() => { 3850 this.webKeyboardController.insertText('insert '); 3851 }).margin({ 3852 bottom: 200, 3853 }) 3854 // Delete characters from the end to the beginning for the length specified by the length parameter. 3855 Button("deleteForward").onClick(() => { 3856 this.webKeyboardController.deleteForward(1); 3857 }).margin({ 3858 bottom: 200, 3859 }) 3860 // Delete characters from the beginning to the end for the length specified by the length parameter. 3861 Button("deleteBackward").onClick(() => { 3862 this.webKeyboardController.deleteBackward(1); 3863 }).margin({ 3864 left: -220, 3865 }) 3866 // Insert a function key. 3867 Button("sendFunctionKey").onClick(() => { 3868 this.webKeyboardController.sendFunctionKey(6); 3869 }) 3870 } 3871 } 3872 3873 build() { 3874 Column() { 3875 Web({ src: $rawfile('index.html'), controller: this.controller }) 3876 .onInterceptKeyboardAttach((KeyboardCallbackInfo) => { 3877 // Initialize option. By default, the default keyboard is used. 3878 let option: WebKeyboardOptions = { 3879 useSystemKeyboard: true, 3880 }; 3881 if (!KeyboardCallbackInfo) { 3882 return option; 3883 } 3884 3885 // Save the WebKeyboardController. When a custom keyboard is used, this handler is required to control behaviors such as input, deletion, and closing of the keyboard. 3886 this.webKeyboardController = KeyboardCallbackInfo.controller 3887 let attributes: Record<string, string> = KeyboardCallbackInfo.attributes 3888 // Traverse attributes. 3889 let attributeKeys = Object.keys(attributes) 3890 for (let i = 0; i < attributeKeys.length; i++) { 3891 console.log('WebCustomKeyboard key = ' + attributeKeys[i] + ', value = ' + attributes[attributeKeys[i]]) 3892 } 3893 3894 if (attributes) { 3895 if (attributes['data-keyboard'] == 'customKeyboard') { 3896 // Determine the soft keyboard to use based on the attributes of editable HTML elements. For example, if the attribute includes data-keyboard and its value is customKeyboard, custom keyboard is used. 3897 console.log('WebCustomKeyboard use custom keyboard') 3898 option.useSystemKeyboard = false; 3899 // Set the custom keyboard builder. 3900 option.customKeyboard = () => { 3901 this.customKeyboardBuilder() 3902 } 3903 return option; 3904 } 3905 3906 if (attributes['keyboard-return'] != undefined) { 3907 // Determine the soft keyboard to use based on the attributes of editable HTML elements. For example, if the attribute includes keyboard-return, use the system keyboard and specify the type of the system soft keyboard's Enter key. 3908 option.useSystemKeyboard = true; 3909 let enterKeyType: number | undefined = this.inputAttributeMap.get(attributes['keyboard-return']) 3910 if (enterKeyType != undefined) { 3911 option.enterKeyType = enterKeyType 3912 } 3913 return option; 3914 } 3915 } 3916 3917 return option; 3918 }) 3919 } 3920 } 3921 } 3922 ``` 3923 3924 HTML file to be loaded: 3925 ```html 3926 <!-- index.html --> 3927 <!DOCTYPE html> 3928 <html> 3929 3930 <head> 3931 <meta charset="utf-8"> 3932 <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0"> 3933 </head> 3934 3935 <body> 3936 3937 <p style="font-size:12px">input tag. Original default behavior: </p> 3938 <input type="text" style="width: 300px; height: 20px"><br> 3939 <hr style="height:2px;border-width:0;color:gray;background-color:gray"> 3940 3941 <p style="font-size:12px">input tag. System keyboard with enterKeyType as UNSPECIFIED: </p> 3942 <input type="text" keyboard-return="UNSPECIFIED" style="width: 300px; height: 20px"><br> 3943 <hr style="height:2px;border-width:0;color:gray;background-color:gray"> 3944 3945 <p style="font-size:12px">input tag. System keyboard with enterKeyType as GO: </p> 3946 <input type="text" keyboard-return="GO" style="width: 300px; height: 20px"><br> 3947 <hr style="height:2px;border-width:0;color:gray;background-color:gray"> 3948 3949 <p style="font-size:12px">input tag. System keyboard with enterKeyType as SEARCH: </p> 3950 <input type="text" keyboard-return="SEARCH" style="width: 300px; height: 20px"><br> 3951 <hr style="height:2px;border-width:0;color:gray;background-color:gray"> 3952 3953 <p style="font-size:12px">input tag. System keyboard with enterKeyType as SEND: </p> 3954 <input type="text" keyboard-return="SEND" style="width: 300px; height: 20px"><br> 3955 <hr style="height:2px;border-width:0;color:gray;background-color:gray"> 3956 3957 <p style="font-size:12px">input tag. System keyboard with enterKeyType as NEXT: </p> 3958 <input type="text" keyboard-return="NEXT" style="width: 300px; height: 20px"><br> 3959 <hr style="height:2px;border-width:0;color:gray;background-color:gray"> 3960 3961 <p style="font-size:12px">input tag. System keyboard with enterKeyType as DONE: </p> 3962 <input type="text" keyboard-return="DONE" style="width: 300px; height: 20px"><br> 3963 <hr style="height:2px;border-width:0;color:gray;background-color:gray"> 3964 3965 <p style="font-size:12px">input tag. System keyboard with enterKeyType as PREVIOUS: </p> 3966 <input type="text" keyboard-return="PREVIOUS" style="width: 300px; height: 20px"><br> 3967 <hr style="height:2px;border-width:0;color:gray;background-color:gray"> 3968 3969 <p style="font-size:12px">input tag. Custom keyboard: </p> 3970 <input type="text" data-keyboard="customKeyboard" style="width: 300px; height: 20px"><br> 3971 3972 </body> 3973 3974 </html> 3975 ``` 3976 3977## onNativeEmbedVisibilityChange<sup>12+</sup> 3978 3979onNativeEmbedVisibilityChange(callback: OnNativeEmbedVisibilityChangeCallback) 3980 3981Triggered when the visibility of a same-layer tag (such as an **Embed** tag or an **Object** tag) on a web page changes in the viewport. Same-layer tags are invisible by default. If a tag is visible when the page is loaded for the first time, it is reported. If a tag is invisible, it is not reported. Same-layer tags are considered invisible only when they are all invisible. Partially visible or all visible tags are considered visible. To obtain the visible status change caused by the CSS attributes (including visibility, display, and size change) of the same-layer tag, configure [nativeEmbedOptions](./arkts-basic-components-web-attributes.md#nativeembedoptions16) and set **supportCssDisplayChange** in [EmbedOptions](./arkts-basic-components-web-i.md#embedoptions16) to **true**. 3982 3983**System capability**: SystemCapability.Web.Webview.Core 3984 3985**Parameters** 3986 3987| Name | Type | Mandatory | Description | 3988| ------ | ------ | ---- | --------------------- | 3989| callback | [OnNativeEmbedVisibilityChangeCallback](./arkts-basic-components-web-t.md#onnativeembedvisibilitychangecallback12) | Yes| Callback invoked when the visibility of a same-layer tag changes.| 3990 3991**Example** 3992 3993 ```ts 3994 // xxx.ets 3995 import { webview } from '@kit.ArkWeb'; 3996 import { NodeController, BuilderNode, NodeRenderType, FrameNode, UIContext } from "@kit.ArkUI"; 3997 3998 declare class Params { 3999 text: string; 4000 width: number; 4001 height: number; 4002 } 4003 4004 declare class NodeControllerParams { 4005 surfaceId: string; 4006 renderType: NodeRenderType; 4007 width: number; 4008 height: number; 4009 } 4010 4011 class MyNodeController extends NodeController { 4012 private rootNode: BuilderNode<[Params]> | undefined | null; 4013 private surfaceId_: string = ""; 4014 private renderType_: NodeRenderType = NodeRenderType.RENDER_TYPE_DISPLAY; 4015 private width_: number = 0; 4016 private height_: number = 0; 4017 4018 setRenderOption(params: NodeControllerParams) { 4019 this.surfaceId_ = params.surfaceId; 4020 this.renderType_ = params.renderType; 4021 this.width_ = params.width; 4022 this.height_ = params.height; 4023 } 4024 4025 makeNode(uiContext: UIContext): FrameNode | null { 4026 this.rootNode = new BuilderNode(uiContext, { surfaceId: this.surfaceId_, type: this.renderType_ }); 4027 this.rootNode.build(wrapBuilder(ButtonBuilder), { text: "myButton", width: this.width_, height: this.height_ }); 4028 return this.rootNode.getFrameNode(); 4029 } 4030 4031 postEvent(event: TouchEvent | undefined): boolean { 4032 return this.rootNode?.postTouchEvent(event) as boolean; 4033 } 4034 } 4035 4036 @Component 4037 struct ButtonComponent { 4038 @Prop params: Params; 4039 @State bkColor: Color = Color.Red; 4040 4041 build() { 4042 Column() { 4043 Button(this.params.text) 4044 .height(50) 4045 .width(200) 4046 .border({ width: 2, color: Color.Red }) 4047 .backgroundColor(this.bkColor) 4048 4049 } 4050 .width(this.params.width) 4051 .height(this.params.height) 4052 } 4053 } 4054 4055 @Builder 4056 function ButtonBuilder(params: Params) { 4057 ButtonComponent({ params: params }) 4058 .backgroundColor(Color.Green) 4059 } 4060 4061 @Entry 4062 @Component 4063 struct WebComponent { 4064 @State embedVisibility: string = ''; 4065 controller: webview.WebviewController = new webview.WebviewController(); 4066 private nodeController: MyNodeController = new MyNodeController(); 4067 uiContext: UIContext = this.getUIContext(); 4068 4069 build() { 4070 Column() { 4071 Stack() { 4072 NodeContainer(this.nodeController) 4073 Web({ src: $rawfile("index.html"), controller: this.controller }) 4074 .enableNativeEmbedMode(true) 4075 .onNativeEmbedLifecycleChange((embed) => { 4076 if (embed.status == NativeEmbedStatus.CREATE) { 4077 this.nodeController.setRenderOption({ 4078 surfaceId: embed.surfaceId as string, 4079 renderType: NodeRenderType.RENDER_TYPE_TEXTURE, 4080 width: this.uiContext!.px2vp(embed.info?.width), 4081 height: this.uiContext!.px2vp(embed.info?.height) 4082 }); 4083 this.nodeController.rebuild(); 4084 } 4085 }) 4086 .onNativeEmbedVisibilityChange((embed) => { 4087 if (embed.visibility) { 4088 this.embedVisibility = 'Visible'; 4089 } else { 4090 this.embedVisibility = 'Hidden'; 4091 } 4092 console.log("embedId = " + embed.embedId); 4093 console.log("visibility = " + embed.visibility); 4094 }) 4095 } 4096 } 4097 } 4098 } 4099 ``` 4100 4101 HTML file to be loaded: 4102 ```html 4103 <!-- index.html --> 4104 <!DOCTYPE html> 4105 <html> 4106 <head> 4107 <title>Same-Layer Rendering Test HTML</title> 4108 <meta name="viewport"> 4109 </head> 4110 <body> 4111 <div> 4112 <div id="bodyId"> 4113 <embed id="nativeButton" type = "native/button" width="800" height="800" src="test?params1=1?" style = "background-color:red"/> 4114 </div> 4115 </div> 4116 </body> 4117 </html> 4118 ``` 4119 4120## onNativeEmbedMouseEvent<sup>20+</sup> 4121 4122onNativeEmbedMouseEvent(callback: MouseInfoCallback) 4123 4124Callback triggered when the following operations are performed on the same-layer tag: 4125 4126- Tapping or holding with the left, middle, or right mouse button. 4127- Tapping or holding the left, middle, or right mouse button using the touchpad. 4128 4129 4130**System capability**: SystemCapability.Web.Webview.Core 4131 4132**Parameters** 4133 4134| Name | Type | Mandatory | Description | 4135| ------ | ------ | ---- | --------------------- | 4136| callback | [MouseInfoCallback](./arkts-basic-components-web-t.md#mouseinfocallback20) | Yes| Callback triggered when a same-layer tag is clicked using the mouse or touchpad.| 4137 4138**Example** 4139 4140 ```ts 4141 // xxx.ets 4142 import { webview } from '@kit.ArkWeb'; 4143 import { NodeController, BuilderNode, NodeRenderType, FrameNode, UIContext } from "@kit.ArkUI"; 4144 4145 declare class Params { 4146 text: string; 4147 width: number; 4148 height: number; 4149 } 4150 4151 declare class NodeControllerParams { 4152 surfaceId: string; 4153 renderType: NodeRenderType; 4154 width: number; 4155 height: number; 4156 } 4157 4158 class MyNodeController extends NodeController { 4159 private rootNode: BuilderNode<[Params]> | undefined | null; 4160 private surfaceId_: string = ""; 4161 private renderType_: NodeRenderType = NodeRenderType.RENDER_TYPE_DISPLAY; 4162 private width_: number = 0; 4163 private height_: number = 0; 4164 4165 setRenderOption(params: NodeControllerParams) { 4166 this.surfaceId_ = params.surfaceId; 4167 this.renderType_ = params.renderType; 4168 this.width_ = params.width; 4169 this.height_ = params.height; 4170 } 4171 4172 makeNode(uiContext: UIContext): FrameNode | null { 4173 this.rootNode = new BuilderNode(uiContext, { surfaceId: this.surfaceId_, type: this.renderType_ }); 4174 this.rootNode.build(wrapBuilder(ButtonBuilder), { text: "myButton", width: this.width_, height: this.height_ }); 4175 return this.rootNode.getFrameNode(); 4176 } 4177 4178 postInputEvent(event: TouchEvent | MouseEvent | undefined): boolean { 4179 return this.rootNode?.postInputEvent(event) as boolean; 4180 } 4181 } 4182 4183 @Component 4184 struct ButtonComponent { 4185 @Prop params: Params; 4186 @State bkColor: Color = Color.Red; 4187 4188 build() { 4189 Column() { 4190 Button(this.params.text) 4191 .height(50) 4192 .width(200) 4193 .border({ width: 2, color: Color.Red }) 4194 .backgroundColor(this.bkColor) 4195 4196 } 4197 .width(this.params.width) 4198 .height(this.params.height) 4199 } 4200 } 4201 4202 @Builder 4203 function ButtonBuilder(params: Params) { 4204 ButtonComponent({ params: params }) 4205 .backgroundColor(Color.Green) 4206 } 4207 4208 @Entry 4209 @Component 4210 struct WebComponent { 4211 @State mouseAction: string = ''; 4212 @State mouseButton: string = ''; 4213 controller: webview.WebviewController = new webview.WebviewController(); 4214 private nodeController: MyNodeController = new MyNodeController(); 4215 uiContext: UIContext = this.getUIContext(); 4216 4217 build() { 4218 Column() { 4219 Stack() { 4220 NodeContainer(this.nodeController) 4221 Web({ src: $rawfile("index.html"), controller: this.controller }) 4222 .enableNativeEmbedMode(true) 4223 .onNativeEmbedLifecycleChange((embed) => { 4224 if (embed.status == NativeEmbedStatus.CREATE) { 4225 this.nodeController.setRenderOption({ 4226 surfaceId: embed.surfaceId as string, 4227 renderType: NodeRenderType.RENDER_TYPE_TEXTURE, 4228 width: this.uiContext!.px2vp(embed.info?.width), 4229 height: this.uiContext!.px2vp(embed.info?.height) 4230 }); 4231 this.nodeController.rebuild(); 4232 } 4233 }) 4234 .onNativeEmbedMouseEvent((event) => { 4235 if (event && event.mouseEvent) { 4236 let ret = this.nodeController.postInputEvent(event.mouseEvent) 4237 if (event.result) { 4238 event.result.setMouseEventResult(ret, true); 4239 } 4240 } 4241 }) 4242 } 4243 } 4244 } 4245 } 4246 ``` 4247HTML file to be loaded: 4248 ```html 4249 <!-- index.html --> 4250 <!Document> 4251 <html> 4252 <head> 4253 <title>Same-Layer Rendering Test</title> 4254 <meta name="viewport"> 4255 </head> 4256 <body> 4257 <div> 4258 <div id="bodyId"> 4259 <embed id="nativeButton" type ="native/button" width="800" height="800" style="background-color:red"/> 4260 </div> 4261 </div> 4262 </body> 4263 </html> 4264 ``` 4265 4266## onOverrideErrorPage<sup>20+</sup> 4267 4268onOverrideErrorPage(callback: OnOverrideErrorPageCallback) 4269 4270Triggered when an error occurs during web page loading of main resources. You can use this API to customize the error display page. 4271 4272In addition, this feature takes effect only after the default error page is enabled by calling the [setErrorPageEnabled](./arkts-apis-webview-WebviewController.md#seterrorpageenabled20) API. 4273 4274**System capability**: SystemCapability.Web.Webview.Core 4275 4276**Parameters** 4277 4278| Name | Type | Mandatory | Description | 4279| ------- | ---------------------------------------- | ---- | --------------- | 4280| callback | [OnOverrideErrorPageCallback](./arkts-basic-components-web-t.md#onoverrideerrorpagecallback20) | Yes | Callback triggered when an error occurs during web page loading. | 4281 4282**Example** 4283 4284 ```ts 4285// xxx.ets 4286import { webview } from '@kit.ArkWeb'; 4287@Entry 4288@Component 4289struct WebComponent { 4290 controller: webview.WebviewController = new webview.WebviewController(); 4291 build() { 4292 Column() { 4293 Web({ src: "www.error-test.com", controller: this.controller }) 4294 .onControllerAttached(() => { 4295 this.controller.setErrorPageEnabled(true); 4296 if (!this.controller.getErrorPageEnabled()) { 4297 this.controller.setErrorPageEnabled(true); 4298 } 4299 }) 4300 .onOverrideErrorPage(event => { 4301 let htmlStr = "<html><h1>error occur : "; 4302 htmlStr += event.error.getErrorCode(); 4303 htmlStr += "</h1></html>"; 4304 return htmlStr; 4305 }) 4306 } 4307 } 4308} 4309 ``` 4310 4311## onSslErrorReceive<sup>(deprecated)</sup> 4312 4313onSslErrorReceive(callback: (event?: { handler: Function, error: object }) => void) 4314 4315Triggered when an SSL error occurs during resource loading. 4316 4317> **NOTE** 4318> 4319> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [onSslErrorEventReceive<sup>9+</sup>](#onsslerroreventreceive9) instead. 4320 4321**System capability**: SystemCapability.Web.Webview.Core 4322 4323## onFileSelectorShow<sup>(deprecated)</sup> 4324 4325onFileSelectorShow(callback: (event?: { callback: Function, fileSelector: object }) => void) 4326 4327Triggered to process an HTML form whose input type is **file**, in response to the tapping of the **Select File** button. 4328 4329> **NOTE** 4330> 4331> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [onShowFileSelector<sup>9+</sup>](#onshowfileselector9) instead. 4332 4333**System capability**: SystemCapability.Web.Webview.Core 4334 4335## onUrlLoadIntercept<sup>(deprecated)</sup> 4336 4337onUrlLoadIntercept(callback: (event?: { data:string | WebResourceRequest }) => boolean) 4338 4339Triggered when the **Web** component is about to access a URL. This API is used to determine whether to block the access. 4340This API is deprecated since API version 10. You are advised to use [onLoadIntercept<sup>10+</sup>](#onloadintercept10) instead. 4341 4342**System capability**: SystemCapability.Web.Webview.Core 4343 4344**Parameters** 4345 4346| Name | Type | Mandatory | Description | 4347| ------ | ------ | ---- | --------------------- | 4348| callback | (event?: { data:string \| [WebResourceRequest](./arkts-basic-components-web-WebResourceRequest.md) }) => boolean | Yes| URL information.<br>The return value is of the Boolean type. If **true** is returned, the access is blocked. Otherwise, the access is allowed.| 4349 4350**Example** 4351 4352 ```ts 4353 // xxx.ets 4354 import { webview } from '@kit.ArkWeb'; 4355 4356 @Entry 4357 @Component 4358 struct WebComponent { 4359 controller: webview.WebviewController = new webview.WebviewController(); 4360 4361 build() { 4362 Column() { 4363 Web({ src: 'www.example.com', controller: this.controller }) 4364 .onUrlLoadIntercept((event) => { 4365 if (event) { 4366 console.log('onUrlLoadIntercept ' + event.data.toString()); 4367 } 4368 return true 4369 }) 4370 } 4371 } 4372 } 4373 ``` 4374