本文介紹WKWebView怎么與js交互,至于怎么用WKWebView這里就不介紹了
html代碼
<html>
<meta charset="UTF-8">
<head>
<title>
H5測(cè)試
</title>
</head>
<body>
<h1 align="center">標(biāo)題1(App調(diào)用Js使標(biāo)題變成紅色)</h1>
<script>
//js調(diào)用APP-傳單個(gè)參數(shù)
function callNativeApp(){
try{
webkit.messageHandlers.callbackHandle.postMessage("Hello World")
}catch(error){
console.error('The native context not exist ')
}
}
//js調(diào)用APP-傳多個(gè)參數(shù)
function callNativeApp2(){
try{
webkit.messageHandlers.callbackHandle2.postMessage({key: "Hello", value: "World"})
}catch(error){
console.error('The native context not exist ')
}
}
//APP調(diào)用js
function changeHead(){
document.querySelector('h1').style.color = "red"
}
</script>
<button style="text-align:center;height:50px;width:200px;font-size:16px" onclick="callNativeApp()">調(diào)用APP(單個(gè)參數(shù))</button>
<button style="text-align:center;height:50px;width:220px;font-size:16px" onclick="callNativeApp2()">調(diào)用APP(多個(gè)個(gè)參數(shù))</button>
</body>
</html>
APP調(diào)JS
- 代碼
//調(diào)用js
webView.evaluateJavaScript("changeHead()", completionHandler: {
(any, error) in
if (error != nil) {
Log.error("\(error)")
}
})
- 結(jié)果

result1.png
JS給APP傳參數(shù)
- 首先注冊(cè)你需要監(jiān)聽的js方法名
//監(jiān)聽js
webView.configuration.userContentController.add(self, name: "callbackHandle")
webView.configuration.userContentController.add(self, name: "callbackHandle2")
- 2.繼承WKScriptMessageHandler 并重寫userContentController方法,在該方法里接收J(rèn)S傳來的參數(shù)
@available(iOS 8.0, *)
func userContentController(_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage) {
switch message.name {
case "callbackHandle":
//單個(gè)參數(shù)
Log.info("\(message.body)")
case "callbackHandle2":
//多個(gè)參數(shù)
if let dic = message.body as? NSDictionary {
let key: String = (dic["key"] as AnyObject).description
let value: String = (dic["value"] as AnyObject).description
Log.info("key: \(key)")
Log.info("value: \(value)")
}
default: break
}
}
- 3.結(jié)果

result.png