我一直在搜索内置微信浏览器产生的用户代理字符串的某些文档。
我做了很多非常具体的浏览器检测,我找不到与微信传递到网站的UA字符串有关的任何内容。
这将是这样的:
Mozilla/5.0 (iPhone; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25
有没有人知道是否有办法区分iOS上的Safari和iOS上的微信内置浏览器? (或者如果可能的话)
任何建议都将不胜感激!
答案 0 :(得分:5)
我已经编辑了我的答案,因为我发现Weixin(WeChat)有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可以分享时刻并与特定朋友分享,并在成功分享后获得回调。
P.S。
刚才发现,在iOS微信上,网桥的初始化速度比Android快,然后这个回调永远不会被调用,因为在初始化网桥后添加了监听器。
所以要完成答案,以下是如何正确地做到这一点:
// 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.
}
答案 1 :(得分:4)
这很简单。只需检查用户代理,如:
if(req.headers['user-agent'].indexOf('MicroMessenger') !== -1){
//we are in wechat browser
your code here
}
有时微信浏览器evilly阻止App Store链接。那时你需要将用户重定向到其他地方,或引导他们在其他更友好的浏览器中打开你的页面。 :)
答案 2 :(得分:1)
至于现在(WeChat6.xx),微信在ios上的内置浏览器的UA字符串是:
... MicroMessenger/6.1.4 ...
,而野生动物园:
... Safari/600.1.4
所以以下代码适用于android和ios:
var isWeChat = /micromessenger/i.test(navigator.userAgent);