2

我一直在搜索有关内置微信浏览器生成的用户代理字符串的某种文档。

我做了很多非常具体的浏览器检测,但我找不到任何与微信传递给网站的 UA 字符串远程相关的东西。

这将是这样的:

Mozilla/5.0 (iPhone; CPU OS 6_0 像 Mac OS X) AppleWebKit/536.26 (KHTML, 像 Gecko) 版本/6.0 Mobile/10A5355d Safari/8536.25

有谁知道是否有办法区分 iOS 上的 Safari 和 iOS 上的微信内置浏览器?(或者如果这是可能的)

任何建议将不胜感激!

4

3 回答 3

5

这很简单。只需检查用户代理,如:

if(req.headers['user-agent'].indexOf('MicroMessenger') !== -1){
  //we are in wechat browser
  your code here
}

有时微信浏览器会恶意屏蔽 App Store 链接。那时您需要将用户重定向到其他地方,或引导他们在其他更友好的浏览器中打开您的页面。:)

于 2015-01-28T12:56:42.177 回答
5

我已经编辑了我的答案,因为我发现有微信(微信)的 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微信上,bridge的初始化速度比Android快,然后这个回调永远不会被调用,因为监听器是在初始化bridge之后添加的。

所以要完成答案,这里是如何正确地做到这一点:

// 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.
}
于 2014-08-08T06:02:39.727 回答
1

至于现在(WeChat6.xx),微信内置浏览器在ios上的UA字符串为:

... MicroMessenger/6.1.4 ...,而野生动物园: ... Safari/600.1.4

因此以下代码适用于 android 和 ios:

var isWeChat = /micromessenger/i.test(navigator.userAgent);

于 2015-05-04T08:55:38.113 回答