-
Notifications
You must be signed in to change notification settings - Fork 11
Native Calling JavaScript APIs
iMoeNya edited this page Apr 23, 2024
·
2 revisions
Use register
or registerAsyn
to register synchronous or asynchronous APIs. Here we have addValue
and append
:
bridge.register('addValue', function(l, r) {
return l + r;
})
bridge.registerAsyn('append', function(arg1, arg2, arg3, respond) {
respond(arg1 + " " + arg2 + " " + arg3);
})
After registration, native can call them with 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 {
// ...
}
}
For native developers, whether an API is synchronous or asynchronous doesn't make too much of a difference for calling.
You can register a namespace that contains multiple functions:
bridge.register("syncFunctions",{
returnAsIs: function(v) {
return v
},
otherFunction: function() {
// ...
}
})
bridge.registerAsyn("asyncFunctions",{
adding100: function(input, respond) {
respond(input + 100)
}
})
Calling from 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 {
// ...
}
}
Call WebView.hasJavaScriptMethod
to check whether or not there is such an API declared in JavaScript.