For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /note/js/app-communication.md.

App 通信

前言

Web 前端开发与 iOS 前端开发之间的数据交互,需要借助 JavaScript 封装的特定的方法来实现两者之间的逻辑业务交互

封装函数 setupWebViewJavascriptBridge

代码示例
function setupWebViewJavascriptBridge(callback) {
    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);
}
提示

JavaScript 与 iOS App 之间数据交互时,需要借助封装好的 setupWebViewJavascriptBridge 方法来实现两端开发之间的逻辑数据交互问题。

H5 触发事件唤起 iOS App 中的事件函数

代码示例
setupWebViewJavascriptBridge(function (bridge) {
  bridge.callHandler('iOS事件名', {'参数param'}, function responseCallback(responseData) { });
});
事件名:
  • iOS 事件名:为 iOS 开发同事提供的唤起 app 中响应事件的事件名;
  • 参数 param:传递给 iOS app 的参数为 key-value 键值对类型

iOS App 中触发事件唤起前端 JavaScript 封装的方法

代码示例
setupWebViewJavascriptBridge(function (bridge) {
    bridge.registerHandler("jsFn", function (json) {
        var param = JSON.parse(json); // 数据类型转换
        jsFn(param);
    });
});
注意事项
  • jsFn:为 JavaScript 封装的函数方法名;
  • 与 iOS app 交互返回的数据为JSON字符串;
  • 需要 iOS app 传值的时候,则需要先使用 JSON.parse(response) 转换为 JSON 对象 之后再传值给 js 封装的 事件函数。

JavaScript 和 Android App 之间的数据交互

代码示例
window.android.AndroidEventName(params); // params为传递给Android app的参数值
注意事项
  • AndroidEventName:为 Android app 开发提供的事件方法名;
  • 如果在 vue 中实现 Android App 调用 JS 封装的函数方法,则需要将 JS 封装的函数名作用域指定到全局作用域,即 window 下。
  • Android 调用 JS 方法时,与 js 调用自身封装的方法一致。