vue H5 与 原生交互

H5调原生

api.js

/**

* @name 判断iOS

*/

export const isiOS = ()=>{

    let u = navigator.userAgent;

    let iOs = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端\

    return iOs;

}

/**

* @name 判断android

*/

export const isAndroid = ()=>{

    let u = navigator.userAgent;

    let android = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端

    return android

}

使用

import { isiOS, isAndroid } from "@/filters/api";

if (isiOS()) this.$bridge.callhandler("certificationStores");

if (isAndroid()) window.android.certificationStores();

 


//原生调用H5

bridge.js

function setupWebViewJavascriptBridge (callback) {

    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)}

    export default { 

        callhandler (name, data, callback)

        {   

            setupWebViewJavascriptBridge(function (bridge)

            {   

                bridge.callHandler(name, data, callback)   

            }) 

        }, 

        registerhandler (name, callback)

        { 

            setupWebViewJavascriptBridge(function (bridge)

            {     

                bridge.registerHandler(name, function (data, responseCallback)

                {       

                    callback(data, responseCallback)     

                })   

            }) 

}}

 

main.js

import Bridge from './service/bridge';

Vue.prototype.$bridge = Bridge;

 

mounted() {

window.assignmentAd = item => {

      this.assignmentAd(item);

    };

    window.isFinish = this.isFinish;

    this.backHandler();

  },

//安卓原生调用H5 传值

assignmentAd(item) {

    console.log(item)

}

//ios原生调用H5 传值 并H5返回值给原生

backHandler() {

      this.$bridge.registerhandler("backHandler", (id, responseCallback) => {

        console.log(id)

        responseCallback(true);

      });

    },

////安卓原生调用H5 H5返回值给原生 类型必须为字符串

    isFinish() {

      window.isFinish = null;

      return "1";

    }

你可能感兴趣的:(vue,H5)