java 版
private static final String PHONE_REG = "\\b(ip(hone|od)|android|opera m(ob|in)i" + "|windows (phone|ce)|blackberry" + "|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp" + "|laystation portable)|nokia|fennec|htc[-_]" + "|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b"; private static final String TABLE_REG = "\\b(ipad|tablet|(Nexus 7)|up.browser" + "|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
private static final Pattern PHONE_PAT = Pattern.compile(PHONE_REG, Pattern.CASE_INSENSITIVE); private static final Pattern TABLE_PAT = Pattern.compile(TABLE_REG, Pattern.CASE_INSENSITIVE);
public static String checkLoginDeviceType(String userAgent) { if (null == userAgent) { userAgent = ""; } Matcher matcherPhone = PHONE_PAT.matcher(userAgent); Matcher matcherTable = TABLE_PAT.matcher(userAgent); if (matcherPhone.find()) { return PHONE_TYPE; } else if (matcherTable.find()) { return PAD_TYPE; } else { return PC_TYPE; } }
|
js 版
没经过项目测试,只是记录别人写的代码,而且好像只能区分移动端和桌面,不能区分移动端是 pad 还是 phone
var browser = { versions: (function () { var u = navigator.userAgent, app = navigator.appVersion return { trident: u.indexOf('Trident') > -1, presto: u.indexOf('Presto') > -1, webKit: u.indexOf('AppleWebKit') > -1, gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, mobile: !!u.match(/AppleWebKit.*Mobile.*/) || u.indexOf('iPad') > -1, ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, iPhone: u.indexOf('iPhone') > -1, iPad: u.indexOf('iPad') > -1, webApp: u.indexOf('Safari') == -1 } })(), language: (navigator.browserLanguage || navigator.language).toLowerCase() }
if (browser.versions.mobile) { } else { }
|