js 判断是否在微信小程序

1,646 阅读1分钟

直接上代码,根据window对象提供的属性进行判断监听

let weixinBoolean = false
const ready = () => {
  if (window.__wxjs_environment === 'miniprogram') {
    weixinBoolean = true;
  }
};
if (!window.WeixinJSBridge || !WeixinJSBridge.invoke) {
  document.addEventListener('WeixinJSBridgeReady', ready, false);
} else {
  ready();
  window.WeixinJSBridge.on('onPageStateChange', res => {
    console.log('res is active', res.active);
  });
}

if (weixinBoolean) {
    console.log('微信小程序')
}