Detect Android phone via Javascript / jQuery
How would i detect that the device in use is an Android for a mobile website?
I need to apply 开发者_如何学Gocertain css attributes to the Android platform.
Thanks
Take a look at that : http://davidwalsh.name/detect-android
JavaScript:
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if(isAndroid) {
// Do something!
// Redirect to Android-site?
window.location = 'http://android.davidwalsh.name';
}
PHP:
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if(stripos($ua,'android') !== false) { // && stripos($ua,'mobile') !== false) {
header('Location: http://android.davidwalsh.name');
exit();
}
Edit : As pointed out in some comments, this will work in 99% of the cases, but some edge cases are not covered. If you need a much more advanced and bulletproofed solution in JS, you should use platform.js : https://github.com/bestiejs/platform.js
How about this one-liner?
var isAndroid = /(android)/i.test(navigator.userAgent);
The i
modifier is used to perform case-insensitive matching.
Technique taken from Cordova AdMob test project: https://github.com/floatinghotpot/cordova-admob-pro/wiki/00.-How-To-Use-with-PhoneGap-Build
I think Michal's answer is the best, but we can take it a step further and dynamically load an Android CSS as per the original question:
var isAndroid = /(android)/i.test(navigator.userAgent);
if (isAndroid) {
var css = document.createElement("link");
css.setAttribute("rel", "stylesheet");
css.setAttribute("type", "text/css");
css.setAttribute("href", "/css/android.css");
document.body.appendChild(css);
}
;(function() {
var redirect = false
if (navigator.userAgent.match(/iPhone/i)) {
redirect = true
}
if (navigator.userAgent.match(/iPod/i)) {
redirect = true
}
var isAndroid = /(android)/i.test(navigator.userAgent)
var isMobile = /(mobile)/i.test(navigator.userAgent)
if (isAndroid && isMobile) {
redirect = true
}
if (redirect) {
window.location.replace('jQueryMobileSite')
}
})()
js version, catches iPad too:
var is_mobile = /mobile|android/i.test (navigator.userAgent);
精彩评论