use
git clone https://github.com/JianweiWangs/Chopper.git
cd Chopper
make
to fetch and build source code quickly.
To run the example project, clone the repo, and run make
from the root directory first.
There are some script help you develop and PR.
# install dependence and open project
make
# install dependence
make install
# build test
make test
# open project
make open
# quit Xcode
make quit
Before you pull request, make sure test success.
- create a javascript module
import Chopper
class TestModule: JavaScriptModuleInterface {
// test module
var module: String {
return "test"
}
// actions, you can add any action you want
var moduleMapping: [String : Dispatch] {
return [
"showAlert" : showAlert
]
}
func showAlert(message: JavaScriptMessage, callback: @escaping (Bool, [String : Any]) -> Void) {
print(message.context.frameViewController)
print(message.context.viewController)
print(message)
callback(true, ["code" : "0"])
}
}
- create bridge, inject module to dataSource
import Chopper
class ViewController: UIViewController {
@IBOutlet weak var webview: WKWebView!
var jsbridge: JavaScriptBridge!
override func viewDidLoad() {
super.viewDidLoad()
jsbridge = JavaScriptBridge(dataSource: self)
}
}
extension ViewController: JavaScriptBridgeDataSource {
// you can return multiple module instance, the modules more there are, the more actions can be handle
var modules: [JavaScriptModuleInterface] {
return [TestModule()]
}
var viewController: UIViewController {
return self
}
var webView: WKWebView {
return self.webview
}
}
- JavaScript Import it
dispatch('test', 'showAlert', {
'title': 'Chopper',
'message': 'this is a js call native test'
}, function (success, params) {
alert('callback isSuccess: ' + success + ' params: ' + params.code)
})
You also call use convenience regist to bridge webview script
jsbridge.regist(module: "convenience", action: "showAlert") { [unowned self] (message, callback) in
// recommand use message.context.viewController instead of `self`
// if use self, use weak or unowned to avoid reference cycle
print(message.context.viewController == self) // true
print(message)
callback(true, ["code": 1])
}
Swift 4.0
, iOS 8.0
Chopper is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'Chopper'
JianweiWangs, [email protected]
Chopper is available under the MIT license. See the LICENSE file for more info.