navigator.userAgent 判断当前浏览器所处的环境
场景1:判断页面是在手机端还是PC端打开
window.location.href=/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)?"http://localhost:8888/mobile_web":"http://localhost:8888/PC";
场景2:判断页面是在手机端,平板端还是PC端打开
var os = function (){ var ua = navigator.userAgent, isWindowsPhone = /(?:Windows Phone)/.test(ua), isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone, isAndroid = /(?:Android)/.test(ua), isFireFox = /(?:Firefox)/.test(ua), isChrome = /(?:Chrome|CriOS)/.test(ua), isTablet = /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (isFireFox && /(?:Tablet)/.test(ua)), isPhone = /(?:iPhone)/.test(ua) && !isTablet, isPc = !isPhone && !isAndroid && !isSymbian; return { isTablet: isTablet, isPhone: isPhone, isAndroid: isAndroid, isPc: isPc }; }(); if (os.isAndroid || os.isPhone) { alert("手机" ); } else if (os.isTablet) { alert("平板" ); } else if (os.isPc) { alert("电脑" ); }
场景3:获取操作系统类型,判断是Android或者IOS
/** * 获取操作系统类型, * 0 Android * 1 iOS */ function getOSType() { if (/(Android)/i.test(navigator.userAgent)) { return 0; } else if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) { return 1; } else { return 2; } }
场景4:判断当前环境是否是微信环境
function is_weixin(){ var ua = navigator.userAgent.toLowerCase(); if(ua.match(/MicroMessenger/i)=="micromessenger") { return true; } else { return false; } }