Skip to content

前端使用WebViewJavascriptBridge实现JS与iOS、Android客户端交互

  1. JS 调用 native 的 handler(JS 发起请求)
window.WebViewJavascriptBridge.callHandler(
    'handlerName',  // 调用 native 的 handler
    data,   // 传数据给 native
    function(res) {
        // 接收 native 返回的数据 res
    }
);
  1. Native 调用 JS 的方法(提供 handler 给 native)
//注册事件监听
function connectWebViewJavascriptBridge(callback) {
  // Android
  if (window.WebViewJavascriptBridge) {
    callback(WebViewJavascriptBridge)
  } else {
    document.addEventListener(
      'WebViewJavascriptBridgeReady',
      function() {
        callback(WebViewJavascriptBridge)
      },
      false
    );
  }

  // iOS
  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);
}

connectWebViewJavascriptBridge(function(bridge) {
  // 注册一个 JavaScript Handler,native 调用时执行 H5 操作
  bridge.registerHandler("handlerName", function(data, responseCallback) {
     // 接收来自 native 的数据 data
     console.log(data);
     // 返回数据给 Native
     var res = "Response Data";
     responseCallback(res);
  });

  // Android初始化,必须
  bridge.init(function(message, responseCallback) {
     // 接收来自 native 的数据 message
     console.log(message);
     // 返回数据给 Native
     var res = "Response Data";
     responseCallback(res);
  });
});

发表评论

Your email is never published nor shared. Required fields are marked *


TOP