JsbridgeのVueでのパッケージングとインタラクション

3117 ワード

点我
Jsbridgeに書いてあります.js
let isAndroid = navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Adr') > -1;
let isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);

//       ,        
function setupWebViewJavascriptBridge(callback) {
    //Android  
    if (isAndroid) {
        if (window.WebViewJavascriptBridge) {
            callback(WebViewJavascriptBridge)
        } else {
            document.addEventListener(
                'WebViewJavascriptBridgeReady',
                function () {
                    callback(WebViewJavascriptBridge)
                },
                false
            );
        }
        console.log('tag', '  ')
        sessionStorage.phoneType = 'android'
    }

    //iOS  
    if (isiOS) {
        if (window.WebViewJavascriptBridge) {
            return callback(WebViewJavascriptBridge);
        }
        if (window.WVJBCallbacks) {
            return window.WVJBCallbacks.push(callback);
        }
        window.WVJBCallbacks = [callback];
        var WVJBIframe = document.createElement('iframe');
        WVJBIframe.style.display = 'none';
        WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
        document.documentElement.appendChild(WVJBIframe);
        setTimeout(function () {
            document.documentElement.removeChild(WVJBIframe)
        }, 0);
        console.log('tag', 'ios');
        sessionStorage.phoneType = 'ios'
    }
}
//      ,              (android     ,ios  )
setupWebViewJavascriptBridge(function (bridge) {
    if (isAndroid) {
        //   
        bridge.init(function (message, responseCallback) {
            var data = {
                'Javascript Responds': 'Wee!'
            };
            responseCallback(data);
        })
    }
})

export default {
    // js APP   (     :app          app       )
    callHandler(name, data, callback) {
        setupWebViewJavascriptBridge(function (bridge) {
            bridge.callHandler(name, data, callback)
        })
    },
    // APP js   (     :js          )
    registerHandler(name, callback) {
        setupWebViewJavascriptBridge(function (bridge) {
            bridge.registerHandler(name, function (data, responseCallback) {
                callback(data, responseCallback)
            })
        })
    }
}
  main.jsに導入:
import Bridge from './config/JSbridge.js'
Vue.prototype.$bridge = Bridge
コンポーネントで使用する:メソッド名とapp開発者はコミュニケーションがよく、ここでjsはappを調整し、appが提供する方法はdataToAndroidである.appはjsを調整して、jsは提供する方法はdataToJsです
    
  mounted(){
    this.getAPPDate()
  },

js app
  sendMsg(){
    let msg = this.msg
    this.$bridge.callHandler('dataToAndroid',msg,(res)=>{
      alert('  app    :'+res)
      this.test = res
    })
  },

app js
  getAPPDate(){
    this.$bridge.registerHandler('dataToJs', (data, responseCallback) => {
      alert('app    js  ,    :'+ data)
      responseCallback(data)
    })
  }