• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# User-Agent开发指导
2<!--RP1-->
3User-Agent(简称UA)是一个特殊的字符串,包含设备类型、操作系统及版本等关键信息。在Web开发中,这个字符串使服务器能够识别请求的来源设备及其特性,从而根据这些信息提供定制化的内容和服务。如果页面无法正确识别UA,可能会导致多种异常情况。例如,为移动设备优化的页面布局可能会在桌面设备上显示错乱,反之亦然。此外,某些特定的浏览器功能或CSS样式可能仅在特定的浏览器版本中受支持,如果页面无法根据UA字符串做出正确的判断,就可能导致渲染问题或逻辑错误。
4
5## 默认User-Agent结构
6
7- 默认User-Agent定义
8
9  ```ts
10  Mozilla/5.0 ({DeviceType}; {OSName} {OSVersion}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{ChromeCompatibleVersion}.0.0.0 Safari/537.36  ArkWeb/{ArkWeb VersionCode} {DeviceCompat} {扩展区}
11  ```
12
13- 举例说明
14
15  ```ts
16  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
17  ```
18
19- 字段说明
20
21  | 字段                  | 含义                                                         |
22  | --------------------- | ------------------------------------------------------------ |
23  | DeviceType            | 当前的设备类型。<br>取值范围:<br>- Phone:手机<br>- Tablet:平板设备<br>-  PC:2in1设备 |
24  | OSName                | 基础操作系统名称。<br>默认取值:OpenHarmony                  |
25  | OSVersion             | 基础操作系统版本,两位数字,M.S。<br>通过系统参数const.ohos.fullname解析版本号得到,取版本号部分M.S前两位。<br>默认取值:例如5.0       |
26  | ChromeCompatibleVersion | 兼容Chrome主版本的版本号,从114版本开始演进。<br>默认取值:114            |
27  | ArkWeb                | OpenHarmony版本Web内核名称。<br>默认取值:ArkWeb             |
28  | ArkWeb VersionCode    | ArkWeb版本号,格式a.b.c.d。<br>默认取值:例如4.1.6.1         |
29  | DeviceCompat          | 前向兼容字段。<br>默认取值:Mobile                          |
30  | 扩展区                | 三方应用可以扩展的字段。<br>三方应用使用ArkWeb组件时,可以做UA扩展,例如加入APP相关信息标识。 |
31
32> **说明:**
33>
34> - 当前默认User-Agent的ArkWeb字段前有两个空格。
35>
36> - 当前通过User-Agent中是否含有"Mobile"字段来判断是否开启前端HTML页面中meta标签的viewport属性。当User-Agent中不含有"Mobile"字段时,meta标签中viewport属性默认关闭,此时可通过显性设置[metaViewport](../reference/apis-arkweb/ts-basic-components-web.md#metaviewport12)属性为true来覆盖关闭状态。
37>
38> - 建议通过OpenHarmony关键字识别是否是OpenHarmony设备,同时可以通过DeviceType识别设备类型用于不同设备上的页面显示(ArkWeb关键字表示设备使用的web内核,OpenHarmony关键字表示设备使用的操作系统,因此推荐通过OpenHarmony关键字识别是否是OpenHarmony设备)。
39>
40> - {DistributionOSName}和{DistributionOSVersion}字段在API version 15之前的版本中未启用,从API version 15版本开始不在默认User-Agent中体现。
41
42## 自定义User-Agent结构
43
44在下面的示例中,通过调用[getUserAgent()](../reference/apis-arkweb/js-apis-webview.md#getuseragent)接口获取当前默认的用户代理(User-Agent)字符串。这一接口提供的默认User-Agent信息为开发者提供了基础,使开发者能够基于这个默认信息进行定制或扩展。
45
46```ts
47// xxx.ets
48import { webview } from '@kit.ArkWeb';
49import { BusinessError } from '@kit.BasicServicesKit';
50
51@Entry
52@Component
53struct WebComponent {
54  controller: webview.WebviewController = new webview.WebviewController();
55
56  build() {
57    Column() {
58      Button('getUserAgent')
59        .onClick(() => {
60          try {
61            let userAgent = this.controller.getUserAgent();
62            console.log("userAgent: " + userAgent);
63          } catch (error) {
64            console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
65          }
66        })
67      Web({ src: 'www.example.com', controller: this.controller })
68    }
69  }
70}
71```
72
73以下示例通过[setCustomUserAgent()](../reference/apis-arkweb/js-apis-webview.md#setcustomuseragent10)接口设置自定义用户代理,但请注意,此操作会覆盖系统的用户代理。因此,我们建议将扩展字段追加在默认用户代理的末尾,比如三方应用程序的开发场景,可以在系统默认用户代理字符串的末尾追加特定的APP标识,这样既能保留原有用户代理信息,又能增加自定义的应用识别信息。
74
75当Web组件src设置了url时,建议在onControllerAttached回调事件中设置User-Agent,设置方式请参考示例。不建议将User-Agent设置在onLoadIntercept回调事件中,会概率性出现设置失败。如果未在onControllerAttached回调事件中设置User-Agent。再调用setCustomUserAgent方法时,可能会出现加载的页面与实际设置User-Agent不符的异常现象。
76
77当Web组件src设置为空字符串时,建议先调用setCustomUserAgent方法设置User-Agent,再通过loadUrl加载具体页面。
78
79```ts
80// xxx.ets
81import { webview } from '@kit.ArkWeb';
82import { BusinessError } from '@kit.BasicServicesKit';
83
84@Entry
85@Component
86struct WebComponent {
87  controller: webview.WebviewController = new webview.WebviewController();
88  // 三方应用相关信息标识
89  @State customUserAgent: string = ' DemoApp';
90
91  build() {
92    Column() {
93      Web({ src: 'www.example.com', controller: this.controller })
94      .onControllerAttached(() => {
95        console.log("onControllerAttached");
96        try {
97          let userAgent = this.controller.getUserAgent() + this.customUserAgent;
98          this.controller.setCustomUserAgent(userAgent);
99        } catch (error) {
100          console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
101        }
102      })
103    }
104  }
105}
106```
107
108在下面的示例中,通过[getCustomUserAgent()](../reference/apis-arkweb/js-apis-webview.md#getcustomuseragent10)接口获取自定义用户代理。
109
110```ts
111// xxx.ets
112import { webview } from '@kit.ArkWeb';
113import { BusinessError } from '@kit.BasicServicesKit';
114
115@Entry
116@Component
117struct WebComponent {
118  controller: webview.WebviewController = new webview.WebviewController();
119  @State userAgent: string = '';
120
121  build() {
122    Column() {
123      Button('getCustomUserAgent')
124        .onClick(() => {
125          try {
126            this.userAgent = this.controller.getCustomUserAgent();
127            console.log("userAgent: " + this.userAgent);
128          } catch (error) {
129            console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
130          }
131        })
132      Web({ src: 'www.example.com', controller: this.controller })
133    }
134  }
135}
136```
137
138## 常见问题
139
140### 如何通过User-Agent来识别OpenHarmony操作系统中不同设备
141
142OpenHarmony设备的识别主要通过User-Agent中的系统、系统版本和设备类型三个维度来判断。建议同时检查系统、系统版本和设备类型,以确保更准确的设备识别。
143
1441. 系统识别
145
146   通过User-Agent中的{OSName}字段识别OpenHarmony系统。
147
148   ```ts
149   const isOpenHarmony = () => /OpenHarmony/i.test(navigator.userAgent);
150   ```
151
1522. 系统版本识别
153
154   通过User-Agent中的{OSName}和{OSVersion}字段识别OpenHarmony系统及系统版本。格式为:OpenHarmony + 版本号。
155
156   ```ts
157   const matches = navigator.userAgent.match(/OpenHarmony (\d+\.?\d*)/);
158   matches?.length && Number(matches[1]) >= 5;
159   ```
160
1613. 设备类型识别
162
163    通过deviceType字段来识别不同设备类型。
164
165   ```ts
166   // 检测是否为手机设备
167   const isPhone = () => /Phone/i.test(navigator.userAgent);
168
169   // 检测是否为平板设备
170   const isTablet = () => /Tablet/i.test(navigator.userAgent);
171
172   // 检测是否为2in1设备
173   const is2in1 = () => /PC/i.test(navigator.userAgent);
174   ```
175
176### 如何模拟OpenHarmony操作系统的User-Agent进行前端调试
177
178Windows/Mac/Linux等操作系统中,可以通过Chrome/Edge/Firefox等浏览器DevTools提供的User-Agent复写能力,模拟OpenHarmony User-Agent。
179<!--RP1End-->