1# Setting UserAgent
2<!--RP1-->
3UserAgent (UA) is a special string that contains key information such as the device type, operating system, and version. If a page cannot correctly identify the UA, exceptions in the page layout, rendering, and logic may occur.
4
5## Default UserAgent Structure
6
7- Default User Agent string
8
9  ```ts
10  Mozilla/5.0 ({DeviceType}; {OSName} {OSVersion}; {DistributionOSName} {DistributionOSVersion}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{ChromeCompatibleVersion}.0.0.0 Safari/537.36 ArkWeb/{ArkWeb VersionCode} {DeviceCompat} {Extension}
11  ```
12
13- Example
14
15  Mozilla/5.0 (Phone; OpenHarmony 5.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 ArkWeb/4.1.6.1 Mobile
16
17- Description
18
19  | Field.                 | Description                                                        |
20  | --------------------- | ------------------------------------------------------------ |
21  | DeviceType            | Current device type.<br>Value range:<br>- **Phone**: mobile phone<br>- **Tablet**: tablet<br>- **PC**: 2-in-1 device|
22  | OSName                | OS name.<br>Default value: OpenHarmony                 |
23  | OSVersion             | OS version. The value is a two-digit number, in M.S format.<br>To obtain the first two digits M.S, you can use the system parameter **const.ohos.fullname** to parse the version number.<br>Default value: **5.0**      |
24  | DistributionOSName    | OS distribution name.                                        |
25  | DistributionOSVersion | OS distribution version. The value is a two-digit number, in M.S format.<br>You can obtain the M.S value by parsing the version number using the system parameter **const.product.os.dist.apiname**. Use **const.product.os.dist.version** if **const.product.os.dist.apiname** is empty.<br>Default value: **5.0**    |
26  | ChromeCompatibleVersion | The version that is compatible with the Chrome main version, which starts from 114.<br>Default value: **114**           |
27  | ArkWeb                | Web kernel name of the OpenHarmony version.<br>Default value: **ArkWeb**            |
28  | ArkWeb VersionCode    | ArkWeb version number, in the format of a.b.c.d.<br>Default value: **4.1.6.1**        |
29  | DeviceCompat          | Forward compatible field.<br>Default value: **Mobile**                         |
30  | Extension               | The field that can be extended by a third-party application.<br>When a third-party application uses the **Web** component, the UA can be extended. For example, the application information identifier can be added.|
31
32> **NOTE**
33>
34> - Currently, the **viewport** attribute of the **meta** tag on the frontend HTML page is enabled based on whether **UserAgent** contains the **Mobile** field. If **UserAgent** does not contain the **Mobile** field, the **viewport** attribute in the **meta** tag is disabled by default. In this case, you can explicitly set [metaViewport](../reference/apis-arkweb/ts-basic-components-web.md#metaviewport12) to **true** to enable the **viewport** attribute.
35>
36> - You are advised to use the **OpenHarmony** keyword to identify whether a device is an OpenHarmony device, and use the **DeviceType** keyword to identify the device type for page display on different devices. (The **ArkWeb** keyword indicates the web kernel used by the device, and the **OpenHarmony** keyword indicates the operating system used by the device.)
37
38## Custom UserAgent Structure
39
40Example of using [getUserAgent()](../reference/apis-arkweb/js-apis-webview.md#getuseragent) to obtain the default user agent, which can be customized:
41
42```ts
43// xxx.ets
44import { webview } from '@kit.ArkWeb';
45import { BusinessError } from '@kit.BasicServicesKit';
46
47@Entry
48@Component
49struct WebComponent {
50  controller: webview.WebviewController = new webview.WebviewController();
51
52  build() {
53    Column() {
54      Button('getUserAgent')
55        .onClick(() => {
56          try {
57            let userAgent = this.controller.getUserAgent();
58            console.log("userAgent: " + userAgent);
59          } catch (error) {
60            console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
61          }
62        })
63      Web({ src: 'www.example.com', controller: this.controller })
64    }
65  }
66}
67```
68
69In the following example, the custom user agent set through [setCustomUserAgent()](../reference/apis-arkweb/js-apis-webview.md#setcustomuseragent10) overwrites the system user agent. You are advised to add the extension field to the end of the default user agent.
70
71When **src** of the **Web** component is set to a URL, you are advised to set **UserAgent** in **onControllerAttached**. For details, see the following example. You are not advised to set **UserAgent** in **onLoadIntercept**. Otherwise, the setting may fail occasionally. If **UserAgent** is not set in **onControllerAttached**, calling **setCustomUserAgent** may load a page that is inconsistent with the custom user agent.
72
73When **src** of the **Web** component is set to an empty string, you are advised to call **setCustomUserAgent** to set **UserAgent** and then use **loadUrl** to load a specific page.
74
75```ts
76// xxx.ets
77import { webview } from '@kit.ArkWeb';
78import { BusinessError } from '@kit.BasicServicesKit';
79
80@Entry
81@Component
82struct WebComponent {
83  controller: webview.WebviewController = new webview.WebviewController();
84  // Third-party application information identifier
85  @State customUserAgent: string = ' DemoApp';
86
87  build() {
88    Column() {
89      Web({ src: 'www.example.com', controller: this.controller })
90      .onControllerAttached(() => {
91        console.log("onControllerAttached");
92        try {
93          let userAgent = this.controller.getUserAgent() + this.customUserAgent;
94          this.controller.setCustomUserAgent(userAgent);
95        } catch (error) {
96          console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
97        }
98      })
99    }
100  }
101}
102```
103
104Example of obtaining the custom user agent through [getCustomUserAgent()](../reference/apis-arkweb/js-apis-webview.md#getcustomuseragent10):
105
106```ts
107// xxx.ets
108import { webview } from '@kit.ArkWeb';
109import { BusinessError } from '@kit.BasicServicesKit';
110
111@Entry
112@Component
113struct WebComponent {
114  controller: webview.WebviewController = new webview.WebviewController();
115  @State userAgent: string = '';
116
117  build() {
118    Column() {
119      Button('getCustomUserAgent')
120        .onClick(() => {
121          try {
122            this.userAgent = this.controller.getCustomUserAgent();
123            console.log("userAgent: " + this.userAgent);
124          } catch (error) {
125            console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
126          }
127        })
128      Web({ src: 'www.example.com', controller: this.controller })
129    }
130  }
131}
132```
133
134## FAQs
135
136### How do I use UserAgent to identify different devices of OpenHarmony?
137
138OpenHarmony devices can be identified based on the system name, system version, and device type in the **UserAgent**. You are advised to check all of them to ensure accurate device identification.
139
1401. Identification based on the system name
141
142   Use the **{OSName}** field.
143
144   ```ts
145   const isOpenHarmony = () => /OpenHarmony/i.test(navigator.userAgent);
146   ```
147
1482. Identification based on the system version
149
150   Use the **{OSName}** and **{OSVersion}** fields. The format is **OpenHarmony + Version number**.
151
152   ```ts
153   const matches = navigator.userAgent.match(/OpenHarmony (\d+\.?\d*)/);
154   matches?.length && Number(matches[1]) >= 5;
155   ```
156
1573. Identification based on the device type
158
159    Use the **deviceType** field.
160
161   ```ts
162   // Check whether the device is a mobile phone.
163   const isPhone = () => /Phone/i.test(navigator.userAgent);
164
165   // Check whether the device is a tablet.
166   const isTablet = () => /Tablet/i.test(navigator.userAgent);
167
168   // Check whether the device is a 2-in-1 device.
169   const is2in1 = () => /PC/i.test(navigator.userAgent);
170   ```
171
172### How do I simulate the UserAgent of OpenHarmony for frontend debugging?
173
174In Windows, macOS, and Linux, you can use the **UserAgent** rewriting capability provided by DevTools to simulate the OpenHarmony **UserAgent** in Chrome, Edge, and Firefox.
175<!--RP1End-->
176