JavaScript 如何获取您设备的Android版本
任务是通过JavaScript来检测用户的Android版本。
这里讨论了两种方法,第一个示例使用了 RegExp ,第二个示例使用了 indexOf 方法来搜索关键字 ‘android’ 。
注意: 这两个代码只在Android设备上运行时有效。
方法1
在这个方法中,我们将使用 navigator.useragent属性 ,它返回浏览器发送给服务器的用户代理头的值。它包含有关浏览器的名称、版本和平台的信息。然后我们需要在返回的字符串中搜索关键字 ‘android’ ,并将值存入临时数组(其中包含版本),为此我们将使用一个 RegExp 。如果temp不为空,则索引0处的值为答案,否则为undefined。
示例: 此示例实现了上述方法。
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<style>
body {
text-align: center;
}
h1 {
color: green;
}
.gfg {
font-size: 20px;
font-weight: bold;
}
#geeks {
font-size: 24px;
font-weight: bold;
color: green;
}
</style>
</head>
<body>
<h1>
GeeksForGeeks
</h1>
<p class="gfg">
Click on the button to get the android
version of the user.
</p>
<button onclick="GFG_Fun()">
click here
</button>
<p id="geeks">
</p>
<script>
var element = document.getElementById("body");
function androidV(ua) {
ua = (ua || navigator.userAgent).toLowerCase();
var match = ua.match(/android\s([0-9\.]*)/i);
return match ? match[1] : undefined;
};
function GFG_Fun() {
$('#geeks').html(androidV());
}
</script>
</body>
输出:
方法2
在这个方法中,我们将使用 navigator.userAgent 属性,它返回浏览器发送给服务器的用户代理头的值。它包含关于浏览器的名称、版本和平台的信息。然后,我们需要搜索字符串中是否存在关键词“android”,为了实现这一点,我们将使用 indexOf 。如果存在,那么使用 .slice() 和 indexOf 获取包含在关键词“android”之后的版本。
示例: 此示例实现了上述方法。
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<style>
body {
text-align: center;
}
h1 {
color: green;
}
.gfg {
font-size: 20px;
font-weight: bold;
}
#geeks {
font-size: 24px;
font-weight: bold;
color: green;
}
</style>
</head>
<body>
<h1>
GeeksForGeeks
</h1>
<p class="gfg">
Click on the button to get the android
version of the user.
</p>
<button onclick="GFG_Fun()">
click here
</button>
<p id="geeks">
</p>
<script>
var element = document.getElementById("body");
function GFG_Fun() {
var androidV = null;
var ua = navigator.userAgent;
if (ua.indexOf("Android") >= 0) {
androidV = parseFloat(ua.slice(ua.indexOf("Android") + 8));
}
$('#geeks').html(androidV);
}
</script>
</body>
输出: