简体   繁体   中英

Detect mobile device via Javascript

Related to this question: Detect Android phone via Javascript / jQuery

In the new version of the android sdk, the native browser isn't returning the codename "android" anymore. navigator.userAgent returns something like:

mozilla/5.0 (X11; Linux x86_64) AppleWebkit7534.24 (KHTML, like Gecko) Chrome/11.0.696.34 Safari7534.24

Any suggestions why? This comes from a handset with the HTC One S with the current Android version 4.1.1

See this question . Are you sure you're not viewing in desktop mode? The stock browser, and many others, have two different user agents depending on the browsing mode.

Don't ever use browser sniffing! Use feature detection. There is a javascript library called modernizr , that can do actions according to features of the users client.

Yeah... this is probably because your browser is in "desktop mode".

You probably want to show some mobile version of your page when displayed on small screens so what you can try is:

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<script type="text/javascript">  
  if ((screen.width < 480) || (screen.height < 480)) {    
    location.replace('/m/');
  }  
</script>

You need the viewport metatag for the browser to report the actual screen size.

Edit:
According to this you might need to wait some time for the browser to "catch up" before checking the screen size so I guess it will be better to use:

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<script type="text/javascript">  
  setTimeout(function() {
               if ((screen.width < 480) || (screen.height < 480)) {    
                 location.replace('/m/');
               }  
             }, 200);
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM