How to detect a mobile device with JavaScript? How to detect a mobile device with JavaScript? javascript javascript

How to detect a mobile device with JavaScript?


I know this answer is coming 3 years late but none of the other answers are indeed 100% correct. If you would like to detect if the user is on ANY form of mobile device (Android, iOS, BlackBerry, Windows Phone, Kindle, etc.), then you can use the following code:

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) {    // Take the user to a different screen here.}


You would detect the requesting browsers user agent string, and then decide based on what it is if it's coming from a mobile browser or not. This device is not perfect, and never will be due to the fact that user agents aren't standardized for mobile devices (at least not to my knowledge).

This site will help you create the code: http://www.hand-interactive.com/resources/detect-mobile-javascript.htm

Example:

You could get the user agent in javascript by doing this:

var uagent = navigator.userAgent.toLowerCase();

And then do the check's in the same format as this (just using iPhone as a quick example, but others would need to be a little bit different)

function DetectIphone(){   if (uagent.search("iphone") > -1)      alert('true');   else      alert('false');}

Edit

You'd create a simple HTML page like so:

<html>    <head>        <title>Mobile Detection</title>    </head>    <body>        <input type="button" OnClick="DetectIphone()" value="Am I an Iphone?" />    </body></html><script>    function DetectIphone()    {       var uagent = navigator.userAgent.toLowerCase();       if (uagent.search("iphone") > -1)          alert('true');       else          alert('false');    }</script>


A pretty simple solution is to check for the screen width. Since almost all mobile devices have a max screen width of 480px (at present), it's pretty reliable:

if( screen.width <= 480 ) {    location.href = '/mobile.html';}

The user-agent string is also a place to look. However, the former solution is still better since even if some freaking device does not respond correctly for the user-agent, the screen width doesn't lie.

The only exception here are tablet pc's like the ipad. Those devices have a higher screen width than smartphones and I would probably go with the user-agent-string for those.