h5:
Swift:
1.继承WKScriptMessageHandler
实现
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {}
方法,获取信息为message.body
2.启用js,添加ScriptMessageHandler
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//接收h5信息,scan为h5的方法名,页面消失时须移除!!不然会循环引用
webView.configuration.preferences.javaScriptEnabled = **true**
webView.configuration.userContentController.add(**self**, name: "scan")
}
3.页面消失时移除ScriptMessageHandler
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
webView.configuration.userContentController.removeScriptMessageHandler(forName: "scan")
}