🌉 A Bridge for Sending Messages between Swift and JavaScript in WKWebViews.
MIT License
This project is inspired by WebViewJavascriptBridge!
You can write hybrid modules in just a few lines of code by using WKWebViewJavascriptBridge without the need to be concerned with the underlying messaging implementation.
It is well known that WKWebView loads web pages faster and more efficiently than UIWebView, and also doesn't have as much memory overhead for you.
Under the current timeline, most iOS apps only support iOS 9.0+.
The reason for the iOS platform cross-domain access vulnerability is due to UIWebView turning on the WebKitAllowUniversalAccessFromFileURLs and WebKitAllowFileAccessFromFileURLs options.
WKWebView default allowFileAccessFromFileURLs and allowUniversalAccessFromFileURLs option is false.
bridge = WKWebViewJavascriptBridge(webView: webView)
bridge.register(handlerName: "testiOSCallback") { (parameters, callback) in
print("testiOSCallback called: \(String(describing: parameters))")
callback?("Response from testiOSCallback")
}
bridge.call(handlerName: "testJavascriptHandler", data: ["foo": "before ready"], callback: nil)
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)
}
setupWKWebViewJavascriptBridge(function(bridge) {
/* Initialize your app here */
bridge.registerHandler('testJavascriptHandler', function(data, responseCallback) {
console.log('iOS called testJavascriptHandler with', data)
responseCallback({ 'Javascript Says':'Right back atcha!' })
})
bridge.callHandler('testiOSCallback', {'foo': 'bar'}, function(response) {
console.log('JS got response', response)
})
})
pod 'WKWebViewJavascriptBridge', '~> 1.2.0'
to your Podfile.pod install
or pod update
.import WKWebViewJavascriptBridge
.github "Lision/WKWebViewJavascriptBridge" ~> 1.2.0
to your Cartfile.carthage update --platform ios
.WKWebViewJavascriptBridge
framework to your project.Either clone the repo and manually add the Files in WKWebViewJavascriptBridge.
This framework requires iOS 9.0+
and Xcode 9.0+
.
WKWebViewJavascriptBridge is provided under the MIT license. See LICENSE file for details.