To use the bridge, follow these four steps to connect your Swift native code and JavaScript web code.
1. Instantiate the bridge in Swift
Initialize the bridge using your existing WKWebView instance:
bridge = WKWebViewJavascriptBridge(webView: webView)
2. Register Handlers in Native (Swift)
Use register(handlerName:...) to listen for calls from JavaScript, and call(handlerName:...) to trigger a handler in JavaScript:
// Listen for JS calls
bridge.register(handlerName: "testiOSCallback") { (paramters, callback) in
print("testiOSCallback called: \(String(describing: paramters))")
callback?("Response from testiOSCallback")
}
// Call a JS handler
bridge.call(handlerName: "testJavascriptHandler", data: ["foo": "before ready"], callback: nil)
3. Setup the Bridge in JavaScript
Copy and paste this helper function into your JavaScript code to initialize the connection:
function setupWKWebViewJavascriptBridge(callback) {
if (window.WKWebViewJavascriptBridge) { return callback(WKWebViewJavascriptBridge); }
if (window.WKWVJBCallbacks) { return window.WKWVJBCallbacks.push(callback); }
window.WKWVJBCallbacks = [callback];
window.webkit.messageHandlers.iOS_Native_InjectJavascript.postMessage(null)
}
4. Use the Bridge in JavaScript
Call setupWKWebViewJavascriptBridge with a callback function. Inside that callback, you can use registerHandler to listen for native calls and callHandler to send messages to native code:
setupWKWebViewJavascriptBridge(function(bridge) {
/* Initialize your app here */
// Listen for Native calls
bridge.registerHandler('testJavascriptHandler', function(data, responseCallback) {
console.log('iOS called testJavascriptHandler with', data)
responseCallback({ 'Javascript Says':'Right back atcha!' })
})
// Call Native handlers
bridge.callHandler('testiOSCallback', {'foo': 'bar'}, function(response) {
console.log('JS got response', response)
})
})