Skip to content

Instantly share code, notes, and snippets.

@BelinChung
Last active August 29, 2015 14:03
Show Gist options
  • Save BelinChung/a512ee7e6e4babf5a042 to your computer and use it in GitHub Desktop.
Save BelinChung/a512ee7e6e4babf5a042 to your computer and use it in GitHub Desktop.
Mobile UA detection library.You can access device object which contains useful information about device and platform.
var device = (function () {
var device = {};
var ua = navigator.userAgent;
var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
device.ios = device.android = device.iphone = device.ipad = false;
// Android
if (android) {
device.os = 'android';
device.osVersion = android[2];
device.android = true;
}
if (ipad || iphone || ipod) {
device.os = 'ios';
device.ios = true;
}
// iOS
if (iphone && !ipod) {
device.osVersion = iphone[2].replace(/_/g, '.');
device.iphone = true;
}
if (ipad) {
device.osVersion = ipad[2].replace(/_/g, '.');
device.ipad = true;
}
if (ipod) {
device.osVersion = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
device.iphone = true;
}
// Webview
device.webView = (iphone || ipad || ipod) && ua.match(/.*AppleWebKit(?!.*Safari)/i);
// Pixel Ratio
device.pixelRatio = window.devicePixelRatio || 1;
// Check for status bar and fullscreen app mode
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
device.statusBar = false;
if (
device.webView &&
(
// iPhone 5
(windowWidth === 320 && windowHeight === 568) ||
(windowWidth === 568 && windowHeight === 320) ||
// iPhone 4
(windowWidth === 320 && windowHeight === 480) ||
(windowWidth === 480 && windowHeight === 320) ||
// iPad
(windowWidth === 768 && windowHeight === 1024) ||
(windowWidth === 1024 && windowHeight === 768)
)
) {
device.statusBar = true;
}
else {
device.statusBar = false;
}
// Export object
return device;
})();
function test(){
document.write('Device OS:' + device.os + '<br/>');
document.write('Device OS Version:' + device.osVersion + '<br/>');
document.write('is iOS:' + device.ios + '<br/>');
document.write('is iPad:' + device.ipad + '<br/>');
document.write('is iphone:' + device.iphone + '<br/>');
document.write('is Android:' + device.android + '<br/>');
document.write('is WebView:' + device.webView + '<br/>');
document.write('Pixel Ratio:' + device.pixelRatio + '<br/>');
document.write('Status Bar:' + device.statusBar + '<br/>');
}
test();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment