Detecting a mobile browser
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);
ave
Updated on April 29, 2022Comments
-
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 almost 12 yearsRelated: stackoverflow.com/questions/3514784/….
-
KyelJmD almost 12 yearsTry reading this. stackoverflow.com/questions/743129/…
-
UltraInstinct almost 12 yearsIt would be better if server did this and sent across different versions of JS file..
-
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. ButVary: User-Agent
makes the response uncachable in IE. -
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 almost 12 years@bobince Thanks for that. Every single day I get to learn something new at SO! :)
-
Michael Zaporozhets over 11 yearsSo 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 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 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 about 9 yearsIt's generally regarded that it is better to feature detect rather than browser detect these days
-
LCB over 7 years@bobince Maybe "mobile" browser means touchable and small screen?
-
Steven Koch over 3 yearsMost 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 over 3 yearsJust use the css media query, specify min-width and max-width. It's overkill to classify the userAgent.
-
llobet over 3 yearsFor React users: react-device-detect
-
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 over 11 yearsthis is actually super unique and awesome, do you mind if I add it to my answer?
-
xec over 11 yearsthe 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 over 11 yearsthank 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 over 11 yearsThis 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 over 11 yearsas 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 over 11 yearsHi I just visited the detectmobilebrowsers.com link on my iPad 3, iOS 6.1.2, and it says "No mobile browser detected".
-
Michael Zaporozhets over 11 years@RichardLovejoy when building sites, the ipad is generally not considered a mobile.
-
John about 11 yearsThanks 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 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 about 11 yearsSimple solution to a complex problem. I like it!
-
molokoloco about 11 years> Firefox mobile on android doesn't seem to have "'orientation' in window"
-
molokoloco about 11 yearsSorry.. ok for me it work well like that now. "if (Modernizr.touch) /* ... */ " and go on...
-
Gras Double about 11 yearsFrom 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 about 11 yearsLove it and works perfectly, thankyou. For my solution I was just after simple.
-
molokoloco about 11 yearsGoogle 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 about 11 yearsThe 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. almost 11 yearsI'd take care with this approach. It seems not to be supported thoroughly, just by iOS and some Android devices.
-
marksyzm almost 11 yearsGawd, 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-javascript
-
Michael Zaporozhets almost 11 years@ChristopherFrancisco I wish I could take credit for it hahaha
-
Hanna almost 11 yearsThat 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 over 10 yearsI just tested this on an iPhone (iOS 7) and it works if the device is in landscape orientation, but not portrait.
-
shuckster over 10 yearsI 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 usevar mobile =
instead ofmobile =
. -
Admin over 10 years@DoubleGras Would you mind showing where exactly to add that? Thank you so much in advance!
-
Gras Double over 10 yearsIn 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 over 10 yearsthis varient if(window.orientation !== undefined) {...} should be enough
-
SomeShinyObject over 10 yearsWhy not make
any()
a for...in loop of ORedisMobile
members? -
Judah Gabriel Himango over 10 yearsFor 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 about 10 years@ChristopherW i had created its plugin and modified code as you advised
-
Lex about 10 yearsI 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 about 10 yearsAlso 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 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 about 10 yearsI know, but that's still the problem.
-
valir almost 10 yearsI tried different browsers on the same Android 4.4.4 device: Chrome - OK; Firefox - Not working; Dolphin - OK.
-
rharriso over 9 yearsThe updated regex fails in iBooks on iPad. Returns false. The original response returns true.
-
Michael Zaporozhets over 9 yearsHi @rharriso, I've just updated the script with the latest regex. Let me know if it works iBooks now.
-
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 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 over 9 years@MichaelZaporozhets. difference of opinion then. I'll stick with the original regex then.
-
Michael Zaporozhets over 9 years@rharriso I think i'll just write an alternate version that covers iPads too, given the demand.
-
David Oliveros over 9 yearsWhat does the "b" in function(a, b) stands for? you are clearly sending only one argument to the function
-
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 over 9 years
-
surfbuds over 9 yearsThis 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 about 9 years@user2005009 I've added a function that will include tablets to the answer.
-
B2K almost 9 yearsJust wondering how Modernizr.touch would work when on a touchscreen desktop device.
-
CSS almost 9 yearsThis 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 almost 9 years.substr(0,4) returns first 4 letters. How does it detect "android.+mobile"?
-
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 over 8 yearsI 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 over 8 yearsI'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 over 8 yearsI 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 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 implementwindow.screen.orientation
(which is defined in desktop browsers too). I can only assume thatwindow.orientation
is left there for legacy reasons and should therefore not be used in new applications. -
John Slegers over 8 yearsWhy not just use
screen.width
instead? It seems to me that's more reliable thanwindow.matchMedia
. -
stujo over 8 yearsGood 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 over 8 yearsMost 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Ɉ about 8 yearsWindow 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 about 8 yearshow to check if the device are touchscreen ?
-
Jonathan Allard about 8 yearsYou'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 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 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 almost 8 yearsPlease add
Mobile
to your RX -
Anton Kuzmin almost 8 yearsWhat if desktop's monitor supports touch?
-
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 almost 8 yearsAnd howcome this does not recognize safari on iphone ?
-
Luca P. almost 8 yearsCan 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 over 7 yearsthanks 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 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 over 7 yearsNice 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 over 7 yearshi is this function up to date? window.mobileAndTabletcheck = function() {
-
Rahul K over 7 yearsIt really helped. A LOT. Thanks
-
Erick Voodoo about 7 yearsWhat is about landscape?
-
toing_toing about 7 yearsThis is not very useful for certain scenarios. If the desktop browser is resized it maybe detected incorrectly as a mobile browser
-
noblerare about 7 yearsCan someone explains how this function works? How is
check
being updated? -
Jim Pedid about 7 yearsIt 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 almost 7 yearsBootstrap datepicker uses the following: if ( window.navigator.msMaxTouchPoints || 'ontouchstart' in document) { this.input.blur(); }
-
Tigger almost 7 years@J.T.Taylor It looks like Microsoft is recommending
navigator.maxTouchPoints
(noms
prefix). There is also an MDN article to check. -
twicejr almost 7 yearsThis 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 over 6 yearsOrientation approach is really nice! ))
-
hewiefreeman over 6 yearsThat regex is some dangerous stuff you've got there. You could poke someone's eye out with that thing!
-
Mike Wells over 6 yearsI 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. over 6 yearsI 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 over 6 yearswhat if use hammer.. for me return true... ('ontouchstart' in document.documentElement)
-
Master James over 6 yearsNot 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 over 6 yearsNice. Very useful in certain situations
-
skwidbreth about 6 yearsI like your
window.orientation
solution, but the docs say it's deprecated! developer.mozilla.org/en-US/docs/Web/API/Window/orientation -
Vic about 6 yearsthis method is such a mess, why not just have it return a boolean value??
-
Vic about 6 yearswhy not just return the
if
condition instead of having this wholecheck
variable? -
Michael Zaporozhets about 6 years@Vic it... does?
-
Vic about 6 years@MichaelZaporozhets im talking about the self executing function after
var check = false
-
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 about 6 yearsTouch 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 about 6 yearsWon'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 about 6 years@blissfool i guess this will not be the right way for detecting mobile devices then.
-
Koshinae about 6 yearsHello, from the future. Now even the 2K resolution is not unique on mobiles, so please refrain using that as a check.
-
blissfool about 6 yearsUnfortunately, no. But, it might still be a viable option for a very limited use case.
-
Heitor almost 6 yearsTo make it more elegant you should make all te code in just one if-else if-else if block.
-
Heitor almost 6 yearsOrientation approach is NOT nice because Windows 8 and higher can change orientation.
-
Heitor almost 6 yearsA PC is essentially different from mobile devices on usability, horrable answer!!
-
Pavlo Oliinyk almost 6 years
.includes
not sopport by IE-11 -
Bruno Francisco almost 6 yearsI read
detectmob
asdetectmobster
and for a second I thought you were police -
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 over 5 yearsTo use
window.mobilecheck
, you need to use it aswindow.mobilecheck()
. Why is it a function and not a boolean variable? -
Michael Zaporozhets over 5 years@Mth see o.p: "I'm looking for a function..."
-
Maytha8 over 5 yearsI get it. The question says he wants a function that returns a boolean variable. Anyways, thanks for the
function
! -
Maxim over 5 yearsWhat about laptops with touch enabled displays?
-
Maxim over 5 years@PashaOleynik a polyfill can fix that
-
Pablo over 5 yearsnever write code, that is based on an exception, that will be throwen for sure in any case...
-
Cory Kleiser over 5 yearsI know you are just offering it as an alternative; but why not use
window.screen.width
andwindow.screen.height
to capture the device screen size instead ofwindow.innerWidth
andwindow.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 over 5 yearsNote that the Battery Status API is being removed from browsers.
-
Sora2455 over 5 yearsI would check for !matchMedia("(any-pointer:fine)").matches myself. ("No mouse plugged in", rather than "has a touch screen".
-
vhs over 5 yearsBattery 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 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 about 5 yearsTrue, window.orientation is deprecated but window.screen.orientation does not (yet) work on iOS 11.x (returns 'undefined').
-
Ajay G. about 5 yearsHow about using this with a check on screen size? Considering Bootstrap switches to mobile view below 768px?
-
Jeff Clayton almost 5 yearsWindows 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 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 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 almost 5 yearsThis 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 over 4 yearsDetecting chrome in Mac as mobile device
-
StayCool over 4 yearsdoes not detect FireFox fennec on an Android for which I supplemented with navigator.userAgent.toLowerCase().indexOf('fennec') > -1 (perhaps not the best supplement..)
-
Zortext over 4 yearsDo 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 usedocument.body.offsetWidth
orwindow.screen.width
-
Charlie Reitzel over 4 yearsUseful 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 over 4 yearsNexus 7 tablet with Android does not have
Mobile
in the user agent string -
Batailley over 4 yearsAdditionnally you can test the hover property: for smartphones and touchscreens @media (hover: none) and (pointer: coarse)
-
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 about 4 yearsI think this is would work anywhere without polyfills:
const isMobile = /Mobi/.test(window.navigator.userAgent)
-
GirlCode about 4 yearsIt'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 about 4 yearsNote that chrome is deprecating
navigator.userAgent
9to5google.com/2020/01/14/… -
oriadam about 4 yearsmay i suggest
any: () => /Mobile/.test(navigator.userAgent)
-
Ali Mert Çakar almost 4 yearsThen simply use if(window.orientation || window.screen.orientation) {}. Problem solved
-
Benj Sanders almost 4 years@AliMertCakar I agree, but chrome (and may be others) defines window.screen.orientation in the desktop. Cheers.
-
Aleks almost 4 yearsif a user is using Chrome in Desktop mode, it fill fail. Combined with media query would work alright
-
Below the Radar over 3 years
window.mobileAndTabletCheck
function does not detect my iPad Pro -
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 over 3 yearshow widely "supported" is checking
any-pointer
andhover
with MQs? i know MDN says theyre candidate recommendations, sooo -
oldboy over 3 yearschecking battery, thats smart
-
gsxrboy73 over 3 yearsAccording 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 over 3 years"No mobile browser detected" for iPad Air 2 on detectmobilebrowsers.com
-
AlejandroAlis over 3 yearsbetter to use window.screen.width because if the window is not maximized you will get a "wrong" answer
-
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 about 3 yearsNeat! Still works in 2021, albeit I'd add a
let isMobile=
now -
Ictus about 3 yearsscreen.orientation is also supported on desktop developer.mozilla.org/en-US/docs/Web/API/Screen/…
-
Pacerier about 3 yearsWorks on Windows Phone / webOS / Blackberry ?
-
Mikepote almost 3 yearsWhat if the feature I want to detect is how powerful the device CPU is? I need to lower quality on mobile phones...
-
Freddy Daniel almost 3 yearsIt worked! thanks so much.
-
Michael Terry over 2 yearsI can't see any problem with just combining clues, like screen width (not window width) and touch events.
-
Jeff Lee over 2 yearsTo 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 over 2 yearsSee this other answer.
.orientation
is no longer a solution to this problem. -
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 over 2 yearsThis 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 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 over 2 yearsCareful there is an extra
|
inmobileAndTabletCheck
regex which makes the whole test wrong. Tried to edit but it's under 6 characters, so i can't. Any mod ? -
sskular over 2 yearsmaxTouchPoints - what if laptop has a touch screen?
-
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
isundefined
no matter what. 2) When the laptop is in keyboard mode,window.navigator.maxTouchPoints
is1
; so isMobile wasfalse
. 3) When the keyboard is flipped back and the laptop is in tablet mode,window.navigator.maxTouchPoints
is10
; so isMobile wastrue
. Now the subjective question: Do we consider a tablet or laptop in tablet-mode as mobile? 🤔 -
gdibble about 2 yearsAgent 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 about 2 yearsDoesn't work any more
-
Rob about 2 yearsWhat about android TVs.