Best way to detect mobile device and redirect

Sacha Vorbeck picture Sacha Vorbeck · Oct 30, 2014 · Viewed 20.8k times · Source

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>

Answer

Ahmet Can G&#252;ven picture Ahmet Can Güven · Oct 30, 2014

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";
}