JS代码判断浏览者是手机访问还是电脑访问并跳转

代码展示
0 341

csroad
csroad 举报
2019-03-31

在JS代码判断浏览者是手机访问还是电脑访问并跳转



<script type="text/javascript">  
    function browserRedirect() {  
        var sUserAgent = navigator.userAgent.toLowerCase();
        var Android = sUserAgent.match(/android/i) == "android";
        var Linux =  sUserAgent.match(/linux/i) == "linux";
        var Mobi = sUserAgent.match(/mobi/i) == "mobi";
        var Pad = sUserAgent.match(/pad/i) == "pad";
        var IOS = sUserAgent.match(/ios/i) == "ios";
        var iPad = sUserAgent.match(/ipad/i) == "ipad";
        var iPhone = sUserAgent.match(/iphone/i) == "iphone";
        var Windows_Phone = sUserAgent.match(/windows iphone/i) == "windows iphone";
        var Symbian = sUserAgent.match(/symbian/i) == "symbian";
        var ishttps = 'https:' == document.location.protocol ? 'https://': 'http://'; 
        //var ishttps = '//'; 
        
        if ((Android || Linux) && Mobi && !Pad || (IOS && !iPad) || iPhone || Windows_Phone || Symbian){
            var curHref = window.location.href;
            if (curHref.indexOf(ishttps+"csroad.cn") == 0 ){
                window.location.href=curHref.replace(ishttps+"csroad.cn",ishttps+"m.csroad.cn");
            }
            if (curHref.indexOf(ishttps+"www.csroad.cn") == 0 ){
                window.location.href=curHref.replace(ishttps+"www.csroad.cn",ishttps+"m.csroad.cn");
            }
        } 
    }  
    browserRedirect();
</script>