According toWhile Mozilla -Mozilla's Browser detection using the user agent now recommends against this solution:
Note: It's worth re-iterating: it's very rarely a good idea to use user agent sniffing. You can almost always find a better, more broadly compatible way to solve your problem!
it used to recommend:
In summary, we recommend looking for the string “Mobi” anywhere in the User Agent to detect a mobile device.
Like this:
if (/Mobi/.test(navigator.userAgent)) { // mobile! } This will match all common mobile browser user agents, including mobile Mozilla, Safari, IE, Opera, Chrome, etc.
Update for Android
EricL recommends testing for Android as a user agent also, as the Chrome user agent string for tablets does not include "Mobi" (the phone versions do however):
if (/Mobi|Android/i.test(navigator.userAgent)) { // mobile! }