您的当前位置:首页正文

vue App内嵌H5 之间通信 《WebViewJavascriptBridge》

2024-12-01 来源:个人技术集锦

1、新建 bridge.js

let u = navigator.userAgent;
function setupWebViewJavascriptBridge(callback) {
  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];
    var WVJBIframe = document.createElement("iframe");
    WVJBIframe.style.display = "none";
    WVJBIframe.src = "https://__bridge_loaded__";
    document.documentElement.appendChild(WVJBIframe);
    setTimeout(function () {
      document.documentElement.removeChild(WVJBIframe);
    }, 0);
  }
  if (!/(iPhone|iPad|iPod|IOS)/i.test(u)) {
    if (window.WebViewJavascriptBridge) {
      // return callback(WebViewJavascriptBridge);
      return callback(window.WebViewJavascriptBridge);
    } else {
      document.addEventListener(
        "WebViewJavascriptBridgeReady",
        function () {
          window.WebViewJavascriptBridge.init(function (
            message,
            responseCallback
          ) {
            // 在这里处理来自 Android 的初始化
            console.log("Received message from Android:", message);
            responseCallback("Response from WebView");
          });
          callback(WebViewJavascriptBridge);
        },
        false
      );
    }
  }
}
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);
      });
    });
  },
};

2、使用

import bridge from "@/utils/bridge.js";
bridge.registerhandler("appToVue", (data, responseCallback) => {
	//data : app传过来的值
  	console.log(data);
    var responseData = { "Javascript Says": "Right back atcha!" };
    // vue返回给app的数据
    responseCallback(responseData);
  });
显示全文