Skip to content

Instantly share code, notes, and snippets.

@FuruholmAnton
Last active April 25, 2018 08:06
Show Gist options
  • Save FuruholmAnton/51b413e6876112ef2ce68c4fdc78ba30 to your computer and use it in GitHub Desktop.
Save FuruholmAnton/51b413e6876112ef2ce68c4fdc78ba30 to your computer and use it in GitHub Desktop.
import dashify from 'dashify';
export class Sniffer {
constructor() {
this.init();
Object.keys(this.list).forEach(function(info) {
Object.defineProperty(this, info, {
get: function() {
return this.list[info];
},
});
}, this);
}
init() {
const ua = navigator.userAgent.toLowerCase();
const av = navigator.appVersion.toLowerCase();
const isWindowsPhone = /windows phone|iemobile|wpdesktop/.test(ua);
const isDroidPhone = !isWindowsPhone && /android.*mobile/.test(ua);
const isDroidTablet = !isWindowsPhone && !isDroidPhone && (/android/i).test(ua);
const isDroid = isDroidPhone || isDroidTablet;
const isIos = !isWindowsPhone && (/ip(hone|od|ad)/i).test(ua) && !window.MSStream;
const isIpad = !isWindowsPhone && (/ipad/i).test(ua) && isIos;
const isTablet = isDroidTablet || isIpad;
const isPhone = isDroidPhone || (isIos && !isIpad) || isWindowsPhone;
const isDevice = isPhone || isTablet;
const isTouch = !!('ontouchstart' in window || navigator.maxTouchPoints); // The browser wont reset this one without the user refreshing the page
const isFirefox = ua.indexOf('firefox') > -1;
const isSafari = !!ua.match(/version\/[\d\.]+.*safari/);
const isOpera = ua.indexOf('opr') > -1;
const isIE11 = !(window.ActiveXObject) && 'ActiveXObject' in window;
const isIE = av.indexOf('msie') > -1 || isIE11 || av.indexOf('edge') > -1;
const isEdge = ua.indexOf('edge') > -1;
const isChrome = window.chrome !== null && window.chrome !== undefined && navigator.vendor.toLowerCase() == 'google inc.' && !isOpera && !isEdge;
this.list = {
isDroid: isDroid,
isDroidPhone: isDroidPhone,
isDroidTablet: isDroidTablet,
isWindowsPhone: isWindowsPhone,
isIos: isIos,
isIpad: isIpad,
isDevice: isDevice,
isTouch: isTouch,
isEdge: isEdge,
isIE: isIE,
isIE11: isIE11,
isPhone: isPhone,
isTablet: isTablet,
isFirefox: isFirefox,
isSafari: isSafari,
isOpera: isOpera,
isChrome: isChrome,
isDesktop: !isPhone && !isTablet,
};
}
addClasses(el) {
Object.keys(this.list).forEach(function(key) {
if (this.list[key]) el.classList.add(dashify(key));
}, this);
}
resetClasses(el) {
this.init();
Object.keys(this.list).forEach((key) => {
el.classList.toggle(dashify(key), !!this.list[key]);
});
}
getlist() {
return clone(this.list);
}
// TODO: add getVersion() to get IE/Safari/... version
}
function addClass(el, className) {
el.classList.add(className);
}
function clone(source) {
return JSON.parse(JSON.stringify(source));
}
export default new Sniffer();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment