H5与app交互


const emit = (event, json)=> {
  try {
    if (isIOS()) {
      window.webkit.messageHandlers[event].postMessage(json)
    } else {
      if (!json) {
        eval(`window.formuJSInterface.${event}()`)
      } else {
        let params = json
        if (typeof json !== 'string') {
          params = JSON.stringify(json)
        }
        window.formuJSInterface[event](params)
      }
    }
  } catch (error) {
    console.log('发送原生事件失败:' + event)
  }
}

const on = (event, callBack) => {
  window[event] = callBack;
};

const off = (event) => {
  window[event] = null;
}

const isIOS = () => {
  var userAgent = navigator.userAgent
  var isiOS = !!userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)

  return isiOS
}

const isAndroid = () => {
  var userAgent = navigator.userAgent
  var isAndroid = userAgent.indexOf('Android') > -1 || userAgent.indexOf('Adr') > -1

  return isAndroid
}

const bridge = {
  emit,
  on,
  off
}

export default bridge;

这个文件H5页面提供
具体使用: 

import bridge from "bridge";
bridge.emit("getPosition", {});
bridge.on("getPosition", (res) => {
   console.log(res)
});
bridge.off("getPosition");   

 

你可能感兴趣的:(移动端,vue,h5与app交互,vue,event,window,js)