Detecting a mobile browser

1,341,366

Solution 1

Using Regex (from detectmobilebrowsers.com):

Here's a function that uses an insanely long and comprehensive regex which returns a true or false value depending on whether or not the user is browsing with a mobile.

window.mobileCheck = function() {
  let 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;
};

For those wishing to include tablets in this test (though arguably, you shouldn't), you can use the following function:

window.mobileAndTabletCheck = function() {
  let 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|android|ipad|playbook|silk/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;
};

Using navigator.userAgentData

You may also use navigator.userAgentData.mobile, but userAgentData is still experimental, so it is not recommended for use in production.

const isMobile = navigator.userAgentData.mobile; //resolves true/false

Compatibility chart for userAgentData


The Original Answer

You can do this by simply running through a list of devices and checking if the useragent matches anything like so:

  function detectMob() {
    const toMatch = [
        /Android/i,
        /webOS/i,
        /iPhone/i,
        /iPad/i,
        /iPod/i,
        /BlackBerry/i,
        /Windows Phone/i
    ];
    
    return toMatch.some((toMatchItem) => {
        return navigator.userAgent.match(toMatchItem);
    });
}

However since you believe that this method is unreliable, You could assume that any device that had a resolution of 800x600 or less was a mobile device too, narrowing your target even more (although these days many mobile devices have much greater resolutions than this)

i.e

  function detectMob() {
    return ( ( window.innerWidth <= 800 ) && ( window.innerHeight <= 600 ) );
  }

Reference:

Solution 2

How about:

if (typeof screen.orientation !== 'undefined') { ... }

...since smartphones usually support this property and desktop browsers don't. See in MDN.

EDIT 1: As @Gajus pointed out, window.orientation is now deprecated and shouldn't be used.

EDIT 2: You can use the experimental screen.orientation instead of the deprecated window.orientation. See in MDN.

EDIT 3: Changed from window.orientation to screen.orientation

Solution 3

var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i) || navigator.userAgent.match(/WPDesktop/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};

How to use

if( isMobile.any() ) alert('Mobile');

To check to see if the user is on a specific mobile device:

if( isMobile.iOS() ) alert('iOS');

Ref: http://www.abeautifulsite.net/blog/2011/11/detecting-mobile-devices-with-javascript

Enhanced version on github : https://github.com/smali-kazmi/detect-mobile-browser

Solution 4

Here is a simple solution from the source of facebook's slingshot

var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
if (isMobile) {
  /* your code here */
}

Solution 5

Came here looking for a simple, clean way to detect "touch screens devices", which I class as mobile and tablets. Did not find a clean choice in the current answers but did work out the following which may also help someone.

var touchDevice = ('ontouchstart' in document.documentElement);

Edit: To support desktops with a touch screen and mobiles at the same time you can use the following:

var touchDevice = (navigator.maxTouchPoints || 'ontouchstart' in document.documentElement);
Share:
1,341,366
ave
Author by

ave

Updated on April 29, 2022

Comments

  • ave
    ave about 2 years

    I'm looking for a function which return boolean value if user has mobile browser or not.

    I know that I can use navigator.userAgent and write that function by using regex, but user-agents are too various for different platforms. I doubt that match all possible devices would be easy, and I think this problem has been solved before many times so there should be some kind of complete solution for such task.

    I was looking at this site, but sadly the script is so cryptic that I have no idea how to use it for my purpose, which is to create a function which return true / false.

    • Frédéric Hamidi
      Frédéric Hamidi almost 12 years
    • KyelJmD
      KyelJmD almost 12 years
    • UltraInstinct
      UltraInstinct almost 12 years
      It would be better if server did this and sent across different versions of JS file..
    • Amit Patil
      Amit Patil almost 12 years
      @Thrustmaster: It really wouldn't. Serving different JS to different browsers means you have to add Vary: User-Agent to your response, otherwise caching proxies will store one version and send it to the other kind of browser. But Vary: User-Agent makes the response uncachable in IE.
    • Amit Patil
      Amit Patil almost 12 years
      @ave: What are you trying to do by detecting a "mobile" browser? The distinction is highly arguable in today's world of tablets and hybrid computing devices. Are you looking to detect small screens, and present a different UI in that case? Are you looking to detect low-bandwidth connectivity? Are you looking to detect touch interfaces?
    • UltraInstinct
      UltraInstinct almost 12 years
      @bobince Thanks for that. Every single day I get to learn something new at SO! :)
    • Michael Zaporozhets
      Michael Zaporozhets over 11 years
      So i've updated my answer to use the detectmobilebrowsers.com javascript method but return a boolean value if anyone still needs this. ( just in case ). Happy Detecting :)
    • canintex
      canintex about 11 years
      @ave : Just to throw in another way of thinking. I find it's easier to detect devices based on screen size in today's world of multiple portable devices. Using something like Harvey.js you can basically Media Query your JS.
    • landed
      landed about 9 years
      @bob I came here and the reason why I need this is that I want to enable a background video. Mobiles and tablets stop autoplay of the video and it really shows there is a step too far between them STILL. But I echo your reasoning as today I feel this gap should not be there. After all RWD is based on this premise.
    • Liam
      Liam about 9 years
      It's generally regarded that it is better to feature detect rather than browser detect these days
    • LCB
      LCB over 7 years
      @bobince Maybe "mobile" browser means touchable and small screen?
    • Steven Koch
      Steven Koch over 3 years
      Most of the time ask isMobile is a weak question... what you do with this information? preferer a strategy of feature detection. such have screen size less than XXX? Have Bluetooth? have a touch screen? and so on... Use the user agent information to detect it's also a weak feature that could be outdated and fail in some cases.
    • MisterGeeky
      MisterGeeky over 3 years
      Just use the css media query, specify min-width and max-width. It's overkill to classify the userAgent.
    • llobet
      llobet over 3 years
      For React users: react-device-detect
    • gdibble
      gdibble about 2 years
      @ave I strongly lobby toward re-selection of a correct answer for this popular topic. userAgent string detection is fraught with problems and superior strategies such as feature detection have existed since your initial question almost 10y ago. Let's not lead people astray; better to lead to better/modern solutions. Thanks!
  • Michael Zaporozhets
    Michael Zaporozhets over 11 years
    this is actually super unique and awesome, do you mind if I add it to my answer?
  • xec
    xec over 11 years
    the test method is not case sensitive, but your regex is. you could just flag for case insensitive regex with an "i" at the end and do /iphone|etc/i.test(navigator.userAgent)
  • yoav barnea
    yoav barnea over 11 years
    thank you for the compliment. of course i don't mind. i didn't tested it though, so i would love to get some implementation feedbacks
  • Dave Hilditch
    Dave Hilditch over 11 years
    This is probably not going to work for long. 1) Tablets can have decent screen sizes, you want them to display full desktop website but they will have this property 2) Windows 8 is here and with it a bunch of laptops with touch screen and screens that rotate.
  • yoav barnea
    yoav barnea over 11 years
    as for your first point about Tablets with decent screen sizes- I think you could make the same arguments for all others solutions as well (a tablet with big screen that is been tracked as small screen). anyway the idea here is to search for property that is been shared by small devices instead of keep maintence long code and add regex with every new coming device/vesion/model. I think device detection is belong to the past and today we need to focus on feature detection. again I will be glad to here about more suitable property for that matter...
  • Richard Lovejoy
    Richard Lovejoy over 11 years
    Hi I just visited the detectmobilebrowsers.com link on my iPad 3, iOS 6.1.2, and it says "No mobile browser detected".
  • Michael Zaporozhets
    Michael Zaporozhets over 11 years
    @RichardLovejoy when building sites, the ipad is generally not considered a mobile.
  • John
    John about 11 years
    Thanks for shedding some light , the latest version on detectmobilebrowsers.com looks slightly different in that it takes the site it redirects to if mobile as parameter to the annonymouse function
  • Michael Zaporozhets
    Michael Zaporozhets about 11 years
    @John indeed they've mixed some stuff up however the regex hasn't changed since October last year so the above code is still up to date :)
  • ChrisRich
    ChrisRich about 11 years
    Simple solution to a complex problem. I like it!
  • molokoloco
    molokoloco about 11 years
    > Firefox mobile on android doesn't seem to have "'orientation' in window"
  • molokoloco
    molokoloco about 11 years
    Sorry.. ok for me it work well like that now. "if (Modernizr.touch) /* ... */ " and go on...
  • Gras Double
    Gras Double about 11 years
    From the about page: Android tablets, iPads, Kindle Fires and PlayBooks are not detected by design. To add support for tablets, add |android|ipad|playbook|silk to the first regex.
  • Bojangles
    Bojangles about 11 years
    Love it and works perfectly, thankyou. For my solution I was just after simple.
  • molokoloco
    molokoloco about 11 years
    Google TV is Android too. What define a mobile ? Screen Size ? Touch ? deviceOrientation ? When i design it's more a question of mousehover or not, big bouton or small links. So, for now, i run with "if (Modernizr.touch)" :)
  • Michael Zaporozhets
    Michael Zaporozhets about 11 years
    The question is not "How should I go about detecting a mobile browser?" but "how can i get a boolean return from a function such as that which i saw on detectmobilebrowsers.com?"..not really understanding the downvotes but okay
  • Volker E.
    Volker E. almost 11 years
    I'd take care with this approach. It seems not to be supported thoroughly, just by iOS and some Android devices.
  • marksyzm
    marksyzm almost 11 years
    Gawd, this whole idea of user agents is awful and really, really needs to stop. We really need to stop allowing clients to fight against the tide and just stick with media queries. If they want to do redirects based on scale for particular pages, then just check the range of a particular media query via JS i.e. tylergaw.com/articles/reacting-to-media-queries-in-javascrip‌​t
  • Michael Zaporozhets
    Michael Zaporozhets almost 11 years
    @ChristopherFrancisco I wish I could take credit for it hahaha
  • Hanna
    Hanna almost 11 years
    That website is not detecting my Nokia Lumia 928 (Windows Phone) as being a mobile device, despite it have an iemobile check. Anyone know a workaround?
  • siannopollo
    siannopollo over 10 years
    I just tested this on an iPhone (iOS 7) and it works if the device is in landscape orientation, but not portrait.
  • shuckster
    shuckster over 10 years
    I haven't tested on mobile yet, but sessionStorage.desktop doesn't exist in either Safari, Chrome, or Firefox (all newest versions at time of post). You get an up-vote though, since your solution goes in a better direction than others. But don't forget to use var mobile = instead of mobile =.
  • Admin
    Admin over 10 years
    @DoubleGras Would you mind showing where exactly to add that? Thank you so much in advance!
  • Gras Double
    Gras Double over 10 years
    In each code, there are 2 regexes: the first one checks in the whole user agent, the second one only checks the first 4 characters. Add the provided fragment to the first regex, like so, as of today: ...|xda|xiino|android|ipad|playbook|silk/i
  • MistereeDevlord
    MistereeDevlord over 10 years
    this varient if(window.orientation !== undefined) {...} should be enough
  • SomeShinyObject
    SomeShinyObject over 10 years
    Why not make any() a for...in loop of ORed isMobile members?
  • Judah Gabriel Himango
    Judah Gabriel Himango over 10 years
    For those who say we should just rely on media queries, this often doesn't cut it. For example, I have a website that plays HTM5 audio, and mobile browsers don't behave the same as they do on desktop browsers; such as iOS requiring user interaction before playing audio. These sorts of things can't be detected by media queries, nor by Modernizr.
  • Mudaser Ali
    Mudaser Ali about 10 years
    @ChristopherW i had created its plugin and modified code as you advised
  • Lex
    Lex about 10 years
    I prefer this, not for full fledged mobile detection. But as a helper work around to the limited orientation support on desktop. The accepted answer is also risky, if that list isn't up to date the function won't work across all browsers. And given its regex nature the chances of someone maintaining it are slim. This option is clear, short, succinct FTW
  • Jeffrey Gilbert
    Jeffrey Gilbert about 10 years
    Also a good idea not to use indexOf with older browsers still being around which don't support that method, or to use a polyfill. It's not necessary to use toLowerCase on a list of lowercase values, nor is it necessary to do so if you're running /ipad|iphone|etc/i.test(navigator.userAgent) instead of the slow loop you have up there.
  • Alkanshel
    Alkanshel about 10 years
    @marksyzm You seem to be approaching this from a web design perspective, but in the realm of web applications, it's not uncommon at all to have to confine yourself to arbitrary business rules regarding how things display on mobile browsers regardless of screen size.
  • marksyzm
    marksyzm about 10 years
    I know, but that's still the problem.
  • valir
    valir almost 10 years
    I tried different browsers on the same Android 4.4.4 device: Chrome - OK; Firefox - Not working; Dolphin - OK.
  • rharriso
    rharriso over 9 years
    The updated regex fails in iBooks on iPad. Returns false. The original response returns true.
  • Michael Zaporozhets
    Michael Zaporozhets over 9 years
    Hi @rharriso, I've just updated the script with the latest regex. Let me know if it works iBooks now.
  • rharriso
    rharriso over 9 years
    @MichaelZaporozhets, I just ran again through the inspector. Still the function above still returns false. Below is the useragent. "Mozilla/5.0 (iPad; CPU OS 8_0_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12A405 Safari/600.1.4"
  • Michael Zaporozhets
    Michael Zaporozhets over 9 years
    @rharriso Ah sorry, I didn't notice that you were on an iPad in the first comment. Please read the 1st and 2nd comments on this comment thread.
  • rharriso
    rharriso over 9 years
    @MichaelZaporozhets. difference of opinion then. I'll stick with the original regex then.
  • Michael Zaporozhets
    Michael Zaporozhets over 9 years
    @rharriso I think i'll just write an alternate version that covers iPads too, given the demand.
  • David Oliveros
    David Oliveros over 9 years
    What does the "b" in function(a, b) stands for? you are clearly sending only one argument to the function
  • Mudaser Ali
    Mudaser Ali over 9 years
    @Rob_vH i had put this code into github (github.com/smali-kazmi/detect-mobile-browser) with some advance features; you are open to send suggestions there as well
  • Shaiju T
    Shaiju T over 9 years
    why not find the size of screen instead from here and here or media queries in css or media queries in javascript
  • surfbuds
    surfbuds over 9 years
    This won't work on a nexus 7 tablet because the user agent doesn't include the "mobile" keyword after Android, while it does on an Android smartphone. The regex (android|bb\d+|meego).+mobile requires that android be followed by one or more of anything and then "mobile" which is not the case on tablet. Thus the comment from @GrasDouble to resolve the issue on various tablet types. However it might be more efficient to put android|ipad|playbook|silk| at the start of the 1st regexp instead of at the end.
  • Michael Zaporozhets
    Michael Zaporozhets about 9 years
    @user2005009 I've added a function that will include tablets to the answer.
  • B2K
    B2K almost 9 years
    Just wondering how Modernizr.touch would work when on a touchscreen desktop device.
  • CSS
    CSS almost 9 years
    This one gets my upvote for content, but I'm trying to figure out how to convert it to John Papa's styling and having some difficulty. Still quite new to AngularJS as a whole (about a month into knowledge of it) and the vm. notation angles the learning curve upward a bit. Any help? -C§ EDIT: I'm trying to unit test it with karma-jasmine is why I ask.
  • raacer
    raacer almost 9 years
    .substr(0,4) returns first 4 letters. How does it detect "android.+mobile"?
  • JackW
    JackW almost 9 years
    @raacer there are actually two regexes in the answer (both on the same line) - the first one checks against the entire UA string, and looks for android, mobile etc, while the second one only checks against the first 4 characters of the UA.
  • Eolis
    Eolis over 8 years
    I only need to detect a mobile device on my site to determine weither to use touchstart events or click events; the breakpoints are all irrelevant of window size and put in place to ensure the site is formatted nicely. so for a solution to detect weither or not I want touch events (any phone or tablet) or click events (a laptop / desktop) this is an awesome solution. thanks so much; the regex answers were complex and require constant maintenance.
  • CarbonDry
    CarbonDry over 8 years
    I've read through all the comments. Would it not be better to detect its a mobile device by testing the default "click event". For example, query screen size is not good enough for me, because I need to serve a different experience based on whether the user is using their fingers or a mouse. Is this possible? Edit: It appears it could be stackoverflow.com/questions/4817029/…
  • Ivan
    Ivan over 8 years
    I like this solution because it answers the question of "is this mobile" as simply as possible. The question isn't "how do I detect small screen sizes", but rather "Detecting a mobile browser."
  • Gajus
    Gajus over 8 years
    window.orientation is a deprecated property (developer.mozilla.org/en-US/docs/Web/API/Window/orientation‌​, compat.spec.whatwg.org/#dom-window-orientation) that some mobile browsers choose to support for unknown reasons. Same browsers implement window.screen.orientation (which is defined in desktop browsers too). I can only assume that window.orientation is left there for legacy reasons and should therefore not be used in new applications.
  • John Slegers
    John Slegers over 8 years
    Why not just use screen.width instead? It seems to me that's more reliable than window.matchMedia.
  • stujo
    stujo over 8 years
    Good point John, I can't recall exactly what I was thinking at the time, it seems unlikely (looking at it now) that the second clause would return true if the first is false. There must have been some reason I added it though.
  • John Slegers
    John Slegers over 8 years
    Most decent programmers feel ashamed when they see code they wrote themselves a year earlier. Those who don't just haven't grown as programmers ;-)
  • ʇsәɹoɈ
    ʇsәɹoɈ about 8 years
    Window resolution has nothing to do with whether a browser is on a mobile device or not. For example, lots of desktop browsers run in non-full-screen windows. If you present a UI designed for handheld screens to those browsers, their users are going to have a frustrating experience.
  • Syamsoul Azrien
    Syamsoul Azrien about 8 years
    how to check if the device are touchscreen ?
  • Jonathan Allard
    Jonathan Allard about 8 years
    You've answered another question than what was asked. Rather than "how can I detect mobile?", you've answered "how can I detect certain features?". Not all device detection is for feature detection. What if we were looking to get statistics about devices? Then no, "feature detection" is not "much better than [figuring out device]".
  • stripybadger
    stripybadger about 8 years
    @MichaelZaporozhets I realise you just copied it from detectmobilebrowsers.com, but I'm almost tempted to downvote this because of the unmaintainability of that code. It's not just the horific regexes, but why have it wrapped all in a self executing function and why not have a sensibly named variable? Why is it just 'a'?
  • Michael Zaporozhets
    Michael Zaporozhets about 8 years
    @stripybadger Don't shoot the messenger! DMB does it this way (I presume they have an automated compilation script that pushes out the latest 'combination' or so which you have 'a' as the variable. One could of course change this, but maintaining any other updates apart from the return response each update from DMB simply doesn't seem worth my time.
  • oriadam
    oriadam almost 8 years
    Please add Mobile to your RX
  • Anton Kuzmin
    Anton Kuzmin almost 8 years
    What if desktop's monitor supports touch?
  • Tigger
    Tigger almost 8 years
    @HappyCoder I believe it is up to the OS to tell the browser when the touch screen on a desktop is active. So, yes this check should still be valid.
  • Amyth
    Amyth almost 8 years
    And howcome this does not recognize safari on iphone ?
  • Luca P.
    Luca P. almost 8 years
    Can you expand on what browser you are using (exact UA string would be perfect), what data you are getting and what you are expecting?
  • amdev
    amdev over 7 years
    thanks for tablet, it's very usefull ! For me what to do "mobile" is not size, but touchscreen because a lot of css feature like "hover" on menu or tooltip have no sense without a mouse even if the screen is 4000px width
  • Cody
    Cody over 7 years
    (+1), however, my desktop I'm using now has a touchScreen, and it isn't always consistent for touchstart|end|etc.
  • e-zero
    e-zero over 7 years
    Nice Code! I agree that using Javascript to do this is can be painful and requires updating for new devices/browsers on the market, but at at this moment in time I would say use Javascript. Choosing CSS media queries can attempt to detect mobile/tablet but would still require updating for new devices. I would prefer using Javascript since I can keep the mobile/tablet detection code in one place and be able to do anything I need with Javascript code (including modifying the CSS). If you think you found better Javascript code, please share. Btw, is this code being kept up to date?
  • MonsterMMORPG
    MonsterMMORPG over 7 years
    hi is this function up to date? window.mobileAndTabletcheck = function() {
  • Rahul K
    Rahul K over 7 years
    It really helped. A LOT. Thanks
  • Erick Voodoo
    Erick Voodoo about 7 years
    What is about landscape?
  • toing_toing
    toing_toing about 7 years
    This is not very useful for certain scenarios. If the desktop browser is resized it maybe detected incorrectly as a mobile browser
  • noblerare
    noblerare about 7 years
    Can someone explains how this function works? How is check being updated?
  • Jim Pedid
    Jim Pedid about 7 years
    It uses the closure property for the check variable, and sets if if the if statement is true. There's probably better ways to write this.
  • J.T. Taylor
    J.T. Taylor almost 7 years
    Bootstrap datepicker uses the following: if ( window.navigator.msMaxTouchPoints || 'ontouchstart' in document) { this.input.blur(); }
  • Tigger
    Tigger almost 7 years
    @J.T.Taylor It looks like Microsoft is recommending navigator.maxTouchPoints (no ms prefix). There is also an MDN article to check.
  • twicejr
    twicejr almost 7 years
    This is not the answer, but it deserves more than just a comment. The question is: why do you want to detect a browser and then you will probably want to know it because of the (lack of) touch only. Responsive webdesign suffices in most if not all cases.
  • Maxim
    Maxim over 6 years
    Orientation approach is really nice! ))
  • hewiefreeman
    hewiefreeman over 6 years
    That regex is some dangerous stuff you've got there. You could poke someone's eye out with that thing!
  • Mike Wells
    Mike Wells over 6 years
    I too tried wurfl, I am on a iPhone 5C running IOS 11.2. Its not recognising Safari as a mobile browser. I'm expecting to use "is_mobile" : true and then "form_factor": Smartphone and its not returning either.
  • Luca P.
    Luca P. over 6 years
    I had to turn to the Mobile Data gurus in the company and they tell me that OS 11.2 doesn't run on the 5C. Lowest device is the 5S. So something isn't right in what you wrote. Feel free to contact ScientiaMobile offline to verify where the disconnect might be. Thanks
  • Enrikisimo Lopez Ramos
    Enrikisimo Lopez Ramos over 6 years
    what if use hammer.. for me return true... ('ontouchstart' in document.documentElement)
  • Master James
    Master James over 6 years
    Not expecting this to change I opted to make it more static without a function call. It could be done where window.mobileCheck is a boolean that the comprehensive line makes true.
  • Chuck Le Butt
    Chuck Le Butt over 6 years
    Nice. Very useful in certain situations
  • skwidbreth
    skwidbreth about 6 years
    I like your window.orientation solution, but the docs say it's deprecated! developer.mozilla.org/en-US/docs/Web/API/Window/orientation
  • Vic
    Vic about 6 years
    this method is such a mess, why not just have it return a boolean value??
  • Vic
    Vic about 6 years
    why not just return the if condition instead of having this whole check variable?
  • Michael Zaporozhets
    Michael Zaporozhets about 6 years
    @Vic it... does?
  • Vic
    Vic about 6 years
    @MichaelZaporozhets im talking about the self executing function after var check = false
  • Michael Zaporozhets
    Michael Zaporozhets about 6 years
    @Vic ah yeah- honestly, I'm pretty sure I left that in there to 'show working' from the source. That being said- no need for it stay that ugly now. feel free to suggest an edit. Probably time for an es6 version too tbh.
  • blissfool
    blissfool about 6 years
    Touch screen laptops will be detected as mobile device. As well as touch screen monitors for desktops. Believe it or not, you will also run into issue if you are using touchscreen device to RDP into another device that is does not have a touch screen.
  • blissfool
    blissfool about 6 years
    Won't work with laptops and dekstops with touchscreen monitors. Also will be an issue with hybrid pc's like Surface. Less of an issue with desktops but there are more touchscreen laptops being sold these days.
  • Neo Morina
    Neo Morina about 6 years
    @blissfool i guess this will not be the right way for detecting mobile devices then.
  • Koshinae
    Koshinae about 6 years
    Hello, from the future. Now even the 2K resolution is not unique on mobiles, so please refrain using that as a check.
  • blissfool
    blissfool about 6 years
    Unfortunately, no. But, it might still be a viable option for a very limited use case.
  • Heitor
    Heitor almost 6 years
    To make it more elegant you should make all te code in just one if-else if-else if block.
  • Heitor
    Heitor almost 6 years
    Orientation approach is NOT nice because Windows 8 and higher can change orientation.
  • Heitor
    Heitor almost 6 years
    A PC is essentially different from mobile devices on usability, horrable answer!!
  • Pavlo Oliinyk
    Pavlo Oliinyk almost 6 years
    .includes not sopport by IE-11
  • Bruno Francisco
    Bruno Francisco almost 6 years
    I read detectmob as detectmobster and for a second I thought you were police
  • ankh-morpork
    ankh-morpork almost 6 years
    +1 for checking dimensions. I realized the reason I wanted to detect mobile in the first place was to accommodate smaller screen widths.
  • Maytha8
    Maytha8 over 5 years
    To use window.mobilecheck, you need to use it as window.mobilecheck(). Why is it a function and not a boolean variable?
  • Michael Zaporozhets
    Michael Zaporozhets over 5 years
    @Mth see o.p: "I'm looking for a function..."
  • Maytha8
    Maytha8 over 5 years
    I get it. The question says he wants a function that returns a boolean variable. Anyways, thanks for the function!
  • Maxim
    Maxim over 5 years
    What about laptops with touch enabled displays?
  • Maxim
    Maxim over 5 years
    @PashaOleynik a polyfill can fix that
  • Pablo
    Pablo over 5 years
    never write code, that is based on an exception, that will be throwen for sure in any case...
  • Cory Kleiser
    Cory Kleiser over 5 years
    I know you are just offering it as an alternative; but why not use window.screen.width and window.screen.height to capture the device screen size instead of window.innerWidth and window.innerHeight? This way the function won't detect a false screen size when the browser is not full screen. I tested this and it works reliably on Chrome 71, Safari 12, Firefox 64, Edge 18, IE11, Android (Chrome and Firefox), iPhone and iPad (Safari and Chrome for both).
  • Sora2455
    Sora2455 over 5 years
    Note that the Battery Status API is being removed from browsers.
  • Sora2455
    Sora2455 over 5 years
    I would check for !matchMedia("(any-pointer:fine)").matches myself. ("No mouse plugged in", rather than "has a touch screen".
  • vhs
    vhs over 5 years
    Battery Status API removed from Firefox but remains a W3C Candidate Recommendation since July 2016, continues to function in popular browsers and is useful in shaping experience.
  • Neo Morina
    Neo Morina over 5 years
    @Sivic it only gets thrown when a TouchEvent does not exists and the code above catches it and returns false. This is not the case on Mobile or Tablet or other Touch Screen devices.
  • Jonny
    Jonny about 5 years
    True, window.orientation is deprecated but window.screen.orientation does not (yet) work on iOS 11.x (returns 'undefined').
  • Ajay G.
    Ajay G. about 5 years
    How about using this with a check on screen size? Considering Bootstrap switches to mobile view below 768px?
  • Jeff Clayton
    Jeff Clayton almost 5 years
    Windows 8 and newer are focused on adding support for mobiles but also hybrids (laptops that can convert to large pads) which is why orientation fails as a detection method even if moz wasn't referring to it as deprecated.
  • trusktr
    trusktr almost 5 years
    @AkarshSatija Does the performance drop from those 5 regex checks actually impact any of your applications? I would be very surprised if it did. Premature optimization can be a waste of time...
  • Akarsh Satija
    Akarsh Satija almost 5 years
    @trusktr regex match is an expensive operation and handheld devices are always a little challenge at computing. There's no rationale around against Premature optimizations but they come back and bite very soon at your worsts. Also, why not go for optimization when better options are available?
  • John
    John almost 5 years
    This works whereas my last script would get tricked by people using the browser's zoom feature (e.g. a guy I was talking with on a 13" screen with 4K who dropped to 1080p and still had to use zoom). Worked on my iPhone (Safari/Firefox) and Android devices (Waterfox/Chrome/"Browser"). Definitely much more reliable than all the higher up-voted answers.
  • Walker Leite
    Walker Leite over 4 years
    Detecting chrome in Mac as mobile device
  • StayCool
    StayCool over 4 years
    does not detect FireFox fennec on an Android for which I supplemented with navigator.userAgent.toLowerCase().indexOf('fennec') > -1 (perhaps not the best supplement..)
  • Zortext
    Zortext over 4 years
    Do not rely on window.innerWidth for detecting mobile devices. It may give suprisingly large number if the site has elements larger than window width and mobile browser automatically scales the page. Instead use document.body.offsetWidth or window.screen.width
  • Charlie Reitzel
    Charlie Reitzel over 4 years
    Useful for the case of detecting a device where a mobile app could be installed. You don't care about the browser, per se. Just the device / OS.
  • Alex Sorokoletov
    Alex Sorokoletov over 4 years
    Nexus 7 tablet with Android does not have Mobile in the user agent string
  • Batailley
    Batailley over 4 years
    Additionnally you can test the hover property: for smartphones and touchscreens @media (hover: none) and (pointer: coarse)
  • Chunky Chunk
    Chunky Chunk over 4 years
    @AlexSorokoletov Also for the MDN article If the device is large enough that it's not marked with “Mobi”, you should serve your desktop site (which, as a best practice, should support touch input anyway, as more desktop machines are appearing with touchscreens).
  • zenw0lf
    zenw0lf about 4 years
    I think this is would work anywhere without polyfills: const isMobile = /Mobi/.test(window.navigator.userAgent)
  • GirlCode
    GirlCode about 4 years
    It's from Win 7 with Graphical Software installed can change orientation but ask yourself a question, who can on Desktop / Laptop use a another screen orientation like Portrait instead of Landscape and use i for even more than 1 minute. No one !!! Changing orientation on Desktop means you'll start reading characters on your screen from bottom to top.
  • T.Woody
    T.Woody about 4 years
    Note that chrome is deprecating navigator.userAgent 9to5google.com/2020/01/14/…
  • oriadam
    oriadam about 4 years
    may i suggest any: () => /Mobile/.test(navigator.userAgent)
  • Ali Mert Çakar
    Ali Mert Çakar almost 4 years
    Then simply use if(window.orientation || window.screen.orientation) {}. Problem solved
  • Benj Sanders
    Benj Sanders almost 4 years
    @AliMertCakar I agree, but chrome (and may be others) defines window.screen.orientation in the desktop. Cheers.
  • Aleks
    Aleks almost 4 years
    if a user is using Chrome in Desktop mode, it fill fail. Combined with media query would work alright
  • Below the Radar
    Below the Radar over 3 years
    window.mobileAndTabletCheck function does not detect my iPad Pro
  • Michael Zaporozhets
    Michael Zaporozhets over 3 years
    @BelowtheRadar Unfortunately iPad Pro Safari does not identify itself as a tablet or mobile device, which disables this method of identification. If you're looking to target the ipad and similar devices, I'd probably look at browser api sniffing methods instead. See this answer for further information stackoverflow.com/questions/57776001/…
  • oldboy
    oldboy over 3 years
    how widely "supported" is checking any-pointer and hover with MQs? i know MDN says theyre candidate recommendations, sooo
  • oldboy
    oldboy over 3 years
    checking battery, thats smart
  • gsxrboy73
    gsxrboy73 over 3 years
    According to this: caniuse.com/matchmedia, it's pretty widely support for all modern browsers. The only browsers to be concerned about are mobile browsers since that function will return false for all other browsers whether they support matchMedia or not. So based on caniuse.com, only 0.03% of global users are not supported.
  • GajendraSinghParihar
    GajendraSinghParihar over 3 years
    "No mobile browser detected" for iPad Air 2 on detectmobilebrowsers.com
  • AlejandroAlis
    AlejandroAlis over 3 years
    better to use window.screen.width because if the window is not maximized you will get a "wrong" answer
  • karel
    karel over 3 years
    window.orientation is deprecated. This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
  • Hillsie
    Hillsie about 3 years
    Neat! Still works in 2021, albeit I'd add a let isMobile= now
  • Ictus
    Ictus about 3 years
    screen.orientation is also supported on desktop developer.mozilla.org/en-US/docs/Web/API/Screen/…
  • Pacerier
    Pacerier about 3 years
    Works on Windows Phone / webOS / Blackberry ?
  • Mikepote
    Mikepote almost 3 years
    What if the feature I want to detect is how powerful the device CPU is? I need to lower quality on mobile phones...
  • Freddy Daniel
    Freddy Daniel almost 3 years
    It worked! thanks so much.
  • Michael Terry
    Michael Terry over 2 years
    I can't see any problem with just combining clues, like screen width (not window width) and touch events.
  • Jeff Lee
    Jeff Lee over 2 years
    To go deeper on @lctus's comment, as of this writing, I don't think answer is usable any more, and should be updated to that effect. On the desktop versions of both Chrome and Firefox, screen.orientation is defined, so this solution will provide false positives for at least those desktop browsers.
  • Sebastian Simon
    Sebastian Simon over 2 years
    See this other answer. .orientation is no longer a solution to this problem.
  • Roko C. Buljan
    Roko C. Buljan over 2 years
    "Just don't use this" ? You can always delete your answer. Also, all those .match( ... hm. RegExp and .test() is a simpler variant.
  • Roko C. Buljan
    Roko C. Buljan over 2 years
    This was already answered here. Why you think your answer adds any additional context over the existing one from 2018? It's already absolutely clear that window.matchMedia('mediaString').matches returns a boolean.
  • insign
    insign over 2 years
    @RokoC.Buljan well, what may seems obviously to you maybe is not to everyone. So I decided to make my own answer.
  • Magoo
    Magoo over 2 years
    Careful there is an extra | in mobileAndTabletCheck regex which makes the whole test wrong. Tried to edit but it's under 6 characters, so i can't. Any mod ?
  • sskular
    sskular over 2 years
    maxTouchPoints - what if laptop has a touch screen?
  • gdibble
    gdibble over 2 years
    @sskular that was a very good question---thanks. I tested it for us, as I have a Lenovo X1 Yoga available with Win10. 1) localStorage.mobile is undefined no matter what. 2) When the laptop is in keyboard mode, window.navigator.maxTouchPoints is 1; so isMobile was false. 3) When the keyboard is flipped back and the laptop is in tablet mode, window.navigator.maxTouchPoints is 10; so isMobile was true. Now the subjective question: Do we consider a tablet or laptop in tablet-mode as mobile? 🤔
  • gdibble
    gdibble about 2 years
    Agent strings will be spoofed. 2022 and long before, feature detection is far superior and reliable. Mandalorians would say, "userAgent is Not the way."
  • Krishna Karki
    Krishna Karki about 2 years
    Doesn't work any more
  • Rob
    Rob about 2 years
    What about android TVs.