I have been working on a lot of HTML5 projects recently, and many pages will be shared through SNS such as WeChat and Weibo. Provide downloads of the company APP on the sharing page. However, in many application browsers, clicking the download link cannot download the application. Then for these browsers, we need to prompt users to open the shared page from Safari or the system's own browser. Through js, we can determine which browser the current page is opened in.
The following is a sample code. The comments indicate how to use JS to determine whether it is opened in the WeChat browser, whether it is in QQ Space Browser, and whether it is in Open Sina Weibo . Of course, it can be made more perfect, and the judgment is whether it is opened on a mobile device or on a PC browser opens . You can refer to this article for more details. It can be judged that it is opened in the browser of Android system or IOS system browser opens .
if (browser.versions.mobile) {//判断是否是移动设备打开。browser代码在下面 var ua = navigator.userAgent.toLowerCase();//获取判断用的对象 if (ua.match(/MicroMessenger/i) == "micromessenger") { //在微信中打开 } if (ua.match(/WeiBo/i) == "weibo") { //在新浪微博客户端打开 } if (ua.match(/QQ/i) == "qq") { //在QQ空间打开 } if (browser.versions.ios) { //是否在IOS浏览器打开 } if(browser.versions.android){ //是否在安卓浏览器打开 } } else { //否则就是PC浏览器打开 }
Attach the browser code and you can determine many browsers through the following methods. Including judging IE browser, Opera browser, Safari, Google Chrome, Firefox, etc.
var browser = { versions: function () { var u = navigator.userAgent, app = navigator.appVersion; return { //移动终端浏览器版本信息 trident: u.indexOf('Trident') > -1, //IE内核 presto: u.indexOf('Presto') > -1, //opera内核 webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核 gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核 mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端 ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端 android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器 iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器 iPad: u.indexOf('iPad') > -1, //是否iPad webApp: u.indexOf('Safari') == -1 //是否web应该程序,没有头部与底部 }; }(), language: (navigator.browserLanguage || navigator.language).toLowerCase() }
Another method:
I used JS to judge. After searching for information, I finally achieved the effect and directly entered the code
function is_weixn(){ var ua = navigator.userAgent.toLowerCase(); if(ua.match(/MicroMessenger/i)=="micromessenger") { return true; } else { return false; } }
The test is completely passed, whether it is Android, iPhone or iPad. Of course, in addition to using js to judge, it is easier to use other languages to judge, such as PHP
function is_weixin(){ if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) { return true; } return false; }
The above is a method to share with you how to use js to determine which browser to open the current page. I hope it will be helpful to your study.