Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect a mobile device with JavaScript?

I have been asked to create an actual HTML page / JavaScript to simulate detection of the mobile devices (iPhone / iPad / Android) using JavaScript code. This will then take the user to a different screen which asks them for their email address.

like image 775
Jeevs Avatar asked Jul 12 '11 15:07

Jeevs


People also ask

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

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

How can I check my mobile device?

The easiest way to check your phone's model name and number is to use the phone itself. Go to the Settings or Options menu, scroll to the bottom of the list, and check 'About phone', 'About device' or similar. The device name and model number should be listed.


2 Answers

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. } 
like image 175
Baraa Avatar answered Sep 17 '22 18:09

Baraa


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> 
like image 44
slandau Avatar answered Sep 19 '22 18:09

slandau