1.利用js的addEventListener(),方法自己注入事件监听
2.window.webkit.messageHandlers.testJS.postMessage(stundet),实现js和原生的交互
- WKScriptMessageHandler会引起内存泄露的问题()
//TODO: 加载html xinle 2019.09.11
extension WebController {
func loadWith(HTMLStr: String) {
print("~~~HTMLStr:\(HTMLStr)~~~")
self.webView.loadHTMLString(HTMLStr, baseURL:nil)
}
func addJS() {
// 动态添加JS代码,实现某个控件的点击事件
let jsStr = "var stundet = {'name': 'goToAppHome'};var js_name = document.getElementsByClassName('back-button ant-btn ant-btn-default ant-btn-block')[0];function haha() {window.webkit.messageHandlers.testJS.postMessage(stundet);};js_name.addEventListener('click', haha, false);"
self.webView.evaluateJavaScript(jsStr) {[weak self] (_, error) in
print("~~~js执行结果:\(String(describing: error))~~~")
if (error == nil) {
let userVC:WKUserContentController = self?.webView.configuration.userContentController ?? WKUserContentController()
if !(self?.isAddJS ?? false) {
userVC.addHandler(self ?? WebController(), name: "testJS")
self?.isAddJS = true
}
}
}
}
func testJS(name: String) {
print("js调用原生方法, 参数name:\(name)")
if name == "goToAppHome" {
navigationController?.popToRootViewController(animated: true)
}
}
}
// 实现代理
extension WebController: WKScriptMessageHandler {
// JS调用原生方法的处理
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print("JS 调用了\(message.name)方法,传回参数\(message.body)")
if message.name == "testJS" {
let data: Dictionary = message.body as! Dictionary<String, Any>
testJS(name:data["name"] as! String)
}
}
}
解决WKScriptMessageHandler内存泄露
import UIKit
import WebKit
class WeakScriptMessageDelegate: NSObject, WKScriptMessageHandler {
// 弱引用
weak var delegate: WKScriptMessageHandler?
init(_ delegate: WKScriptMessageHandler) {
super.init()
self.delegate = delegate
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
self.delegate?.userContentController(userContentController, didReceive: message)
}
}
// 扩展WKUserContentController
extension WKUserContentController {
func addHandler(_ message: Any, name: String) {
if let msg = message as? WKScriptMessageHandler {
self.add(WeakScriptMessageDelegate(msg), name: name)
}
}
}
网友评论