A simple JS library that detects mobile devices.
Why use isMobile?
You probably shouldn't use this library unless you absolutely have to. In most cases, good responsive design solves the problem of controlling how to render things across different screen sizes. But there are always edge cases. If you have an edge case, then this library might be for you.
I had very specific requirements for a project when I created this:
- Redirect all iPhones, iPods, Android phones, and seven inch devices to the mobile site.
Yep, at the time, a completely separate site had already been created for mobile devices. So I couldn't depend on media queries, feature detection, graceful degradation, progressive enhancement, or any of the cool techniques for selectively displaying things. I had to find a way to redirect visitors on certain devices to the mobile site.
I couldn't do detection on the back-end, because the entire site was generated as HTML, and then cached and served by a CDN, so I had to do the detection client-side.
So I resorted to User-Agent (UA) sniffing.
I tried to keep the script small (currently ~1.5k bytes, minified) and simple, because it would need to execute in the
<head>, which is generally a bad idea, since JS blocks the downloading and rendering of all assets while it parses and executes. In the case of mobile redirection, I don't mind so much, because I want to start the redirect as soon as possible, before the device has a chance to start downloading and rendering other stuff. For non-mobile platforms, the script should execute fast, so the browser can quickly get back to downloading and rendering.
How it works in the browser
How it works in Node.js
You import and call the
Devices detected by isMobile
In a browser, the following properties of the global
isMobile object will either be
false. In Node,
isMobile will be whatever you named the variable.
isMobile.apple.device(any mobile Apple device)
isMobile.android.device(any mobile Android device; OkHttp user agents will match this)
Amazon Silk devices (also passes Android checks)
isMobile.amazon.device(any mobile Amazon Silk device)
isMobile.windows.device(any mobile Windows device)
isMobile.other.device(any "Other" device)
isMobile.any- any device matched
isMobile.phone- any device in the 'phone' groups above
isMobile.tablet- any device in the 'tablet' groups above
I include the minified version of the script, inline, and at the top of the
<head>. Cellular connections tend to suck, so it would be wasteful overhead to open another connection, just to download ~1.5kb of JS:
After checking out the repo, install dependencies:
Then build a minified, distributable JS file:
npm run build
It will be output to
You can then use it with a
<script> tag, bundle it with something else or follow the suggestion in the example above and include it inline to save opening another connection.
npm install ismobilejs
const isMobile = ;const userAgent = reqheaders'user-agent';console;