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

Raymond Raymond event 2011-10-31 visibility 2,349
more_vert

说明

本文介绍如果在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>

More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts