Best way to detect mobile device and redirect

冷暖自知 提交于 2019-11-30 04:25:33

问题


Here's my snippet for detecting a mobile display based on the screen size. You can force the site to stay in desktop-mode by adding a forceDesktop param to the URL.

I`m new to jquery so if you have suggestions, please comment.

Credits go to brandonjp: How can I get query string values in JavaScript?

        <script>
            $.urlParam = function(name, url) {
                if (!url) {
                    url = window.location.href;
                }
                var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(url);
                if (!results) { 
                    return undefined;
                }
                return results[1] || undefined;
            }
            window.onload = function() {
                var forceDesktop = $.urlParam('forceDesktop');
                if (!forceDesktop) {
                    if ( $(window).width() < 639) {   
                        var url = "http://m.mysite.com/";    
                        $(location).attr('href',url);
                    }
                }
            };
        </script>

回答1:


Actually, I believe that it is important to detect mobile from window width.

So here is the way that I am using.

function detectmob() {
   if(window.innerWidth <= 800 || window.innerHeight <= 600) {
     return true;
   } else {
     return false;
   }
}

if (detectmob()){
top.location.href="mobile";
}



回答2:


If you're going to use some form of browser-sniffing rather than feature detection via something like Modernizr, your best bet is to grab some script from http://detectmobilebrowsers.com/ rather than use home-grown / incomplete scripts pasted here and there.




回答3:


why not this?

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
    window.location = "http://m.mysite.tld/"; 
}



回答4:


best way is

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) )     
{
   var url = "http://m.mysite.com/";    
   $(location).attr('href',url);

}

For more Here



来源:https://stackoverflow.com/questions/26649767/best-way-to-detect-mobile-device-and-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!