Skip to content

Instantly share code, notes, and snippets.

@loo2k
Last active March 14, 2019 02:08
Show Gist options
  • Save loo2k/6769e0a69b5b99d051b3 to your computer and use it in GitHub Desktop.
Save loo2k/6769e0a69b5b99d051b3 to your computer and use it in GitHub Desktop.
JavaScript 判断是否微信内置浏览器
var isWeixin = false;
if (typeof WeixinJSBridge == "object" && typeof WeixinJSBridge.invoke == "function") {
isWeixin = true;
} else {
if (document.addEventListener) {
document.addEventListener("WeixinJSBridgeReady", function() { isWeixin = true; }, false);
} else if (document.attachEvent) {
document.attachEvent("WeixinJSBridgeReady", function() { isWeixin = true; });
document.attachEvent("onWeixinJSBridgeReady", function() { isWeixin = true; });
}
}
@gordonchanhk
Copy link

The detection need to either run after onload event, or need a setTimout for multiple attempt because this variable is not available until the in-app browser / page is completely rendered.

@gordonchanhk
Copy link

// This should be the most ideal way to detect WeChat inapp browser:

window.onload = function () {
if (typeof WeixinJSBridge == "undefined"){
if( document.addEventListener ){
document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
}else if (document.attachEvent){
document.attachEvent('WeixinJSBridgeReady', jsApiCall);
document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
}
}else{
jsApiCall();
}
}

function jsApiCall() {
document.getElementById('wxmsg').innerHTML = 'WeixinJSBridge ready';
}

@danielzhang5566
Copy link

@gordonchanhkk
window.onload是在页面所有资源加载完才执行,往往需要一定的时间t1。
WeixinJSBridge并不是WebView一打开就有了,客户端需要初始化这个对象,同样需要时间t2。
当t1>t2的时候,给WeixinJSBridgeReady添加事件监听是无效的。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment