JavaScript 如何检测设备是否为Android设备
任务是使用JavaScript检测设备是否为Android手机。
方法1
- 使用 navigator.userAgent 属性来获取浏览器发送给服务器的用户代理标头的值。
- 检查userAgent中的’android’的索引。
- 如果索引大于-1,则为Android手机,否则不是Android手机。
示例: 此示例检查设备是否为Android手机。
<!DOCTYPE HTML>
<html>
<head>
<title>
How to detect Android Phone
using JavaScript ?
</title>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<p id = "GFG_UP" style =
"font-size: 19px; font-weight: bold;">
</p>
<button onclick = "GFG_Fun()">
click here
</button>
<p id = "GFG_DOWN" style =
"color: green; font-size: 24px; font-weight: bold;">
</p>
<script>
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
el_up.innerHTML = "Click on the button to detect if"
+ " the device is android phone.";
function GFG_Fun() {
var res = "Device is not Android Phone";
var userAgent = navigator.userAgent.toLowerCase();
var Android = userAgent.indexOf("android") > -1;
if(Android) {
res = "Device is Android Phone";
}
el_down.innerHTML = res;
}
</script>
</body>
</html>
输出:
- 点击按钮之前:
- 在计算机上运行并点击按钮:
- 在Android手机上运行并点击按钮:
方法2
- 将navigator.userAgent属性存储在变量userAgent中。
- 通过使用RegExp,在userAgent中查找’android’。
- 如果Android的值不为0,则为Android手机,否则不是Android手机。
示例:
<!DOCTYPE HTML>
<html>
<head>
<title>
How to detect Android Phone
using JavaScript ?
</title>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<p id = "GFG_UP" style =
"font-size: 19px; font-weight: bold;">
</p>
<button onclick = "GFG_Fun()">
click here
</button>
<p id = "GFG_DOWN" style =
"color: green; font-size: 24px; font-weight: bold;">
</p>
<script>
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
el_up.innerHTML = "Click on the button to detect if"
+ " the device is android phone.";
function GFG_Fun() {
var res = "Device is not Android Phone";
var Android = /(android)/i.test(navigator.userAgent);
if(Android) {
res = "Device is Android Phone";
}
el_down.innerHTML = res;
}
</script>
</body>
</html>
输出:
- 在点击按钮之前:
- 在电脑上运行并点击按钮:
- 在安卓手机上运行并点击按钮: