前言
本文仅限于 UIWebView/WKWebview 和 swift 的交互,如果需要 js 直接交互请查看 JSPatch 。
UIWebView
webView 传递给 swift
利用 request.URL.scheme。例如约定一个 com.myapp。则发请求时url=com.myapp://?function=functionName¶ms=params
swift 接收
先解析 url,然后在代理方法 func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool 中,if request.URL.scheme == com.myapp { self.functionName(params) }
swift 传递给 webView
webView.stringByEvaluatingJavaScriptFromString(jsString)
WKWebView
方法一
初始化,遵循 WKNavigationDelegate, WKUIDelegate
1
2web = WKWebView.init(frame: CGRect(x: 0, y: 0, width: 300, height: 500), configuration: WKWebViewConfiguration())
web.navigationDelegate = self
拦截URL
1
2
3
4
5
6
7func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
print(navigationAction.request.url)
//在这里执行操作
self.evaluateJavaScript(js)
decisionHandler(.cancel)
return
}
方法二
swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19class MyWebView: WKWebView, WKScriptMessageHandler {
class func webView(frame: CGRect) -> MyWebView {
let contentController = WKUserContentController()
let config = WKWebViewConfiguration()
config.userContentController = contentController
let webView = MyWebView.init(frame: frame, configuration: config)
contentController.add(webView, name: "test")
return webView
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print(message.name)
print(message.body)
}
}1
2
3func buttonTap(_ sender: Any) {
webView.evaluateJavaScript("changeColor('blue')", completionHandler: nil)
}html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<html lang="zh-cn">
<head>
<meta charset="utf-8" />
<script type="text/javascript">
function test() {
// alert("test");
window.webkit.messageHandlers.test.postMessage("test message");
}
function changeColor(color) {
var h1 = document.getElementsByTagName('h1')
h1[0].style.color = color;
}
</script>
</head>
<body>
<h1>我的第一个标题</h1>
<p>我的第一个段落。</p>
<button onclick="test()">Test!</button>
</body>
</html>