Vue与原生App(Android、IOS)交互

在Vue项目中引入WebViewJavascriptBridge

1.在src目录下新建api文件夹,创建src/api/bridge.js,用于封装 WebViewJavascriptBridge ,复制下方代码即可

Vue与原生App(Android、IOS)交互_第1张图片

//判断机型
let u = navigator.userAgent;

function setupWebViewJavascriptBridge(callback) {
  //判断ios 还是Android
  if (/(iPhone|iPad|iPod|iOS)/i.test(u)) {
    if (window.WebViewJavascriptBridge) {
      return callback(window.WebViewJavascriptBridge)
    }
    if (window.WVJBCallbacks) {
      return window.WVJBCallbacks.push(callback)
    }
    window.WVJBCallbacks = [callback]
    let WVJBIframe = document.createElement('iframe')
    WVJBIframe.style.display = 'none'
    WVJBIframe.src = 'https://__bridge_loaded__'
    document.documentElement.appendChild(WVJBIframe)
    setTimeout(() => {
      document.documentElement.removeChild(WVJBIframe)
    }, 0)
  }
}

//安卓注册事件监听
function connectWebViewJavascriptBridge(callback) {
  if (window.WebViewJavascriptBridge) {
    callback(WebViewJavascriptBridge)
  } else {
    document.addEventListener(
      'WebViewJavascriptBridgeReady',
      function () {
        callback(WebViewJavascriptBridge)
      },
      false
    );
  }
}

connectWebViewJavascriptBridge(function (bridge) {
  //初始化
  if (!/(iPhone|iPad|iPod|iOS)/i.test(u)) {
    console.log("初始化")
    bridge.init(function (message, responseCallback) {
      //var data = {'Javascript Responds': 'Wee!'};
      responseCallback(data);
    });
  }
});

export default {
  callHandler(name, data, callback) {
    console.log("call", data, name);
    if (/(iPhone|iPad|iPod|iOS)/i.test(u)) {
      setupWebViewJavascriptBridge(function (bridge) {
        bridge.callHandler(name, data, callback)
      })
    } else {
      connectWebViewJavascriptBridge(function (bridge) {
        bridge.callHandler(name, data, callback)
      })
    }
  },
  registerhandler(name, callback) {
    console.log("reg", callback);
    if (/(iPhone|iPad|iPod|iOS)/i.test(u)) {
      setupWebViewJavascriptBridge(function (bridge) {
        bridge.registerHandler(name, function (data, responseCallback) {
          callback(data, responseCallback)
        })
      })
    } else {
      connectWebViewJavascriptBridge(function (bridge) {
        bridge.registerHandler(name, function (data, responseCallback) {
          callback(data, responseCallback)
        })
      })
    }
  }
}

 

 2.在main.js中全局引用Bridge.js

// 全局引入bridge
import Bridge from '@/api/bridge';
Vue.prototype.$bridge = Bridge;

 3.在Vue页面注册以下注册和调用方法即可

Js调用App的方法(事先约定好方法名称)

Vue与原生App(Android、IOS)交互_第2张图片

this.$bridge.callHandler(
        "方法名",
        {
          type: '',
          data: [],
        },
        // type、data即传给App的数据
        (obj) => {
          // 处理返回数据
          console.log(obj);
        }
      );

App调用Js方法(事先约定好方法名称)

 Vue与原生App(Android、IOS)交互_第3张图片

 

this.$bridge.registerhandler("方法名", (data, responseCallback) => {
      responseCallback(data);
      // data即App传来的数据
    });

 

 

 

 

你可能感兴趣的:(Vue,vue.js,javascript,前端)