Skip to content

Native 调用 JavaScript 接口

iMoeNya edited this page Apr 23, 2024 · 2 revisions

注册接口

在 JavaScript 代码中,通过 registerregisterAsyn 来注册同步和异步接口。下面的例子注册了 addValueappend 两个方法:

bridge.register('addValue', function(l, r) {
  return l + r;
})
bridge.registerAsyn('append', function(arg1, arg2, arg3, respond) {
  respond(arg1 + " " + arg2 + " " + arg3);
})

此后,Native 可以通过 WebView.call 方法调用它们:

webView.call("addValue", with: [1, 1], thatReturns: Int.self) {
    do {
        let _ = try $0.get()  // 2
    } catch {
        // ...
    }
}
webView.call("append", with: ["1", "2", "3"], thatReturns: String.self) {
    do {
        let _ = try $0.get()  // 1 2 3
    } catch {
        // ...
    }
}

对于 Native 来说,同步的接口和异步的接口在使用上是一致的。

注册命名空间

你可以注册一个命名空间,命名空间内可以包含多个方法:

bridge.register("syncFunctions",{
  returnAsIs: function(v) {
    return v
  },
  otherFunction: function() { 
    // ...
  }
})
bridge.registerAsyn("asyncFunctions",{
  adding100: function(input, respond) {
    respond(input + 100)
  }
})

Native 端调用:

webView.call("syncFunctions.returnAsIs", with: [99], thatReturns: Int.self) {
    do {
        _ = try $0.get()  // 99
    } catch {
        // ...
    }
}
webView.call("asyncFunctions.adding100", with: [7], thatReturns: Int.self) {
    do {
        _ = try $0.get()  // 107
    } catch {
        // ...
    }
}

检查接口是否存在

你可以调用 WebView.hasJavaScriptMethod 来检查是否存在某个接口。

Clone this wiki locally