UNPKG

8.14 kBMarkdownView Raw
1[![Build Status](https://travis-ci.org/kaimallea/isMobile.png)](https://travis-ci.org/kaimallea/isMobile)
2[![Node dependencies status](https://david-dm.org/kaimallea/isMobile.png)](https://david-dm.org/kaimallea/isMobile)
3[![](https://data.jsdelivr.com/v1/package/npm/ismobilejs/badge)](https://www.jsdelivr.com/package/npm/ismobilejs)
4
5# isMobile
6
7A simple JS library that detects mobile devices in both the browser and NodeJS.
8
9## Why use isMobile?
10
11### In the Browser
12
13You might not need this library. In most cases, [responsive design](https://en.wikipedia.org/wiki/Responsive_web_design) solves the problem of controlling how to render things across different screen sizes. I recommend a [mobile first](https://medium.com/@Vincentxia77/what-is-mobile-first-design-why-its-important-how-to-make-it-7d3cf2e29d00) approach. But there are always edge cases. If you have an edge case, then this library might be for you.
14
15My edge case at the time was redirecting users to a completely separate mobile site. I tried to keep this script small (**currently ~1.3k 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.
16
17#### How it works in the browser
18
19isMobile runs quickly during initial page load to detect mobile devices; it then creates a JavaScript object with the results.
20
21### In NodeJS
22
23You might want to use this library to do server-side device detection to minimize the amount of bytes you send back to visitors. Or you have your own arbitrary use case.
24
25#### How is works in NodeJS
26
27You import and call the `isMobile` function, passing it a user agent string; it then returns a JavaScript object with the results.
28
29## Devices detected by isMobile
30
31In a browser, the following properties of the global `isMobile` object will either be `true` or `false`. In Node, `isMobile` will be whatever you named the variable.
32
33### Apple devices
34
35- `isMobile.apple.phone`
36- `isMobile.apple.ipod`
37- `isMobile.apple.tablet`
38- `isMobile.apple.universal`
39- `isMobile.apple.device` (any mobile Apple device)
40
41### Android devices
42
43- `isMobile.android.phone`
44- `isMobile.android.tablet`
45- `isMobile.android.device` (any mobile Android device; OkHttp user agents will match this)
46
47### Amazon Silk devices (also passes Android checks)
48
49- `isMobile.amazon.phone`
50- `isMobile.amazon.tablet`
51- `isMobile.amazon.device` (any mobile Amazon Silk device)
52
53### Windows devices
54
55- `isMobile.windows.phone`
56- `isMobile.windows.tablet`
57- `isMobile.windows.device` (any mobile Windows device)
58
59### "Other" devices
60
61- `isMobile.other.blackberry_10`
62- `isMobile.other.blackberry`
63- `isMobile.other.opera` (Opera Mini)
64- `isMobile.other.firefox`
65- `isMobile.other.chrome`
66- `isMobile.other.device` (any "Other" device)
67
68### Aggregate Groupings
69
70- `isMobile.any` - any device matched
71- `isMobile.phone` - any device in the 'phone' groups above
72- `isMobile.tablet` - any device in the 'tablet' groups above
73
74## Usage
75
76### Node.js
77
78#### Install
79
80```bash
81yarn add ismobilejs
82```
83
84or
85
86```bash
87npm install ismobilejs
88```
89
90#### Use
91
92```ts
93import isMobile from 'ismobilejs';
94const userAgent = req.headers['user-agent'];
95console.log(isMobile(userAgent).any);
96```
97
98Or pass in a `window.navigator`-shaped object that includes at least a `userAgent` property. To properly detect iPad on iOS 13, the object should also include the `platform` and `maxTouchPoints` properties.
99
100```js
101// this is just an example. window.navigator is readonly in the browser
102window.navigator = {
103 ...
104 userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko)',
105 platform: 'MacIntel',
106 maxTouchPoints: 2,
107 ..
108}
109```
110
111```ts
112import isMobile from 'ismobilejs';
113console.log(isMobile(window.navigator).apple.tablet);
114```
115
116### Browser
117
118A real-word example: 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.3kb of JS:
119
120<!-- prettier-ignore -->
121```html
122<!DOCTYPE html>
123<html lang="en">
124 <head>
125 <meta charset="utf-8" />
126 <script>
127 // Minified version of isMobile included in the HTML since it's small
128 (function () {var a={};var f=/iPhone/i,h=/iPod/i,i=/iPad/i,r=/\biOS-universal(?:.+)Mac\b/i,g=/\bAndroid(?:.+)Mobile\b/i,j=/Android/i,c=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,d=/Silk/i,b=/Windows Phone/i,k=/\bWindows(?:.+)ARM\b/i,m=/BlackBerry/i,n=/BB10/i,o=/Opera Mini/i,p=/\b(CriOS|Chrome)(?:.+)Mobile/i,q=/Mobile(?:.+)Firefox\b/i;function s(l){return function($){return $.test(l)}}function e(l){var $=(l=l||("undefined"!=typeof navigator?navigator.userAgent:"")).split("[FBAN");void 0!==$[1]&&(l=$[0]),void 0!==($=l.split("Twitter"))[1]&&(l=$[0]);var a=s(l),e={apple:{phone:a(f)&&!a(b),ipod:a(h),tablet:!a(f)&&a(i)&&!a(b),universal:a(r),device:(a(f)||a(h)||a(i))&&!a(b)},amazon:{phone:a(c),tablet:!a(c)&&a(d),device:a(c)||a(d)},android:{phone:!a(b)&&a(c)||!a(b)&&a(g),tablet:!a(b)&&!a(c)&&!a(g)&&(a(d)||a(j)),device:!a(b)&&(a(c)||a(d)||a(g)||a(j))||a(/\bokhttp\b/i)},windows:{phone:a(b),tablet:a(k),device:a(b)||a(k)},other:{blackberry:a(m),blackberry10:a(n),opera:a(o),firefox:a(q),chrome:a(p),device:a(m)||a(n)||a(o)||a(q)||a(p)},any:!1,phone:!1,tablet:!1};return e.any=e.apple.universal||e.apple.device||e.android.device||e.windows.device||e.other.device,e.phone=e.apple.phone||e.android.phone||e.windows.phone,e.tablet=e.apple.tablet||e.android.tablet||e.windows.tablet,e}a=e();if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=a}else if(typeof define==="function"&&define.amd){define(function(){return a})}else{this["isMobile"]=a}})();
129
130 // My own arbitrary use of isMobile, as an example
131 (function() {
132 var MOBILE_SITE = '/mobile/index.html', // site to redirect to
133 NO_REDIRECT = 'noredirect'; // cookie to prevent redirect
134
135 // I only want to redirect iPhones, Android phones
136 if (isMobile.apple.phone || isMobile.android.phone) {
137 // Only redirect if the user didn't previously choose
138 // to explicitly view the full site. This is validated
139 // by checking if a "noredirect" cookie exists
140 if (document.cookie.indexOf(NO_REDIRECT) === -1) {
141 document.location = MOBILE_SITE;
142 }
143 }
144 })();
145 </script>
146 </head>
147 <body>
148 <!-- imagine lots of html and content -->
149 </body>
150</html>
151```
152
153### jsDelivr CDN [![](https://data.jsdelivr.com/v1/package/npm/ismobilejs/badge)](https://www.jsdelivr.com/package/npm/ismobilejs)
154
155Alternatively, you can include this library via [jsDelivr CDN](https://www.jsdelivr.com/package/npm/ismobilejs) in a `script` tag:
156
157`<script src="https://cdn.jsdelivr.net/npm/ismobilejs@1/dist/isMobile.min.js"></script>`
158
159**Visit the isMobile [jsDelivr page](https://www.jsdelivr.com/package/npm/ismobilejs) to get the most up-to-date URL pointing to the lastest version.**
160
161## Building manually
162
163After checking out the repo, install dependencies:
164
165```bash
166yarn install
167```
168
169Then build the library:
170
171```bash
172yarn build
173```
174
175Three versions of the library will be generated:
176
1771. `./cjs/index.js` - the CommonJS version of the library
1782. `./esm/index.js` - the ESModule version of the library
1793. `./dist/isMobile.min.js` - the browser version of the library
180
181Additionally, types will be output to `types`.
182
183## Contributing
184
185This library uses Spotify's [web-scripts](https://github.com/spotify/web-scripts) project to build, lint, test, format and release the this library.
186
187You must use `yarn commit` rather than `git commit` to commit files. This enforced commit messages to following a specific format and enables automation of release notes and version bump.