Skip to content

Bridge API

RPC 通道。#include "webview/bridge.hpp"。每 Window 自带一个,经 win->... 访问。

注册槽

cpp
template<class F>
void on(std::string name, F&& f);

注册槽函数。参数从 JSON 反序列化,返回值序列化回 JS。返回 std::future<T> → JS 端 Promise。

cpp
win->on("add", [](int a, int b) { return a + b; });
win->on("fetch", [](int id) {
    std::promise<json> p; p.set_value(load(id)); return p.get_future();
});

同步调用

cpp
template<class T, class... A>
T call(const std::string& name, A&&... args);

同步调 JS 槽,嵌套泵等 Promise,带超时与重入死锁检测。

cpp
auto s = win->call<std::string>("greet", "world");

异常:

  • 无 transport → runtime_error("bridge: no transport")
  • 重入同名 channel → runtime_error("bridge: reentrant call ...")
  • 超时 → runtime_error("bridge: call ... timed out")

即发即忘

cpp
template<class... A>
void send(const std::string& name, A&&... args);

不等返回。无 transport 时静默 no-op。

Transport / Executor

方法说明
setTransport(BridgeTransport*)注入发送通道(Window 已设)
setExecutor(Executor)注入 worker 线程池
callOnExecutor(task)把任务丢 executor
setWaitHook(hook)call 等待时的自定义泵

状态查询

方法说明
handlerCount()已注册槽数
hasPending(id) / hasPending()是否有未决调用

envelope 信封

json
{ "id": 1, "channel": "add", "args": [2, 3] }   // 请求
{ "id": 1, "result": 5 }                          // 回复
{ "id": 1, "error": "..." }                       // 错误

前端 bridge 对象

runtime.js 自动注入 window.bridge

方法说明
bridge.call(name, ...args)调 C++ 槽,返 Promise
bridge.on(name, fn)注册 JS 槽
bridge.send(name, ...args)通知 C++