How to detect a mobile device with JavaScript?
Asked Answered
C

21

87

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.

Cadwell answered 12/7, 2011 at 15:37 Comment(2)
if u can know the screen dimensions that way u can differentiate between an iphone and an ipadCarnify
Use can use code : #11382173Coray
S
93

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.
}
Speaking answered 26/10, 2014 at 20:59 Comment(3)
I would add the keyword "Mobile" as well.Guglielmo
do you need a library of some sort? I doubt is that simple.Merrymerryandrew
This code snippet helps but the issue with web browser simulated as mobile. Please helpAetiology
M
31

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>
Messieurs answered 12/7, 2011 at 15:41 Comment(4)
But I am wondering what would be start? Create a dummy webpage and embedd this coding in there. Is it html that we will use in, because as I mentioned in my code above, I have nothing to start with.Cadwell
Great!!!! Thanks for that. How about redirecting it to a different page. Do you think something like this would help? if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/Android/i))) { if (document.cookie.indexOf("iphone_redirect=false") == -1) window.location = "m.espn.go.com/wireless/?iphone&i=COMR";Cadwell
Don't forget that user agents can be changed, spoofed and may not reflect the current browser. That being said if a client spoofs/changes their UserAgent and you they the wrong view displayed it's their own fault. There are other ways other than pure user agent although the user agent is typically the root of all detection. There is a really good (although outdated) example here github.com/ahand/mobileesp?files=1Hey
Smart - never thought of that :DBahner
C
21

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.

Cattish answered 12/7, 2011 at 15:40 Comment(2)
Right!! I only need to detect iPhone or Android. So this shouldn't be a problem, but just to let you know I have absolutely nothing to start with. Shall I create a dummy Webpage and embedd this! Also how would the detection be checked? Would I need to transfer the script to a phone?Cadwell
My, how screen widths have changed ;)Sarena
B
17
if(navigator.userAgent.match(/iPad/i)){
 //code for iPad here 
}

if(navigator.userAgent.match(/iPhone/i)){
 //code for iPhone here 
}


if(navigator.userAgent.match(/Android/i)){
 //code for Android here 
}



if(navigator.userAgent.match(/BlackBerry/i)){
 //code for BlackBerry here 
}


if(navigator.userAgent.match(/webOS/i)){
 //code for webOS here 
}
Backstairs answered 8/4, 2013 at 2:1 Comment(3)
this is the best and cleanest solutionLumper
Even though this code won't execute more than one block since it's checking one thing over and over again, this code should make use of else-if blocks because of that reason. Also, what if the user agent variable changes somehow in between blocks? It'll execute more than 1 block, here.Exscind
You are right ,and don't forget that code was 4 years ago :) and there is now better tools or ways to do the same jobBackstairs
O
9
var isMobileDevice = navigator.userAgent.match(/iPad|iPhone|iPod/i) != null 
    || screen.width <= 480;
Osgood answered 19/11, 2012 at 13:57 Comment(1)
+1 for regex matching allowing users to easily check for multiple devices in one shot. However, I would add for clarity that because you denote /i at the end of the regex for insensitive match there really is no need to camel case the search params. The following would be equivalent (and also search for android devices): .match(/ipad|iphone|ipod|android/i)Kilmarx
A
7

A simple solution could be css-only. You can set styles in your stylesheet, and then adjust them on the bottom of it. Modern smartphones act like they are just 480px wide, while they are actually a lot more. The code to detect a smaller screen in css is

@media handheld, only screen and (max-width: 560px), only screen and (max-device-width: 480px)  {
    #hoofdcollumn {margin: 10px 5%; width:90%}
}

Hope this helps!

Aldin answered 6/2, 2013 at 18:34 Comment(0)
F
6

I use mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)

Fp answered 27/3, 2014 at 23:2 Comment(0)
X
5

So I did this. Thank you all!

<head>
<script type="text/javascript">
    function DetectTheThing()
    {
       var uagent = navigator.userAgent.toLowerCase();
       if (uagent.search("iphone") > -1 || uagent.search("ipad") > -1 
       || uagent.search("android") > -1 || uagent.search("blackberry") > -1
       || uagent.search("webos") > -1)
          window.location.href ="otherindex.html";
    }
</script>

</head>

<body onload="DetectTheThing()">
VIEW NORMAL SITE
</body>

</html>
Xanthippe answered 14/7, 2015 at 0:59 Comment(0)
S
5

Since it's now 2015, if you stumbled across this question then you should probably be using window.matchMedia (and, if it's still 2015, polyfilling for older browsers):

if (matchMedia('handheld').matches) {
    //...
} else {
    //...
}
Sascha answered 22/7, 2015 at 13:7 Comment(3)
This didn't work for me on a Nexus 5 running Firefox.Hypo
Note from MDN Note: CSS2.1 and Media Queries 3 defined several additional media types (tty, tv, projection, handheld, braille, embossed, aural), but they were deprecated in Media Queries 4 and shouldn't be used.Snowdrop
See my answer below, for some reason handheld doesn't work for me either.Rola
H
4

The cleanest way of finding device type is:

if (navigator.userAgentData.mobile) { // do something }

(although it isn't yet supported on Safari)

More info: https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData/mobile

Hypochlorite answered 31/7, 2021 at 13:9 Comment(2)
interesting that this feature is not available on FF even though we have this mdn link.Hooknosed
in mid 2022 userAgentData has quite low support, 71%Dahna
M
3

You can use the user-agent string to detect this.

var useragent = navigator.userAgent.toLowerCase();

if( useragent.search("iphone") )
    ; // iphone
else if( useragent.search("ipod") )
    ; // ipod
else if( useragent.search("android") )
    ; // android
etc

You can find a list of useragent strings here http://www.useragentstring.com/pages/useragentstring.php

Malposition answered 12/7, 2011 at 15:43 Comment(0)
H
3

I advise you check out http://wurfl.io/

In a nutshell, if you import a tiny JS file:

<script type='text/javascript' src="//wurfl.io/wurfl.js"></script>

you will be left with a JSON object that looks like:

{
 "complete_device_name":"Google Nexus 7",
 "is_mobile":true,
 "form_factor":"Tablet"
}

(that's assuming you are using a Nexus 7, of course) and you will be able to do things like:

WURFL.complete_device_name

This is what you are looking for.

Disclaimer: I work for the company that offers this free service. Thanks.

Hoes answered 11/3, 2014 at 17:18 Comment(1)
"You can use these services free of charge, as long as your website is publicly available and does not require fees or paid subscription to access." -web.wurfl.io/#wurfl-jsFurtek
J
2

Device detection based on user-agent is not very good solution, better is to detect features like touch device (in new jQuery they remove $.browser and use $.support instead).

To detect mobile you can check for touch events:

function is_touch_device() {
  return 'ontouchstart' in window // works on most browsers 
      || 'onmsgesturechange' in window; // works on ie10
}

Taken from What's the best way to detect a 'touch screen' device using JavaScript?

Jolenejolenta answered 6/5, 2014 at 11:8 Comment(3)
Down vote because OP is asking for mobile device. With touchscreen laptops nowadays, 'Touch Device' is not a very good solution.Bland
@thebrenny laptops are mobile devices dude, they can get moved easily from place to placeDogma
Oh boy, I've had some laptops that are pretty useless at being portable! 🙃 But either way, OP gave iPhone, iPad, and Android as examples for what they wanted to detect, and "mobile" is short for "mobile phone". Probably a better description would've been "keyboardless"Bland
I
2

This is an example of how to check if webpage is loaded in Desktop or mobile app.

JS will execute on page load and you can do Desktop specific things on page load eg hide barcode scanner.

   <!DOCTYPE html>
    <html>
    <head>
     <script type="text/javascript">

            /*
            * Hide Scan button if Page is loaded in Desktop Browser
            */
            function hideScanButtonForDesktop() {

                if (!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent))) {

                    // Hide scan button for Desktop
                    document.getElementById('btnLinkModelScan').style.display = "none";
                }         
            }

            //toggle scanButton for Desktop on page load
            window.onload = hideScanButtonForDesktop;
        </script>
    </head>
Irrepealable answered 8/11, 2016 at 10:12 Comment(0)
R
2

Testing for user agent is complex, messy and invariably fails. I also didn't find that the media match for "handheld" worked for me. The simplest solution was to detect if the mouse was available. And that can be done like this:

let isMouseAvailable = window.matchMedia("(any-pointer:coarse)").matches;

That will tell you if you need to show hover items or not and anything else that requires a physical pointer. The sizing can then be done on further media queries based on width.

The following little library is a belt braces version of the query above, should cover most "are you a tablet or a phone with no mouse" scenarios.

https://patrickhlauke.github.io/touch/touchscreen-detection/

Media matches have been supported since 2015 and you can check the compatibility here: https://caniuse.com/#search=matchMedia

In short you should maintain variables relating to whether the screen is touch screen and also what size the screen is. In theory I could have a tiny screen on a mouse operated desktop.

Rola answered 15/3, 2019 at 16:9 Comment(6)
If you're trying to determine whether to show hover items, shouldn't you use the media query (hover) instead?Cussed
@Cussed My point being is that even if the device supports hover, I need a device that can hover. If I don't have a pointer I can't hover.Rola
IIUC hover means that the primary input device supports hover, which a pointer would but a touchscreen wouldn'tCussed
i would suggest code improvement to make it more understandable what you're up to there - 'var result'? what are you testing for? how about 'var isDeviceMobile' or 'var isDeviceDesktop' instead? bcs mouse when present matches 'fine', not 'coarse'. otherwise i think it's a great answer! thank youDahna
which made me think - can you have a bluetooth mouse working with phone or tablet? or even mouse connected via cable? then i guess this way the detection would failDahna
@Dahna Yes it probably would fail. I see my answer is from 3 years ago and it probably needs revision. You see a lot of variations in controllers such as using an Xbox controller to operate something. I'll make the code improvements anyway.Rola
G
1

Determine what the User Agent is for the devices that you need to simulate and then test a variable against that.

for example:

// var userAgent = navigator.userAgent.toLowerCase(); // this would actually get the user agent

var userAgent = "iphone"; /* Simulates User Agent for iPhone */
if (userAgent.indexOf('iphone') != -1) {
   // some code here
}
Garges answered 12/7, 2011 at 15:41 Comment(1)
!!~userAgent.indexOf('iphone') // >> true|falseElide
A
0

This is my version, quite similar to the upper one, but I think good for reference.

if (mob_url == "") {
  lt_url = desk_url;
} else if ((useragent.indexOf("iPhone") != -1 || useragent.indexOf("Android") != -1 || useragent.indexOf("Blackberry") != -1 || useragent.indexOf("Mobile") != -1) && useragent.indexOf("iPad") == -1 && mob_url != "") {
  lt_url = mob_url;
} else {
  lt_url = desk_url;
}
Aegina answered 3/9, 2013 at 7:31 Comment(0)
M
0

Simply use DeviceDetection

deviceDetection.deviceType // phone | tablet according to device
Mouth answered 18/7, 2014 at 16:23 Comment(1)
Do you work for them? That literally just used user agentDogma
S
0

Another possibility is to use mobile-detect.js. Try the demo.

Browser usage:

<script src="mobile-detect.js"></script>
<script>
    var md = new MobileDetect(window.navigator.userAgent);
    // ... see below
</script>

Node.js / Express:

var MobileDetect = require('mobile-detect'),
    md = new MobileDetect(req.headers['user-agent']);
// ... see below

Example:

var md = new MobileDetect(
    'Mozilla/5.0 (Linux; U; Android 4.0.3; en-in; SonyEricssonMT11i' +
    ' Build/4.1.A.0.562) AppleWebKit/534.30 (KHTML, like Gecko)' +
    ' Version/4.0 Mobile Safari/534.30');

// more typically we would instantiate with 'window.navigator.userAgent'
// as user-agent; this string literal is only for better understanding

console.log( md.mobile() );          // 'Sony'
console.log( md.phone() );           // 'Sony'
console.log( md.tablet() );          // null
console.log( md.userAgent() );       // 'Safari'
console.log( md.os() );              // 'AndroidOS'
console.log( md.is('iPhone') );      // false
console.log( md.is('bot') );         // false
console.log( md.version('Webkit') );         // 534.3
console.log( md.versionStr('Build') );       // '4.1.A.0.562'
console.log( md.match('playstation|xbox') ); // false
Sacerdotal answered 26/10, 2016 at 8:57 Comment(0)
C
0

As I (kind of without success) searched for the proper solution for my hack, I want to add my hack here nonetheless: I simply check for support of device orientation, which seems the most significant diffrence between mobiles and desktop:

var is_handheld=0; // just a global if(window.DeviceOrientationEvent) {is_handheld=1;}

That being said, imho a page should also offer manual choice between mobile / desktop layout. I got 1920*1080 and I can zoom in - an oversimplified and feature-reduced wordpressoid chunk is not always a good thing. Especially forcing a layout based on nonworking device detection - it happens all the time.

Chile answered 23/11, 2017 at 11:46 Comment(0)
L
0

Similar to several of the answers above. This simple function, works very well for me. It is current as of 2019

function IsMobileCard()
{
var check =  false;

(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);

return check;   
}
Lenis answered 19/5, 2019 at 22:56 Comment(2)
what is the data source for this insanely long regex that's probably hard to maintain and debug?Dahna
I got it from another user. Works greatLenis

© 2022 - 2024 — McMap. All rights reserved.