1# AtomicServiceWeb
2
3**AtomicServiceWeb** is an advanced web component offering customization to meet specific demands. It shields irrelevant APIs from the native **Web** component and extends functionality through JavaScript capabilities.
4
5> **NOTE**
6>
7> - This component is supported since API version 12. Updates will be marked with a superscript to indicate their earliest API version.
8> - You can preview how this component looks on a real device, but not in DevEco Studio Previewer.
9
10## Required Permissions
11
12**ohos.permission.INTERNET**, required for accessing online web pages. For details about how to apply for a permission, see [Declaring Permissions](../../../security/AccessToken/declare-permissions.md).
13
14## Modules to Import
15
16```
17import { AtomicServiceWeb } from '@kit.ArkUI';
18```
19
20## Child Components
21
22Not supported
23
24## Attributes
25
26The [universal attributes](ts-universal-attributes-size.md) are not supported.
27
28## AtomicServiceWeb
29
30```
31AtomicServiceWeb({
32  src: ResourceStr,
33  controller: AtomicServiceWebController,
34  navPathStack?: NavPathStack,
35  mixedMode?: MixedMode,
36  darkMode?: WebDarkMode,
37  forceDarkAccess?: boolean,
38  onMessage?: Callback<OnMessageEvent>,
39  onErrorReceive?: Callback<OnErrorReceiveEvent>,
40  onHttpErrorReceive?: Callback<OnHttpErrorReceiveEvent>,
41  onPageBegin?: Callback<OnPageBeginEvent>,
42  onPageEnd?: Callback<OnPageEndEvent>,
43  onControllerAttached?: Callback<void>,
44  onLoadIntercept?: Callback<OnLoadInterceptEvent, boolean>,
45  onProgressChange?: Callback<OnProgressChangeEvent>
46})
47```
48
49**Decorator**: @Component
50
51**Atomic service API**: This API can be used in atomic services since API version 12.
52
53**System capability**: SystemCapability.ArkUI.ArkUI.Full
54
55**Parameters**
56
57| Name                  | Type                                                                                                              | Mandatory| Decorator      | Description                                                                                                                 |
58|----------------------|------------------------------------------------------------------------------------------------------------------|----|-------------|----------------------------------------------------------------------------------------------------------------------|
59| src                  | [ResourceStr](ts-types.md#resourcestr)                                                                           | Yes | -           | Web page resource address. Accessing network resources requires configuring service domain names in AppGallery Connect, and accessing local resources only supports files within the package (**$rawfile**). Dynamic updating of the address through state variables (for example, @State) is not supported. The loaded web page supports calling system capabilities through the APIs provided by the JS SDK, with the specifics governed by the JS SDK.|
60| controller           | [AtomicServiceWebController](#atomicservicewebcontroller)                                                        | Yes | @ObjectLink | Controller for controlling the behavior of the **AtomicServiceWeb** component.                                                             |
61| navPathStack         | [NavPathStack](ts-basic-components-navigation.md#navpathstack10)                                                 | No | -           | Information about the navigation stack. When **NavDestination** serves as the root container of the page, **NavPathStack** corresponding to the **NavDestination** container must be passed to handle page routing.                                          |
62| mixedMode            | [MixedMode](../../apis-arkweb/ts-basic-components-web.md#mixedmode)                                          | No | @Prop       | Whether to enable loading of HTTP and HTTPS mixed content. By default, this feature is disabled.                                                   |
63| darkMode             | [WebDarkMode](../../apis-arkweb/ts-basic-components-web.md#webdarkmode9)                                     | No | @Prop       | Web dark mode. By default, web dark mode is disabled.                                                                                                     |
64| forceDarkAccess      | boolean                                                                                                          | No | @Prop       | Whether to enable forcible dark mode for the web page. This feature is disabled by default. This API is effective only when web dark mode is enabled.                                                                         |
65| onMessage            | Callback\<[OnMessageEvent](#onmessageevent)\>                                                                    | No | -           | Callback invoked when the HTML5 page sends a message through the **postMessage()** API of the JS SDK, and the **AtomicServiceWeb** component's corresponding page is returned or destroyed.                                                             |
66| onErrorReceive       | Callback\<[OnErrorReceiveEvent](#onerrorreceiveevent)\>                                                          | No | -           | Callback invoked when an error occurs during web page loading. For performance reasons, simplify the implementation logic in the callback. This callback is invoked when there is no network connection.                                                                |
67| onHttpErrorReceive   | Callback\<[OnHttpErrorReceiveEvent](#onhttperrorreceiveevent)\>                                                  | No | -           | Callback invoked when an HTTP error (the response code is greater than or equal to 400) occurs during web page resource loading.                                                                                    |
68| onPageBegin          | Callback\<[OnPageBeginEvent](#onpagebeginevent)\>                                                                | No | -           | Callback invoked when the web page starts to be loaded. It is invoked only for the main frame content, and not for the iframe or frameset content.                                                             |
69| onPageEnd            | Callback\<[OnPageEndEvent](#onpageendevent)\>                                                                    | No | -           | Callback invoked when the web page loading is complete. It is invoked only for the main frame content.                                                                                           |
70| onControllerAttached | Callback\<void\>                                                                                                 | No | -           | Callback invoked when a controller is attached to the **AtomicServiceWeb** component.                                                                                        |
71| onLoadIntercept      | [OnLoadInterceptCallback](#onloadinterceptcallback) | No | -  | Callback invoked when the **AtomicServiceWeb** component is about to load the URL. It is used to determine whether to block the loading. By default, the loading is allowed.                                                                             |
72| onProgressChange     | Callback\<[OnProgressChangeEvent](../../apis-arkweb/ts-basic-components-web.md#onprogresschangeevent12)\>        | No | -           | Callback invoked when the web page loading progress changes.                                                                                                     |
73
74## AtomicServiceWebController
75
76Implements an **AtomicServiceWebController** object for controlling the behavior of the **AtomicServiceWeb** component. An **AtomicServiceWebController** can control only one **AtomicServiceWeb** component, and the APIs on the **AtomicServiceWebController** can be called only after it has been bound to the target **AtomicServiceWeb** component.
77
78**Decorator Type**: @Observed
79
80**Atomic service API**: This API can be used in atomic services since API version 12.
81
82**System capability**: SystemCapability.ArkUI.ArkUI.Full
83
84### getUserAgent
85
86getUserAgent(): string
87
88Obtains the default user agent of this web page.
89
90**Atomic service API**: This API can be used in atomic services since API version 12.
91
92**System capability**: SystemCapability.ArkUI.ArkUI.Full
93
94**Return value**
95
96| Type    | Description     |
97|--------|---------|
98| string | Default user agent.|
99
100**Error codes**
101
102For details about the error codes, see [Webview Error Codes](../../apis-arkweb/errorcode-webview.md).
103
104| ID   | Error Message                                                                                            |
105|----------|--------------------------------------------------------------------------------------------------|
106| 17100001 | Init error. The AtomicServiceWebController must be associated with a AtomicServiceWeb component. |
107
108### getCustomUserAgent
109
110getCustomUserAgent(): string
111
112Obtains a custom user agent.
113
114**Atomic service API**: This API can be used in atomic services since API version 12.
115
116**System capability**: SystemCapability.ArkUI.ArkUI.Full
117
118**Return value**
119
120| Type    | Description        |
121|--------|------------|
122| string | Information about the custom user agent.|
123
124**Error codes**
125
126For details about the error codes, see [Webview Error Codes](../../apis-arkweb/errorcode-webview.md).
127
128| ID   | Error Message                                                                                            |
129|----------|--------------------------------------------------------------------------------------------------|
130| 17100001 | Init error. The AtomicServiceWebController must be associated with a AtomicServiceWeb component. |
131
132### setCustomUserAgent
133
134setCustomUserAgent(userAgent: string): void
135
136Sets a custom user agent, which will overwrite the default user agent.
137
138You are advised to set **UserAgent** in the **onControllerAttached** callback event. For details, see the example. Avoid setting **UserAgent** in the **onLoadIntercept** callback event, as there is a risk of failure in applying the setting.
139
140> **NOTE**
141>
142>If a URL is set for **src** in the **AtomicServiceWeb** component, and **UserAgent** is not set in the **onControllerAttached** callback event, calling **setCustomUserAgent** again may result in the loaded page being inconsistent with the actual user agent.
143
144**Atomic service API**: This API can be used in atomic services since API version 12.
145
146**System capability**: SystemCapability.ArkUI.ArkUI.Full
147
148**Parameters**
149
150| Name      | Type    | Mandatory| Description                                                                      |
151|-----------|--------|----|--------------------------------------------------------------------------|
152| userAgent | string | Yes | Information about the custom user agent. It is recommended that you obtain the current default user agent through [getUserAgent](#getuseragent) and then customize the obtained user agent.|
153
154**Error codes**
155
156For details about the error codes, see [Webview Error Codes](../../apis-arkweb/errorcode-webview.md).
157
158| ID   | Error Message                                                                                            |
159|----------|--------------------------------------------------------------------------------------------------|
160| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
161| 17100001 | Init error. The AtomicServiceWebController must be associated with a AtomicServiceWeb component. |
162
163### refresh
164
165refresh(): void
166
167Refreshes the web page.
168
169**Atomic service API**: This API can be used in atomic services since API version 12.
170
171**System capability**: SystemCapability.ArkUI.ArkUI.Full
172
173**Error codes**
174
175For details about the error codes, see [Webview Error Codes](../../apis-arkweb/errorcode-webview.md).
176
177| ID   | Error Message                                                                                            |
178|----------|--------------------------------------------------------------------------------------------------|
179| 17100001 | Init error. The AtomicServiceWebController must be associated with a AtomicServiceWeb component. |
180
181### forward
182
183forward(): void
184
185Moves to the next page based on the history stack. This API is generally used together with [accessForward](#accessforward).
186
187**Atomic service API**: This API can be used in atomic services since API version 12.
188
189**System capability**: SystemCapability.ArkUI.ArkUI.Full
190
191**Error codes**
192
193For details about the error codes, see [Webview Error Codes](../../apis-arkweb/errorcode-webview.md).
194
195| ID   | Error Message                                                                                            |
196|----------|--------------------------------------------------------------------------------------------------|
197| 17100001 | Init error. The AtomicServiceWebController must be associated with a AtomicServiceWeb component. |
198
199### backward
200
201backward(): void
202
203Moves to the previous page based on the history stack. This API is generally used together with [accessBackward](#accessbackward).
204
205**Atomic service API**: This API can be used in atomic services since API version 12.
206
207**System capability**: SystemCapability.ArkUI.ArkUI.Full
208
209**Error codes**
210
211For details about the error codes, see [Webview Error Codes](../../apis-arkweb/errorcode-webview.md).
212
213| ID   | Error Message                                                                                            |
214|----------|--------------------------------------------------------------------------------------------------|
215| 17100001 | Init error. The AtomicServiceWebController must be associated with a AtomicServiceWeb component. |
216
217### accessForward
218
219accessForward(): boolean
220
221Checks whether going to the next page can be performed on this page.
222
223**Atomic service API**: This API can be used in atomic services since API version 12.
224
225**System capability**: SystemCapability.ArkUI.ArkUI.Full
226
227**Return value**
228
229| Type     | Description                   |
230|---------|-----------------------|
231| boolean | Returns **true** if going to the next page can be performed on the current page; returns **false** otherwise.|
232
233**Error codes**
234
235For details about the error codes, see [Webview Error Codes](../../apis-arkweb/errorcode-webview.md).
236
237| ID   | Error Message                                                                                            |
238|----------|--------------------------------------------------------------------------------------------------|
239| 17100001 | Init error. The AtomicServiceWebController must be associated with a AtomicServiceWeb component. |
240
241### accessBackward
242
243accessBackward(): boolean
244
245Checks whether going to the previous page can be performed on this page.
246
247**Atomic service API**: This API can be used in atomic services since API version 12.
248
249**System capability**: SystemCapability.ArkUI.ArkUI.Full
250
251**Return value**
252
253| Type     | Description                   |
254|---------|-----------------------|
255| boolean | Returns **true** if moving to the previous page can be performed on the current page; returns **false** otherwise.|
256
257**Error codes**
258
259For details about the error codes, see [Webview Error Codes](../../apis-arkweb/errorcode-webview.md).
260
261| ID   | Error Message                                                                                            |
262|----------|--------------------------------------------------------------------------------------------------|
263| 17100001 | Init error. The AtomicServiceWebController must be associated with a AtomicServiceWeb component. |
264
265### accessStep
266
267accessStep(step: number): boolean
268
269Performs a specific number of steps forward or backward from this page.
270
271**Atomic service API**: This API can be used in atomic services since API version 12.
272
273**System capability**: SystemCapability.ArkUI.ArkUI.Full
274
275**Parameters**
276
277| Name | Type    | Mandatory| Description                   |
278|------|--------|----|-----------------------|
279| step | number | Yes | Number of the steps to take. A positive number means to go forward, and a negative number means to go backward.|
280
281**Return value**
282
283| Type     | Description       |
284|---------|-----------|
285| boolean | Whether moving forward or backward is performed on the current page.|
286
287**Error codes**
288
289For details about the error codes, see [Webview Error Codes](../../apis-arkweb/errorcode-webview.md).
290
291| ID   | Error Message                                                                                            |
292|----------|--------------------------------------------------------------------------------------------------|
293| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. |
294| 17100001 | Init error. The AtomicServiceWebController must be associated with a AtomicServiceWeb component. |
295
296### loadUrl
297
298loadUrl(url: string | Resource, headers?: Array\<WebHeader>): void
299
300Loads a specified URL.
301
302**Atomic service API**: This API can be used in atomic services since API version 12.
303
304**System capability**: SystemCapability.ArkUI.ArkUI.Full
305
306**Parameters**
307
308| Name    | Type                             | Mandatory| Description            |
309|---------|---------------------------------|----|:---------------|
310| url     | string \| [Resource](../../apis-arkui/arkui-ts/ts-types.md#resource)               | Yes | URL to load.    |
311| headers | Array\<[WebHeader](#webheader)> | No | Additional HTTP request header of the URL.|
312
313**Error codes**
314
315For details about the error codes, see [Webview Error Codes](../../apis-arkweb/errorcode-webview.md).
316
317| ID   | Error Message                                                                                            |
318|----------|--------------------------------------------------------------------------------------------------|
319| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. |
320| 17100001 | Init error. The AtomicServiceWebController must be associated with a AtomicServiceWeb component. |
321| 17100002 | Invalid url.                                                                                     |
322| 17100003 | Invalid resource path or file type.                                                              |
323
324## WebHeader
325
326Describes the request/response header returned by the **AtomicServiceWeb** component.
327
328**Atomic service API**: This API can be used in atomic services since API version 12.
329
330**System capability**: SystemCapability.ArkUI.ArkUI.Full
331
332| Name         | Type    | Readable| Writable| Description           |
333|-------------|--------|----|----|---------------|
334| headerKey   | string | Yes | Yes | Key of the request/response header.  |
335| headerValue | string | Yes | Yes | Value of the request/response header.|
336
337## OnMessageEvent
338
339Represents the callback invoked when the page is navigated back or destroyed.
340
341**Atomic service API**: This API can be used in atomic services since API version 12.
342
343**System capability**: SystemCapability.ArkUI.ArkUI.Full
344
345| Name  | Type      | Mandatory| Description   |
346|------|----------|----|-------|
347| data | object[] | Yes | Message list.|
348
349## OnErrorReceiveEvent
350
351Represents the callback invoked when an error occurs during web page loading.
352
353**Atomic service API**: This API can be used in atomic services since API version 12.
354
355**System capability**: SystemCapability.ArkUI.ArkUI.Full
356
357| Name     | Type                                                                                   | Mandatory| Description             |
358|---------|---------------------------------------------------------------------------------------|----|-----------------|
359| request | [WebResourceRequest](../../apis-arkweb/ts-basic-components-web.md#webresourcerequest) | Yes | Encapsulation of a web page request.     |
360| error   | [WebResourceError](../../apis-arkweb/ts-basic-components-web.md#webresourceerror)     | Yes | Encapsulation of a web page resource loading error.|
361
362## OnHttpErrorReceiveEvent
363
364Represents the callback invoked when an HTTP error occurs during web page resource loading.
365
366**Atomic service API**: This API can be used in atomic services since API version 12.
367
368**System capability**: SystemCapability.ArkUI.ArkUI.Full
369
370| Name      | Type                                                                                     | Mandatory| Description        |
371|----------|-----------------------------------------------------------------------------------------|----|------------|
372| request  | [WebResourceRequest](../../apis-arkweb/ts-basic-components-web.md#webresourcerequest)   | Yes | Encapsulation of a web page request.|
373| response | [WebResourceResponse](../../apis-arkweb/ts-basic-components-web.md#webresourceresponse) | Yes | Encapsulation of a resource response.|
374
375## OnPageBeginEvent
376
377Represents the callback invoked when the web page loading begins.
378
379**Atomic service API**: This API can be used in atomic services since API version 12.
380
381**System capability**: SystemCapability.ArkUI.ArkUI.Full
382
383| Name | Type    | Mandatory| Description       |
384|-----|--------|----|-----------|
385| url | string | Yes | URL of the page.|
386
387## OnPageEndEvent
388
389Represents the callback invoked when the web page loading ends.
390
391**Atomic service API**: This API can be used in atomic services since API version 12.
392
393**System capability**: SystemCapability.ArkUI.ArkUI.Full
394
395| Name | Type    | Mandatory| Description       |
396|-----|--------|----|-----------|
397| url | string | Yes | URL of the page.|
398
399## OnLoadInterceptEvent
400
401Represents the event triggered when resource loading is intercepted.
402
403**Atomic service API**: This API can be used in atomic services since API version 12.
404
405**System capability**: SystemCapability.ArkUI.ArkUI.Full
406
407| Name            | Type     | Mandatory  | Description                                      |
408| -------------- | ---- | ---- | ---------------------------------------- |
409| data | [WebResourceRequest](../../apis-arkweb/ts-basic-components-web.md#webresourcerequest) | Yes| Encapsulation of a web page request.|
410
411## OnProgressChangeEvent
412
413Represents the callback invoked when the web page loading progress changes.
414
415**Atomic service API**: This API can be used in atomic services since API version 12.
416
417**System capability**: SystemCapability.ArkUI.ArkUI.Full
418
419| Name            | Type     | Mandatory  | Description                                      |
420| -------------- | ---- | ---- | ---------------------------------------- |
421| newProgress | number | Yes| New loading progress. The value is an integer ranging from 0 to 100.                      |
422
423## OnLoadInterceptCallback
424
425type OnLoadInterceptCallback = (event: OnLoadInterceptEvent) => boolean
426
427Represents the callback invoked when resource loading is intercepted.
428
429**Atomic service API**: This API can be used in atomic services since API version 12.
430
431**System capability**: SystemCapability.ArkUI.ArkUI.Full
432
433**Parameters**
434
435| Name | Type    | Mandatory| Description                   |
436|------|--------|----|-----------------------|
437| event | OnLoadInterceptEvent | Yes | Event triggered when resource loading is intercepted.|
438
439**Return value**
440
441| Type     | Description       |
442|---------|-----------|
443| boolean | Whether the resource is intercepted.|
444
445## Events
446
447The [universal events](ts-universal-events-click.md) are not supported.
448
449## Example
450
451### Example 1
452
453This example loads a local web page:
454
455```ts
456// xxx.ets
457import { AtomicServiceWeb, AtomicServiceWebController } from '@kit.ArkUI';
458
459@Entry
460@Component
461struct WebComponent {
462  @State controller: AtomicServiceWebController = new AtomicServiceWebController();
463
464  build() {
465    Column() {
466      AtomicServiceWeb({ src: $rawfile("index.html"), controller: this.controller })
467    }
468  }
469}
470```
471
472### Example 2
473
474This example loads an online web page:
475
476```ts
477// xxx.ets
478import { AtomicServiceWeb, AtomicServiceWebController } from '@kit.ArkUI';
479
480@Entry
481@Component
482struct WebComponent {
483    @State controller: AtomicServiceWebController = new AtomicServiceWebController();
484
485    build() {
486        Column() {
487            AtomicServiceWeb({ src: 'https://www.example.com', controller: this.controller })
488        }
489    }
490}
491```
492
493### Example 3
494
495This example demonstrates how to load a web page within a **NavDestination** container.
496
497```ts
498// xxx.ets
499import { AtomicServiceWeb, AtomicServiceWebController } from '@kit.ArkUI';
500
501@Builder
502export function WebComponentBuilder(name: string, param: Object) {
503  WebComponent()
504}
505
506@Component
507struct WebComponent {
508  navPathStack: NavPathStack = new NavPathStack();
509  @State controller: AtomicServiceWebController = new AtomicServiceWebController();
510
511  build() {
512    NavDestination() {
513      AtomicServiceWeb({ src: $rawfile("index.html"), controller: this.controller, navPathStack: this.navPathStack })
514    }
515    .onReady((context: NavDestinationContext) => {
516      this.navPathStack = context.pathStack;
517    })
518  }
519}
520```
521
522### Example 4
523
524This example sets the **onMessage()** event callback.
525
526```ts
527// xxx.ets
528import { AtomicServiceWeb, AtomicServiceWebController, OnMessageEvent } from '@kit.ArkUI';
529
530@Entry
531@Component
532struct WebComponent {
533  @State controller: AtomicServiceWebController = new AtomicServiceWebController();
534
535  build() {
536    Column() {
537      AtomicServiceWeb({
538        src: $rawfile("index.html"),
539        controller: this.controller,
540        // Called when the user clicks Send Message and then Back on an HTML5 page.
541        onMessage: (event: OnMessageEvent) => {
542          console.info(`[AtomicServiceWebLog] onMessage data = ${JSON.stringify(event.data)}`);
543        }
544      })
545    }
546  }
547}
548```
549
550```html
551// index.html
552<!DOCTYPE html>
553<html>
554<meta charset="utf-8">
555<!-- Import the JS SDK file. -->
556<script src="../js/atomicservice-sdk.js" type="text/javascript"></script>
557<body>
558<h1>JS SDK - postMessage()</h1>
559<br/>
560<button type="button" onclick="postMessage({ name: 'Jerry', age: 18 });">Send Message</button>
561<br/>
562<button type="button" onclick="back();">Back</button>
563</body>
564<script type="text/javascript">
565    function postMessage(data) {
566        // API provided by the JS SDK for sending messages.
567        has.asWeb.postMessage({
568            data: data,
569            callback: (err, res) => {
570                if (err) {
571                    console.error(`[AtomicServiceWebLog H5] postMessage error err. Code: ${err.code}, message: ${err.message}`);
572                } else {
573                    console.info(`[AtomicServiceWebLog H5] postMessage success res = ${JSON.stringify(res)}`);
574                }
575            }
576        });
577    }
578
579    function back() {
580        // Router API provided by the JS SDK for navigation back.
581        has.router.back({
582            delta: 1
583        });
584    }
585</script>
586</html>
587```
588
589### Example 5
590
591This example sets the web page loading event callbacks.
592
593```ts
594// xxx.ets
595import {
596  AtomicServiceWeb,
597  AtomicServiceWebController,
598  OnErrorReceiveEvent,
599  OnHttpErrorReceiveEvent,
600  OnPageBeginEvent,
601  OnPageEndEvent
602} from '@kit.ArkUI';
603
604@Entry
605@Component
606struct WebComponent {
607  @State controller: AtomicServiceWebController = new AtomicServiceWebController();
608
609  build() {
610    Column() {
611      AtomicServiceWeb({
612        src: $rawfile('index.html'),
613        controller: this.controller,
614        // Invoked when an error occurs during web page loading.
615        onErrorReceive: (event: OnErrorReceiveEvent) => {
616          console.info(`AtomicServiceWebLog onErrorReceive event = ${JSON.stringify({
617            requestUrl: event.request?.getRequestUrl(),
618            requestMethod: event.request?.getRequestMethod(),
619            errorCode: event.error?.getErrorCode(),
620            errorInfo: event.error?.getErrorInfo()
621          })}`);
622        },
623        // Invoked when an HTTP error occurs during web page resource loading.
624        onHttpErrorReceive: (event: OnHttpErrorReceiveEvent) => {
625          console.info(`AtomicServiceWebLog onHttpErrorReceive event = ${JSON.stringify({
626            requestUrl: event.request?.getRequestUrl(),
627            requestMethod: event.request?.getRequestMethod(),
628            responseCode: event.response?.getResponseCode(),
629            responseData: event.response?.getResponseData(),
630          })}`);
631        },
632        // Invoked when the web page starts to be loaded.
633        onPageBegin: (event: OnPageBeginEvent) => {
634          console.info(`AtomicServiceWebLog onPageBegin event = ${JSON.stringify({
635            url: event.url
636          })}`);
637        },
638        // Invoked when loading of the web page is complete.
639        onPageEnd: (event: OnPageEndEvent) => {
640          console.info(`AtomicServiceWebLog onPageEnd event = ${JSON.stringify({
641            url: event.url
642          })}`);
643        }
644      })
645    }
646  }
647}
648```
649
650### Example 6
651
652This example demonstrates how to use **AtomicServiceWeb** and **AtomicServiceWebController**.
653
654```ts
655// xxx.ets
656import {
657  AtomicServiceWeb,
658  AtomicServiceWebController,
659  OnErrorReceiveEvent,
660  OnHttpErrorReceiveEvent,
661  OnPageBeginEvent,
662  OnPageEndEvent,
663  OnMessageEvent,
664  OnLoadInterceptEvent,
665  OnProgressChangeEvent
666} from '@kit.ArkUI';
667
668@Entry
669@Component
670struct WebComponent {
671  @State darkMode: WebDarkMode = WebDarkMode.On;
672  @State forceDarkAccess: boolean = true;
673  @State mixedMode: MixedMode = MixedMode.None;
674  @State controller: AtomicServiceWebController = new AtomicServiceWebController();
675  @State num: number = 1;
676
677  build() {
678    Column() {
679      Button('accessForward').onClick(() => {
680        console.info(`AtomicServiceWebLog accessForward = ${this.controller.accessForward()}`);
681      })
682      Button('accessBackward').onClick(() => {
683        console.info(`AtomicServiceWebLog accessBackward = ${this.controller.accessBackward()}`);
684      })
685      Button('accessStep').onClick(() => {
686        console.info(`AtomicServiceWebLog accessStep = ${this.controller.accessStep(1)}`);
687      })
688      Button('forward').onClick(() => {
689        console.info(`AtomicServiceWebLog forward = ${this.controller.forward()}`);
690      })
691      Button('backward').onClick(() => {
692        console.info(`AtomicServiceWebLog backward = ${this.controller.backward()}`);
693      })
694      Button('refresh').onClick(() => {
695        console.info(`AtomicServiceWebLog refresh = ${this.controller.refresh()}`);
696      })
697      Button('loadUrl').onClick(() => {
698        console.info(`AtomicServiceWebLog loadUrl = ${this.controller.loadUrl('https://www.baidu.com/')}`);
699      })
700      Button('Dark Mode').onClick(() => {
701        this.forceDarkAccess = !this.forceDarkAccess;
702      })
703      Button('mixedMode').onClick(() => {
704        this.mixedMode = this.mixedMode == MixedMode.None ? MixedMode.All : MixedMode.None;
705      })
706      Button('Click').onClick(() => {
707        console.info(`AtomicServiceWebLog getUserAgent = ${this.controller.getUserAgent()}`);
708        console.info(`AtomicServiceWebLog getCustomUserAgent = ${this.controller.getCustomUserAgent()}`);
709        this.controller.setCustomUserAgent('test' + this.num++);
710
711        console.info(`AtomicServiceWebLog getUserAgent after set = ${this.controller.getUserAgent()}`);
712        console.info(`AtomicServiceWebLog getCustomUserAgent after set = ${this.controller.getCustomUserAgent()}`);
713      })
714      AtomicServiceWeb({
715        src: 'https://www.example.com',
716        mixedMode: this.mixedMode,
717        darkMode: this.darkMode,
718        forceDarkAccess: this.forceDarkAccess,
719        controller: this.controller,
720        onControllerAttached: () => {
721          console.info("AtomicServiceWebLog onControllerAttached call back success");
722        },
723        onLoadIntercept: (event: OnLoadInterceptEvent) => {
724          console.info("AtomicServiceWebLog onLoadIntercept call back success " + JSON.stringify({
725            getRequestUrl: event.data.getRequestUrl(),
726            getRequestMethod: event.data.getRequestMethod(),
727            getRequestHeader: event.data.getRequestHeader(),
728            isRequestGesture: event.data.isRequestGesture(),
729            isMainFrame: event.data.isMainFrame(),
730            isRedirect: event.data.isRedirect(),
731          }))
732          return false;
733        },
734        onProgressChange: (event: OnProgressChangeEvent) => {
735          console.info("AtomicServiceWebLog onProgressChange call back success " + JSON.stringify(event));
736        },
737        onMessage: (event: OnMessageEvent) => {
738          console.info("onMessage call back success " + JSON.stringify(event));
739        },
740        onPageBegin: (event: OnPageBeginEvent) => {
741          console.info("onPageBegin call back success " + JSON.stringify(event));
742        },
743        onPageEnd: (event: OnPageEndEvent) => {
744          console.info("onPageEnd call back success " + JSON.stringify(event));
745        },
746        onHttpErrorReceive: (event: OnHttpErrorReceiveEvent) => {
747          console.info("onHttpErrorReceive call back success " + JSON.stringify(event));
748        },
749        onErrorReceive: (event: OnErrorReceiveEvent) => {
750          console.info("onErrorReceive call back success " + JSON.stringify(event));
751        }
752      })
753    }
754  }
755}
756```
757