Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to detect mobile device and redirect

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>
like image 788
Sacha Vorbeck Avatar asked Oct 30 '14 09:10

Sacha Vorbeck


People also ask

What is the best way to detect a mobile device?

In summary, we recommend looking for the string “Mobi” anywhere in the User Agent to detect a mobile device. Like this: if (/Mobi/. test(navigator.

What is the best way to detect a mobile device JavaScript?

matchMedia() The Window. matchMedia() is one of the best properties for detecting mobile users with JavaScript.

How do websites recognize mobile devices?

It works by examining information contained in the HTTP headers, particularly User Agent strings sent by all web-enabled devices. The User Agent is looked up in a database that returns any requested information including device type.

How to detect mobile or desktop browser?

You can use JavaScript window. matchMedia() method to detect a mobile device based on the CSS media query. You may also use navigator. userAgentData.


2 Answers

why not this?

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
    window.location = "http://m.mysite.tld/"; 
}
like image 89
Patrick Avatar answered Sep 28 '22 08:09

Patrick


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";
}
like image 27
Ahmet Can Güven Avatar answered Sep 28 '22 07:09

Ahmet Can Güven