Skip to content

Instantly share code, notes, and snippets.

@ahmed-musallam
Last active September 10, 2019 04:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmed-musallam/d5ade4ba7ef92accc86d7bfe74c11a06 to your computer and use it in GitHub Desktop.
Save ahmed-musallam/d5ade4ba7ef92accc86d7bfe74c11a06 to your computer and use it in GitHub Desktop.
Device Detector JS
/***
*
* a trimmed down version (~812 bytes minified, not gzipped) of: https://github.com/matthewhudson/current-device/blob/master/src/index.js
* to determine current device is mobile, tablet or desktop
* USAGE:
* 1. prebuilt property: `window.device.type` returns "mobile", "tablet" or "desktop"
* 2. could call `window.device.mobile()` or `window.device.tablet()` or `window.device.desktop()` to check for each
* 3. other methods such as `window.device.windows()`, `window.device.windowsPhone()`, `window.device.android()`, `window.device.blackberry()`
*/
(function() {
var uAgent = window.navigator.userAgent.toLowerCase();
function find(needle) { return uAgent.indexOf(needle) !== -1; }
window.device = {
windows: function() { return find('windows'); },
windowsPhone: function() { return this.windows() && find('phone'); },
android: function() { return !this.windows() && find('android'); },
blackberry: function() { return find('blackberry') || find('bb10') || find('rim'); },
fxos: function() { return (find('(mobile') || find('(tablet')) && find(' rv:');},
mobile: function() {
return (
(this.android() && find('mobile')) ||
(!this.windows() && find('iphone')) ||
find('ipod') ||
(this.windows() && find('phone')) ||
(this.blackberry() && !find('tablet')) ||
(this.fxos() && find('mobile')) ||
find('meego')
);
},
tablet: function() {
return (
find('ipad') ||
(this.android() && !find('mobile')) ||
(this.blackberry() && find('tablet')) ||
(this.windows() && (find('touch') && !this.windowsPhone())) ||
(this.fxos() && find('tablet'))
);
},
desktop: function() {
return !this.tablet() && !this.mobile();
},
findMatch: function (arr) {
for (let i = 0; i < arr.length; i++) {
if (this[arr[i]]()) {
return arr[i];
}
}
return 'unknown';
}
};
var type = device.findMatch(['mobile', 'tablet', 'desktop']);
window.device.type = type;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment