javascript - 如果设备是华为?
问题描述
我只是创建一个页面将用户重定向到应用程序链接(谷歌播放和苹果商店和华为商店)
我只是从这个链接中获取代码
代码是:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<title>Test</title>
<script>
function getMobileOperatingSystem() {
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
if (/android/i.test(userAgent)) {
return "Android";
}
if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
return "iOS";
}
return "unknown";
}
</script>
</head>
<body onload="DetectAndServe()">
<script>
function DetectAndServe() {
let os = getMobileOperatingSystem();
if (os == "Android") {
window.location.href = "https://play.google.com";
} else if (os == "iOS") {
window.location.href = "https://apps.apple.com";
} else {
window.location.href = "https://my-link.com";
}
}
</script>
</body>
</html>
我们知道华为有自己的商店,我如何检查设备是否是华为将其重定向到华为链接?
解决方案
您可能需要测试/huawei/i.test(userAgent)
华为设备,因为设备制造商与操作系统检查 android 不同。
确保华为测试在安卓测试之前,否则永远匹配不了!
我还将更改函数以直接返回应用商店 url,而不是检查操作系统,然后对if (os == "Android")
块内的华为设备进行另一个用户代理测试。
function getAppStoreUrl() {
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
if (/huawei/i.test(userAgent)) {
return "https://my-link.com";
}
if (/android/i.test(userAgent)) {
return "https://play.google.com";
}
if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
return "https://apps.apple.com";
}
return null;
}
function DetectAndServe() {
let appStoreUrl = getAppStoreUrl();
if (appStoreUrl) {
window.location.href = appStoreUrl;
}
}
推荐阅读
- azure - 在 Azure Active Directory 身份验证中提供用户参数
- node.js - 无服务器部署错误:找不到模块'/Users/.../--max-old-space-size=2048'
- c - 在 C 中每个块的顶部声明变量的基本原理?
- angular - 路由到孩子时找不到Angular 10辅助路由
- regex - Bash 中的正则表达式或 Grep
- c++ - xcode中的指令后缩进不起作用
- azure - 在 docker compose 上为 Azurite 自定义存储帐户
- javascript - 无法读取未定义的属性“输入”
- python - 删除数据框中的科学记数法浮点数
- f# - 如何使用户能够下载寓言中的文件?