Last week, I received a request, which is as follows: a user scans the QR code and will generate a link. The link will send a request to the backend and return the download address of an apk. The user can download this apk by clicking the download button. Then a problem occurred. After testing, I found that by scanning the open page with WeChat, clicking the download button, I couldn't download the apk. After that, Baidu said that the built-in browser of WeChat blocked the download link and communicated with the demand side later. The requirement was changed to If the user opened it with WeChat's built-in browser, the user was prompted to change the browser to open the page, otherwise the apk could not be downloaded. So how do you determine whether the user is using a WeChat browser?
We know that js can obtain relevant information about the browser through window.navigator.userAgent, such as: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36. Then we can also obtain relevant information about the built-in browser of WeChat through this method: Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_1 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Mobile/11d201 MicroMessenger/5.3. Based on the keyword MicroMessenger, determine whether it is a built-in browser for WeChat. The judgment function is as follows:
The code copy is as follows:
function isWeiXin(){
var ua = window.navigator.userAgent.toLowerCase();
if(ua.match(/MicroMessenger/i) == 'micromessenger'){
return true;
}else{
return false;
}
}
demo:
The code copy is as follows:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Determine whether it is a built-in browser for WeChat</title>
</head>
<body>
<h1>If you open it in WeChat browser, you can see the following text</h1>
<p></p>
</body>
</html>
<script type="text/javascript">
window.onload = function(){
if(isWeiXin()){
var p = document.getElementsByTagName('p');
p[0].innerHTML = window.navigator.userAgent;
}
}
function isWeiXin(){
var ua = window.navigator.userAgent.toLowerCase();
if(ua.match(/MicroMessenger/i) == 'micromessenger'){
return true;
}else{
return false;
}
}
</script>
Note: You can place the above demo on the server and generate a QR code and scan it.