JavaScript 检测设备是否为iOS
为了判断设备是否为iOS,我们使用Navigator平台和Navigator userAgent属性。
- Navigator userAgent属性
此属性返回浏览器发送到服务器的用户代理标头的值。
返回值包含浏览器的名称、版本和平台的信息。
语法:
navigator.userAgent
返回值:
返回一个字符串,表示当前工作浏览器的用户代理字符串。
- Navigator platform属性
此属性返回浏览器编译的平台。
语法:
navigator.platform
返回值:
返回一个字符串,表示浏览器的平台。
可能的值:
- HP-UX
- Linux i686
- Linux armv7l
- Mac68K
- MacPPC
- SunOS
- Win32
- Etc.
示例1: 此示例通过 (navigator.userAgent) 属性检测设备,并返回 false 。
<!DOCTYPE HTML>
<html>
<head>
<title>
JavaScript
| Detecting a device is iOS.
</title>
</head>
<body style="text-align:center;"
id="body">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP"
style="font-size: 15px;
font-weight: bold;">
Detecting whether a device is iOS.
</p>
<button onclick="gfg_Run()">
detect
</button>
<p id="GFG_DOWN"
style="color:green;
font-size: 23px;
font-weight: bold;">
</p>
<script>
var el_down =
document.getElementById("GFG_DOWN");
function gfg_Run() {
var iOS =
/iPad|iPhone|iPod/.test(navigator.userAgent) &&
!window.MSStream;
el_down.innerHTML = iOS;
}
</script>
</body>
</html>
输出:
- 点击按钮之前:
- 点击按钮之后:
示例2: 该示例通过 (navigator.platform) 属性 检测设备,并返回 true 。
<!DOCTYPE HTML>
<html>
<head>
<title>
JavaScript
| Detecting a device is iOS.
</title>
</head>
<body style="text-align:center;"
id="body">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP"
style="font-size: 15px; font-weight: bold;">
Detecting whether a device is iOS.
</p>
<button onclick="gfg_Run()">
detect
</button>
<p id="GFG_DOWN"
style="color:green;
font-size: 23px;
font-weight: bold;">
</p>
<script>
var el_down =
document.getElementById("GFG_DOWN");
function gfg_Run() {
var iOS =
!!navigator.platform &&
/iPad|iPhone|iPod/.test(navigator.platform);
el_down.innerHTML = iOS;
}
</script>
</body>
</html>
输出:
- 点击按钮之前:
- 点击按钮之后:
示例3: 此示例通过 (navigator.platform)属性 检测设备,并返回 false 。
<!DOCTYPE HTML>
<html>
<head>
<title>
JavaScript
| Detecting a device is iOS.
</title>
</head>
<body style="text-align:center;"
id="body">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP"
style="font-size: 15px;
font-weight: bold;">
Detecting whether a device is iOS.
</p>
<button onclick="gfg_Run()">
detect
</button>
<p id="GFG_DOWN"
style="color:green;
font-size: 23px;
font-weight: bold;">
</p>
<script>
var el_down = document.getElementById("GFG_DOWN");
function gfg_Run() {
var iOS =
!!navigator.platform &&
/iPad|iPhone|iPod/.test(navigator.platform);
el_down.innerHTML = iOS;
}
</script>
</body>
</html>
输出:
- 点击按钮之前:
- 点击按钮之后: