H5与原生交互(IOS&Android)

H5与原生IOS交互——WebViewJavascriptBridge

Web环境初始化

在入口文件index.html依次引入nativeMethods.js,jsMethods.js,bridge_regist.js

// JS调用native的方法: nativeMethods.js
var nativeMethodDefaultData = {
  shareData: {
    shareTitle: '',
    shareDes: '',
    shareImg: '',
    shareUrl: '',
    shareControl: '',
    shareCopyTexts: '',
    tdData: '',
    isAuth: ''
  },
  hotShareData: {
    shareId: '',
    shareTo: '',
    shareTitle: '',
    shareDes: '',
    shareImg: '',
    shareUrl: '',
    shareControl: '',
    shareText: '',
    shareImage: '',
    shareCopyTexts: '',
    shareType: '',
    tdData: ''
  }
}
// 原生调用js的方法:jsMethods.js
var jsMethodForNative = {
  registerAction: function(data, callback) {
    // console.log('native给的data', data)
    //处理oc给的传参
    var responseData = { 'result': 'handle success' }
    //处理完,回调传值给oc
    callback(responseData)
  },
  gotPhotos: function(data, callback) {
    // window.photoData = data;
    window.getPic(data);
    //处理oc给的传参
    var responseData = { 'result': 'handle success' }
    //处理完,回调传值给oc
    callback && callback(responseData)
  }
}
// 函数注册:bridge_regist.js
var ClassmateNative = (function() {
  var ua = window.navigator.userAgent.toLocaleLowerCase()
  var isIos = /iphone|ipod|ipad/.test(ua)
  // 注册方法, 参数是一个回调, WebViewJavascriptBridge会作为参数传入callback
  var setupWebViewJavascriptBridge = function(callback) {
    // console.log('注册用于交互注册的方法')
    // ios注册
    if (window.WebViewJavascriptBridge) {
      return callback(WebViewJavascriptBridge)
    }
    if (isIos) {
      if (window.WVJBCallbacks) {
        return window.WVJBCallbacks.push(callback)
      }
      window.WVJBCallbacks = [callback]
      var WVJBIframe = document.createElement('iframe')
      WVJBIframe.id = 'wvjb'
      WVJBIframe.style.display = 'none'
      WVJBIframe.src = 'https://__bridge_loaded__'
      document.documentElement.appendChild(WVJBIframe)
      setTimeout(function() {
        document.documentElement.removeChild(WVJBIframe)
      }, 0)
    } else {
      // 安卓注册
      if (window.WebViewJavascriptBridge) {
        callback(WebViewJavascriptBridge)
      } else {
        document.addEventListener(
          'WebViewJavascriptBridgeReady',
          function() {
            // console.log('安卓初始化==>')
            callback(WebViewJavascriptBridge)
          },
          false
        )
      }
    }
  }
  // 方法对象, 注册后的所有方法都放在这里
  var methodObj = {}
  var keys = Object.keys(nativeMethodDefaultData)
  for (var i = 0; i < keys.length; i += 1) {
    (function(idx) {
      var k = keys[idx]
      methodObj[k] = function(data, callback) {
        setTimeout(function() {
          // console.log('call' + k, data, callback)
          methodObj[k](data, callback)
        }, 100)
      }
    })(i)
  }

  // 注册所有native提供给js调用的方法: callHandler
  var registNativeMethodForJs = function(bridge) {
    var keys = Object.keys(nativeMethodDefaultData)
    for (var i = 0; i < keys.length; i += 1) {
      (function(idx) {
        var k = keys[idx]
        methodObj[k] = function(data, callback) {
          var options = nativeMethodDefaultData[k]
          var optionsToNative = {}
          // console.log('function-data===>', data)
          for (var d in options) {
            optionsToNative[d] = options[d]
          }
          for (var d in data) {
            optionsToNative[d] = data[d]
          }
          // console.log('optionsToNative===>', optionsToNative)
          // 处理 js 调用 native
          bridge.callHandler(k, optionsToNative, function(response) {
            // 处理native过来的回调
            callback && callback(response)
          })
        }
      })(i)
    }
  }

  // 注册所有js提供给native的方法: registerHandler
  var registJsMethodfornative = function(bridge) {
    // console.log('注册js提供的方法')
    var keys = Object.keys(jsMethodForNative)
    for (var i = 0; i < keys.length; i += 1) {
      var k = keys[i]
      // 处理 native 调用 js
      bridge.registerHandler(k, jsMethodForNative[k])
    }
  }

  // 注册
  setupWebViewJavascriptBridge(function(bridge) {
    registNativeMethodForJs(bridge)
    registJsMethodfornative(bridge)
  })
  return methodObj
})()

H5与原生交互——codova

在入口文件index.html中引入cordova.android.js ,然后和原生协同封装相同函数,进行调用。

// native.js
import { isInTxhApp, isAndroid, isJsbridge } from 'config'
const obj = {}
if (isJsbridge) {
  obj.method = window.ClassmateNative
  console.log('window.ClassmateNative.isJsbridge', window.ClassmateNative)
} else {
  const ClassmateNative = {
    /**
     * 调用native方法
     * @param interval 执行间隔时间
     * @param callback 需要地的函数
     * @param timeout  超时时间
     */
    execNativeMethod: (interval, callback, timeout) => {
      let timer = null

      function intervalFun() {
        timer = setTimeout(() => {
          if (window.cordova.exec) {
            callback()
            clearTimeout(timer)
          } else {
            intervalFun(interval, callback)
          }
        }, interval)
      }

      intervalFun()
      setTimeout(() => {
        clearTimeout(timer)
      }, timeout)
    },

    // 唤起native分享页面
    callNativeShare: (data, success, error) => {
      const options = {
        shareId: '',
        shareUrl: '',
        tdData: '',
        isAuth: ''
      }
      for (const d in data) {
        options[d] = data[d]
      }
      const suc = success || null
      const err = error || null
      ClassmateNative.execNativeMethod(
        20,
        function() {
          window.cordova.exec(suc, err, 'commTools', 'callNativeShare', [options])
        },
        5000
      )
    },
    /**
     * 获取设备ID
     *  无参数
     */
    getDeviceId: (data, success = null, error = null) => {
      ClassmateNative.execNativeMethod(
        20,
        () => {
          window.cordova.exec(success, error, 'commTools', 'getDeviceId', [data])
        },
        5000
      )
    },
    /**
     * 复制内容到剪贴板
     *
     */
    copyToClipboard: (options, success = null, error = null) => {
      console.log('复制内容到剪贴板', options)
      ClassmateNative.execNativeMethod(
        20,
        () => {
          window.cordova.exec(success, error, 'commTools', 'copyToClipboard', [options])
        },
        2000
      )
    }
  }
  obj.method = ClassmateNative
  console.log('cordova.ClassmateNative', ClassmateNative)
}
export default obj.method

相关文章

WebViewJavascriptBridge原理解析
github:WebViewJavascriptBridge

你可能感兴趣的:(H5与原生交互(IOS&Android))