To run the example project, clone the repo, and run pod install
from the Example directory first.
1, Inject function
let webView = WKWebView()
webView.holo.inject(function: "window.bridge.log") { (args) in
print(args ?? "")
}
2, Call function in JS
window.bridge.log("hello world")
1, Inject plugin
let webView = WKWebView()
webView.holo.inject(plugin: WebViewLogPlugin())
2, Define plugin by WebViewPluginProtocol
class WebViewLogPlugin: WebViewPluginProtocol {
func log(_ msg: Any) {
print(msg)
}
// MARK: - WebViewPluginProtocol
var identifier: String {
return "holo.webView.bridge.log"
}
var javascript: String {
return """
window.bridge.log = function(msg) {
window.bridge.js_msgSend("holo.webView.bridge.log", "log()", msg)
}
"""
}
func didReceiveMessage(_ fun: String, args: Any?) {
if fun == "log()" {
self.log(msg ?? "")
}
}
}
3, Call function in JS
window.bridge.log("hello world")
Note that if your JS methods are complex, you can also define the JS method in a .js file and return the contents of the file in the var javascript: String { get }
protocol method, like WebViewAlertPlugin.swift & alert.js.
HoloWebViewBridge is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'HoloWebViewBridge'
gonghonglou, gonghonglou@icloud.com
HoloWebViewBridge is available under the MIT license. See the LICENSE file for more info.