[[toc]]
demo1: 文本通信
h5 -> app
思路:
- h5 全局属性上挂一个变量
- app 接收这个变量的内容
- 关键API: navigation代理 + navigationAction.request.url?.absoluteString
// 这个变量挂载在 request 的 url 上 ,在浏览器实际无法运行,因此不会影响到页面本身
window.location.href="test://hellowolrd"
// app 接收这个变量
navigationAction.request.url?.absoluteString
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 = selfwebView.navigationDelegate = selfview = webView }override func viewDidLoad() {super.viewDidLoad()let myURL = URL(string:"http://localhost:5173/") // oklet 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
<!-- 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>
// app swift
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {print("webView didFinish 页面加载完成之后调用...")webView.evaluateJavaScript("document.getElementById('someElement1').innerText='test data1: app'") {(result, error) inif let result = result {print("someElement result: \(result)")}if let error = error {print("someElement error: \(error)")}}webView.evaluateJavaScript("window.getText('app')") { (result, error) inif let result = result {print("getText result: \(result)")}if let error = error {print("getText error: \(error)")}}
}
demo2: h5通过app调用相机和扫描二维码
思路
- 原生app具备调用相机和扫描二维码的能力
- h5通过jsbridge通知app-》app执行拍照和扫描动作-》将结果返回h5