我一直在到处寻找关于内置微信浏览器生成的用户代理字符串的某种文档。
我做了很多非常具体的浏览器检测,我找不到任何与微信传递给网站的UA字符串远程相关的东西。
应该是这样的:
<>以前Mozilla/5.0 (iPhone;CPU OS 6_0如Mac OS X) AppleWebKit/536.26 (KHTML,如Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25有没有人知道是否有一种方法来区分像iOS上的Safari和微信在iOS上的内置浏览器?(如果可能的话)
任何建议将不胜感激!
我已经编辑了我的答案,因为我发现有微信的JS API:http://mp.weixin.qq.com/qa/index.php?qa=search& q = weixinjsbridge
长话短说,你只要把这个添加到你的js:
document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
// bridge initialized, meaning we're in WeChat, not stand-alone browser...
}, false);
也有API分享朋友圈和分享与特定的朋友,并获得回调时,成功分享。
公立小学刚发现在iOS微信上,网桥初始化的速度比Android快,然后这个回调永远不会被调用因为listener是在网桥初始化后添加的
所以为了完整的回答,下面是正确的做法:
// when your webapp is loaded, before adding listener for weixing js bridge, check if it's already initialized:
var timeoutID = 0;
if( typeof WeixinJSBridge !== "undefined" )
{
// WeChat JS bridge already initialized. Wonderful.
}
else
{
// setup a time out of let's say 5 seconds, to wait for the bridge:
timeoutID = window.setTimeout(WeChatBridgeTimeout,5000);
// now add listener for the bridge:
document.addEventListener('WeixinJSBridgeReady', WeChatBridgeReady, false);
}
// Now in bridge time out:
function WeChatBridgeTimeout()
{
// Just to be sure that bridge was not initialized just before the line we added the listener (since it's a separate process than JS), let's check for it again:
if( typeof WeixinJSBridge !== "undefined" )
{
// WeChat JS bridge already initialized. Wonderful.
}
else
{
// Nope... if it's not initialized by now, we're not in WeChat.
}
}
// And in event handled:
function WeChatBridgeReady()
{
// remove listener timeout
window.clearTimeout(timeoutID);
// WeChat JS bridge initialized.
}
这很简单。只需检查用户代理,如:
if(req.headers['user-agent'].indexOf('MicroMessenger') !== -1){
//we are in wechat browser
your code here
}
有时微信浏览器会恶意屏蔽App Store链接。这时,您需要将用户重定向到其他地方,或者引导他们在其他更友好的浏览器中打开您的页面。:)
目前(微信6.xx), ios平台微信内置浏览器的UA字符串为:
... MicroMessenger/6.1.4 ...
,而safari:... Safari/600.1.4
所以下面的代码在android和ios上都可以工作:
var isWeChat = /micromessenger/i.test(navigator.userAgent);