在网页中通过userAgent获取手机获取手机操作系统类型

来源:互联网 发布:大宗商品数据 编辑:程序博客网 时间:2024/06/06 07:48

转自:http://www.zhixing123.cn/net/32604.html

本文介绍如果在JavaScript中根据手机浏览器提供的信息userAgent判断手机操作系统的类型,并执行相应的操作。

 

原理

通过navigator的userAgent属性判断是否包含特定手机平台的信息;通过JavaScript正则表达式test方法进行匹配判断。

HTML代码

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>手机跳转</title>
<script language="javascript" type="text/javascript">
function checkOS() {
//默认的地址
var defaultUrl = 'index.htm';
//如果检测到是Android系统需要跳转的地址
var androidUrl = 'android.htm';
//如果检测到是iphone/ipod需要跳转的地址
var iphoneUrl = 'iphone.htm';
//symbian跳转地址
var symbianUrl = 'symbian.htm';
//windows phone跳转地址
var windowsPhoneUrl = 'winphone.htm';
var url = '';
var ua = (navigator.userAgent || navigator.vendor || window.opera);
if (ua!=null) {
var uaName = ua.toLowerCase();
if (/android/i.test(uaName)) url = androidUrl;
else
{ if (/ip(hone|od)/i.test(uaName)) url = iphoneUrl;
else {
if (/symbian/i.test(uaName)) url = symbianUrl;
else {
if (/windows (ce|phone)/i.test(uaName)) url = windowsPhoneUrl;
else url = defaultUrl;
}
}
}
//document.writeln(uaName);
}
else { url = defaultUrl; }
window.location.href = url;
}
</script>
</head>
<body onload='checkOS();'>
test
</body>
</html>


0 0