An iOS bridge for sending messages between Swift and JavaScript in WKWebView
use_frameworks!
pod 'JustBridge', '~> 4.2.0'
JustBridge is easy to use. Just init a bridge and then register handler or call handler.
- import JustBridge and declare an ivar property:
import JustBridge
...
var bridge: JustBridge!
- Instantiate JustBridge with a WKWebView:
bridge = JustBridge(with: webView)
-
Register a handler in Swift, and call a JavaScript handler
-
the
errorMessage
can beHandlerNotExistError
orDataIsInvalidError
, type oferrorMessage
is String -
callback
anderrorCallback
can be nil
-
bridge.register("swiftHandler") { (data, callback) in
print("[js call swift] - data: \(data ?? "nil")\n")
callback("[response from swift] - response data: I'm swift response data")
}
bridge.call("jsHandler", data: data, callback: { responseData in
print(responseData ?? "have no response data")
}, errorCallback: { errorMessage in
print(errorMessage)
})
- Register a handler in JavaScript, and call a Swift handler
- the errorMessage can only be
HandlerNotExistError
, type of errorMessage is String callback
anderrorCallback
can be null
- the errorMessage can only be
window.bridge.register("jsHandler", function(data, callback) {
console.log("[swift call js] - data: " + JSON.stringify(data));
callback("[response from js] - response data: I'm js response data");
});
window.bridge.call("swiftHandler", "hello world from js", function(responseData) {
console.log(responseData.toString())
}, function(errorMessage) {
console.log("error: " + errorMessage)
});
You can clone or download this project for more details.