有时页面需要根据不同的设备进行不同的处理,需要判断到底是哪种设备打开了页面。
移动终端浏览器版本信息:
1 var browser = { 2 versions: function () { 3 var u = navigator.userAgent, app = navigator.appVersion; 4 return { 5 trident: u.indexOf(‘Trident‘) > -1, //IE内核 6 presto: u.indexOf(‘Presto‘) > -1, //opera内核 7 webKit: u.indexOf(‘AppleWebKit‘) > -1, //苹果、谷歌内核 8 gecko: u.indexOf(‘Gecko‘) > -1 && u.indexOf(‘KHTML‘) == -1, //火狐内核 9 mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端 10 ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端 11 android: u.indexOf(‘Android‘) > -1 || u.indexOf(‘Linux‘) > -1, //android终端或uc浏览器 12 iPhone: u.indexOf(‘iPhone‘) > -1, //是否为iPhone或者QQHD浏览器 13 iPad: u.indexOf(‘iPad‘) > -1, //是否iPad 14 webApp: u.indexOf(‘Safari‘) == -1 //是否web应该程序,没有头部与底部 15 }; 16 }(), 17 language: (navigator.browserLanguage || navigator.language).toLowerCase() 18 };
浏览器判断:
1 if (browser.versions.mobile) {//判断是否是移动设备打开 2 var ua = navigator.userAgent.toLowerCase();//获取判断用的对象 3 if (ua.match(/MicroMessenger/i) == "micromessenger") { 4 //在微信中打开 5 if(browser.versions.android){ 6 alert(‘weixin-android‘) 7 } 8 if(browser.versions.ios){ 9 alert(‘weixin-ios‘) 10 } 11 }else if(browser.versions.ios) { 12 //在IOS浏览器打开 13 alert(‘ios-browser‘) 14 }else if(browser.versions.android){ 15 //在安卓浏览器打开 16 alert(‘android-browser‘) 17 } 18 } else { 19 //否则就是PC浏览器打开 20 var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串 21 var isOpera = userAgent.indexOf("Opera") > -1; 22 if (isOpera) { 23 alert("Opera") 24 } //判断是否Opera浏览器 25 if (userAgent.indexOf("Firefox") > -1) { 26 alert("FF") 27 } //判断是否Firefox浏览器 28 if (userAgent.indexOf("Chrome") > -1){ 29 alert("Chrome") 30 } 31 if (userAgent.indexOf("Safari") > -1) { 32 alert("Safari") 33 } //判断是否Safari浏览器 34 if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) { 35 alert("IE") 36 } //判断是否IE浏览器 37 }
微信内部支付,获取code:
1 if (browser.versions.mobile) {//判断是否是移动设备打开。browser代码在下面 2 var ua = navigator.userAgent.toLowerCase();//获取判断用的对象 3 if (ua.match(/MicroMessenger/i) == "micromessenger") { 4 var code = this.getUrlParam(‘code‘); // 截取路径中的code 5 if (code == null || code === ‘‘) { 6 var local = window.location.href; 7 window.location.href = ‘https://open.weixin.qq.com/connect/oauth2/authorize?appid=‘ + appid + ‘&redirect_uri=‘ + encodeURIComponent(local) + ‘&response_type=code&scope=snsapi_base&state=1#wechat_redirect‘; 8 } 9 } 10 } 11 12 //获取URL中的属性 13 function getUrlParam(name) { 14 var reg = new RegExp(‘(^|&)‘ + name + ‘=([^&]*)(&|$)‘); 15 var url = window.location.href.split(‘#‘)[0]; 16 var search = url.split(‘?‘)[1]; 17 if (search) { 18 var r = search.substr(0).match(reg); 19 if (r !== null) 20 return unescape(r[2]); 21 return null 22 } else 23 return null 24 }
原文:https://www.cnblogs.com/ndyd/p/14917238.html