【背景知识】
ArkWeb:@ohos.web.webview提供web控制能力,Web组件提供网页显示的能力。
Web用户代理UserAgent定义:
从API version 11起,Web组件基于ArkWeb的内核,默认UserAgent定义如下:
Mozilla/5.0 ({DeviceType}; {OSName} {OSVersion}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{ChromeCompatibleVersion}.0.0.0 Safari/537.36 ArkWeb/{ArkWeb VersionCode} {DeviceCompat} {扩展区}
【定位思路】
因为url加载的网页是电脑网页,所以不做任何适配的话,在手机端加载的电脑网页会显示异常。
因此对于同一个url的网页,需要适配多种设备,例如: 平板,手机,电脑等,而且适配多种设备型号,比如Mate60, Meta60 Pro。
需要:
设备端能够传给网页设备的标识。
网页开发者能够根据设备的标识做对该网页对相应的设备做样式的适配。
【解决方案】
1.通过设置UserAgent,把设备端标识信息传递给网页,因此网页端可以通过deviceType识别设备类型。
aboutToAppear(): void {
webview.once('webInited', () => {
try {
// 应用侧用法示例,定制UserAgent。
this.ua = this.controller.getUserAgent() +
'Mozilla/5.0 ({deviceType}; {OSName} {OSVersion}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 ArkWeb/{ArkWeb VersionCode} {Mobile}';
this.controller.setCustomUserAgent(this.ua);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
}
2.网页侧通过userAgent,获得设备端标识信息,代码示例如下:
window.onload = function(){
const resultText = document.getElementById("result");
// 获得userAgent
resultText.innerHTML = navigator.userAgent;
}
3.在Web的onControllerAttached里面设置UserAgent。
@State userAgent:string = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 ArkWeb/4.1.6.1 Mobile automobile/792 HuaweiBrowser'
Web({ src: '', controller: this.controller})
.onControllerAttached(()=>{
this.controller.setCustomUserAgent(this.userAgent);
this.controller.loadUrl('xxxxxx')
})
【总结】
网页开发者需要根据设备端传递的设备信息对网页做相应的适配,以适配多种设备以及设备型号。