说明

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

About author
Disclaimer
The opinions and comments expressed herein are my own personal opinions and do not represent my employer's view in any way.
Comments
No comments.
Add comment
Title
Title is required.
Name
Name is required.
Email
Please input your personal email with valid format.
Comments
Please input comment content.
Captcha Refresh
Input captcha:

Subscription

Statistics

Locations of visitors to this page