我已经编辑了我的答案,因为我发现有微信(微信)的 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.
}