JS和PHP判断页面是否为微信内访问
判断页面是否为微信内访问,其实也就是判断浏览器UA是否包含微信浏览器相关信息。
比如下面这段抓取到的UA:
# iPhone Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13B143 MicroMessenger/5.4.1 # Android Mozilla/5.0 (Linux; U; Android 4.0.2; en-us; Galaxy Nexus Build/ICL53F) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 MicroMessenger/5.4.1
可以通过 MicroMessenger 关键词来判断是否在微信内浏览。
JavaScript 方法:
<script type="text/javascript"> function isWXbrower(){ var ua = navigator.userAgent.toLowerCase(); if( ua.match(/MicroMessenger/i)=="micromessenger" ){ return true; } else { return false; } } if( !isWXbrower() ){ …… } else { …… } </script>
PHP 方法:
<?php function isWXbrower(){ if( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ){ return true; } return false; } ?>
最后看一下微信自家的判断代码:
<!DOCTYPE html><html> <head> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0"> </head> <body> <script type="text/javascript"> var ua = navigator.userAgent.toLowerCase(); var isWeixin = ua.indexOf('micromessenger') != -1; var isAndroid = ua.indexOf('android') != -1; var isIos = (ua.indexOf('iphone') != -1) || (ua.indexOf('ipad') != -1); if (!isWeixin) { document.head.innerHTML = '<title>抱歉,出错了</title><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0"><link rel="stylesheet" type="text/css" href="https://res.wx.qq.com/open/libs/weui/0.4.1/weui.css">'; document.body.innerHTML = '<div class="weui_msg"><div class="weui_icon_area"><i class="weui_icon_info weui_icon_msg"></i></div><div class="weui_text_area"><h4 class="weui_msg_title">请在微信客户端打开链接</h4></div></div>'; } </script> </body> </html>