javascriptiosuser-agentbrowser-detectionwechat

Is it possible to target the user agent string for WeChat's built-in browser on iOS?


I have been searching high and low for some sort of documentation on the user-agent string that the built-in WeChat browser produces.

I do a lot of really specific browser detection and I cannot find anything remotely related to the UA string that WeChat passes to the website.

It will be something along the lines of this:

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

Does anyone know if there is a way to differentiate between something like Safari on iOS and WeChat's built-in browser on iOS? (or if that's even possible)

Any suggestions will be much appreciated!


Solution

  • I've edited my answer since I found there is JS API for Weixin (WeChat): http://mp.weixin.qq.com/qa/index.php?qa=search&q=weixinjsbridge

    Long-story-short, you just add this to your js:

    document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() { 
        // bridge initialized, meaning we're in WeChat, not stand-alone browser...
    }, false);
    

    There's also API to share on moments and to share with specific friend, and get callback when successfully shared.

    P.S.

    Just figured out that on iOS WeChat, bridge is initialized way faster than on Android, and then this callback never gets called because listener was added after bridge was initialized.

    So to complete answer, here is how to properly do it:

    // 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.
    }