[[toc]]
demo1: 文本通信
h5 -> app
思路:
- h5 全局属性上挂一个变量
- app 接收这个变量的内容
- 关键API: navigation代理 + navigationAction.request.url?.absoluteString
js
// 这个变量挂载在 request 的 url 上 ,在浏览器实际无法运行,因此不会影响到页面本身
window.location.href="test://hellowolrd"
// app 接收这个变量
navigationAction.request.url?.absoluteString
swift
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
// 【1】设置自己为webview的代理
webView.uiDelegate = self
webView.navigationDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let myURL = URL(string:"http://localhost:5173/") // ok
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
print("viewDidLoad...")
}
}
extension ViewController: WKNavigationDelegate {
//【2】通过 navigationAction.request.url?.absoluteString 获取 h5 传递的数据
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
print("webView decidePolicyFor ...")
print(navigationAction.request.url?.absoluteString)
decisionHandler(.allow)
}
}
app -> h5
思路
- app调用js语法,将app的数据通过 html dom结构或者js方法 传递给h5
- 关键API:webView.evaluateJavaScript
html
<!-- h5页面 -->
<div id="someElement1">test data1</div>
<div id="someElement2"></div>
<script>
window.getText=function(data){
const reuslt = 'test data2:'+data;
document.getElementById('someElement2').innerText = reuslt;
return reuslt;
}
</script>
swift
// app swift
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("webView didFinish 页面加载完成之后调用...")
webView.evaluateJavaScript("document.getElementById('someElement1').innerText='test data1: app'") {
(result, error) in
if let result = result {
print("someElement result: \(result)")
}
if let error = error {
print("someElement error: \(error)")
}
}
webView.evaluateJavaScript("window.getText('app')") { (result, error) in
if let result = result {
print("getText result: \(result)")
}
if let error = error {
print("getText error: \(error)")
}
}
}
demo2: h5通过app调用相机和扫描二维码
思路
- 原生app具备调用相机和扫描二维码的能力
- h5通过jsbridge通知app-》app执行拍照和扫描动作-》将结果返回h5