Skip to content

Instantly share code, notes, and snippets.

@tomalex0
Last active October 11, 2015 13:27
Show Gist options
  • Select an option

  • Save tomalex0/3865521 to your computer and use it in GitHub Desktop.

Select an option

Save tomalex0/3865521 to your computer and use it in GitHub Desktop.
to identify if device is phone,tablet or desktop
var osEnvar= {
name : null,
names: {
ios: 'iOS',
android: 'Android',
webos: 'webOS',
blackberry: 'BlackBerry',
rimTablet: 'RIMTablet',
mac: 'MacOS',
win: 'Windows',
linux: 'Linux',
bada: 'Bada',
other: 'Other'
},
prefixes: {
ios: 'i(?:Pad|Phone|Pod)(?:.*)CPU(?: iPhone)? OS ',
android: '(Android |HTC_|Silk/)', // Some HTC devices ship with an OSX userAgent by default,
// so we need to add a direct check for HTC_
blackberry: 'BlackBerry(?:.*)Version\/',
rimTablet: 'RIM Tablet OS ',
webos: '(?:webOS|hpwOS)\/',
bada: 'Bada\/'
},
getosEnv: function () {
var me= this,
names = me.names,
prefixes = me.prefixes,
userAgent = navigator.userAgent, platform = navigator.platform,i, prefix, match, item, is,name, version = '';
is = this.is = function(name) {
return this.is[name] === true;
};
for (i in prefixes) {
if (prefixes.hasOwnProperty(i)) {
prefix = prefixes[i];
match = userAgent.match(new RegExp('(?:'+prefix+')([^\\s;]+)'));
if (match) {
name = names[i];
break;
}
}
}
if (!name) {
name = names[(userAgent.toLowerCase().match(/mac|win|linux/) || ['other'])[0]];
}
this.name = name;
if (platform) {
this.setFlag(platform);
}
this.setFlag(name);
for (i in names) {
if (names.hasOwnProperty(i)) {
item = names[i];
if (!is.hasOwnProperty(name)) {
this.setFlag(item, (name === item));
}
}
}
return this;
},
setFlag: function(name, value) {
if (typeof value == 'undefined') {
value = true;
}
this.is[name] = value;
this.is[name.toLowerCase()] = value;
return this;
},
getDeviceInfo : function(){
var osEnv = this.getosEnv(),
osName = osEnv.name;
if (!osEnv.is.Android && !osEnv.is.iOS && /Windows|Linux|MacOS/.test(osName)) {
deviceType = 'Desktop';
}
else if (osEnv.is.iPad || osEnv.is.Android3 || (osEnv.is.Android4 && userAgent.search(/mobile/i) == -1) || navigator.userAgent.search(/Tablet/i) != "-1") {
deviceType = 'Tablet';
}
else {
deviceType = 'Phone';
}
osEnv.setFlag(deviceType, true);
osEnv.deviceType = deviceType;
return this;
}
}
@tomalex0
Copy link
Copy Markdown
Author

How to use

osEnvar.getDeviceInfo()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment