问题描述
我一直试图找到一种方法来定位华为移动设备,以便我可以将它们重定向到华为应用商店,但似乎找不到解决方案。到目前为止我想到的就是写一个正则表达式来检查华为 |华为 |从 navigator.userAgent 对象返回的字符串中的 huawei .. 但我不确定它是否适用于所有此类设备,尽管我认为这些sample userAgents 是否有模拟器或类似 browserstack 之类的东西来试试这个?
解决方法
您可以通过查询useragent来判断当前设备是否为华为手机。
目前华为浏览器提供基于HMS或GMS设备类型的UA。 以下为示例(浏览器版本号、HMS版本号、GMS版本号、设备信息会相应变化):
- HMS 和 GMS 均已安装。下面是一个例子:
Mozilla/5.0 (Linux; Android 6.0.1; LYA-AL00; HMSCore/4.0.0 GMS/10.4 ) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/70.0.3538.64 HuaweiBrowser/10.0.3.1032.3 Safari Mobile
- 如果只安装了HMS,下面是一个例子:
Mozilla/5.0 (Linux; Android 6.0.1; LYA-AL00; HMSCore/4.0.0 ) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/70.0.3538.64 HuaweiBrowser/10.0.3.102 Mobile Safari/537.36 >
- 仅安装了 GMS。下面是一个例子:
Mozilla/5.0 (Linux; Android 6.0.1; LYA-AL00;GMS/10.4 ) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/70.0.3538.64 HuaweiBrowser/10.0.3.102 Mobile Safari/537.36
- 没有 HMS 或 GMS。下面是一个例子:
Mozilla/5.0 (Linux; Android 6.0.1; LYA-AL00) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/70.0.3538.64 HuaweiBrowser/10.0.3.102 Mobile Safari/537.36
,我不知道如何定位特定类型的手机,但您可以测试用户代理字符串:
/**
* Determine the mobile operating system.
* This function returns one of 'iOS','Android','Windows Phone',or 'unknown'.
*
* @returns {String}
*/
function getMobileOperatingSystem() {
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
// Windows Phone must come first because its UA also contains "Android"
if (/windows phone/i.test(userAgent)) {
return "Windows Phone";
}
if (/android/i.test(userAgent)) {
return "Android";
}
// iOS detection from: http://stackoverflow.com/a/9039885/177710
if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
return "iOS";
}
return "unknown";
}