1111.png
1.添加交互名字,并加载本地测试html文件
加载web
//WKNavigationDelegate, WKScriptMessageHandler, WKUIDelegate
override func viewDidLoad() {
super.viewDidLoad()
// 设置webView的配置
let config = WKWebViewConfiguration.init()
// 注入名字
config.userContentController.add(self, name: "JSBridge")
//创建webView
webView = WKWebView.init(frame: self.view.bounds, configuration: config)
//导航代理
webView.navigationDelegate = self
//交互代理
webView.uiDelegate = self
//加载网页
let filePath = Bundle.main.path(forResource: "index", ofType: "html") ?? ""
//获取代码
let pathURL = URL(fileURLWithPath: filePath)
let request = URLRequest.init(url: pathURL)
//webView.allowsBackForwardNavigationGestures = true
webView.load(request)
view.addSubview(webView)
}
2.写注入代码,并在WKwebView加载完成后注入js代码
网页加载完成开始注入
//网页加载完成
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
//注入监听输入框改变的方法和点击button的方法
//获取js代码存放路径
let filePath = Bundle.main.path(forResource: "bridge", ofType: "js") ?? ""
//获取代码
guard var jsString = try? String(contentsOfFile:filePath ) else {
// 沒有读取出來则不执行注入
return
}
//在bridge.js文件里给输入框赋值是临时的,这里可以替换
jsString = jsString.replacingOccurrences(of: "Placeholder_searchKey", with: "这里可以更换值")
//获取到的代码 注入到web
webView.evaluateJavaScript(jsString, completionHandler: { _, _ in
print("代码注入成功")
})
}
3.接收消息并提示
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
//接收到js发送的消息
//判断消息名字
if message.name == "JSBridge" {
guard let body = message.body as? [String : AnyObject] else{
return
}
if body["id"] as! String == "sumit" {
let value = body["value"] as! String
//弹窗控制器
let alertVC = UIAlertController.init(title: "提示", message: value, preferredStyle: UIAlertController.Style.alert)
let canclelBtn = UIAlertAction.init(title: "ok", style: UIAlertAction.Style.cancel, handler: nil)
alertVC.addAction(canclelBtn)
self.present(alertVC, animated: true, completion: nil)
}
if body["id"] as! String == "searchKey" {
let searchKey = body["value"] as! String
print("输入中:\(searchKey)")
}
}
}
4.测试html文件
测试web代码 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ios原生和Html交互</title>
<style>
#form1 {
text-align: center;
}
button,input{
width: 250px;
}
</style>
</head>
<body>
<div id="form1">
<div>
<input type="text" placeholder="请输入关键字" id = "searchKey">
</div>
<br>
<div>
<button id="sumit">搜索</button>
</div>
</div>
</body>
</html>
5.注入的js代码
这里直接创建一个bridge.js文件,来加载
//需要注入的js方法
//输入框值改变
function inputDidInput(input) {
//向原生发送消息, 并传递
window.webkit.messageHandlers.JSBridge.postMessage({id:"searchKey",value:input.target.value});
}
//点击搜索按钮
function clickBtn(btn) {
//向原生发送消息, 并传递
var input = document.getElementById("searchKey");
//输入框的值
var searchKey = input.value
window.webkit.messageHandlers.JSBridge.postMessage({id:"sumit",value:searchKey});
}
function demoFun() {
//获取输入框
var input_keyword = document.getElementById("searchKey");
//添加输入事件
input_keyword.addEventListener('input',inputDidInput)
//输入框的值
input_keyword.value = "Placeholder_searchKey"
//获取button
var button = document.getElementById("sumit");
button.addEventListener('click', clickBtn);
}
//注入成功后先调用执行
demoFun();