几乎是默写出来,加上自己理解的博客(iOS面试)
1. js调用iOS
js调用:
window.webkit.messageHandlers.jsToIOS.postMessage("这是js传递到ios的数据");
iOS接收:
self.wkWebView?.configuration.userContentController.add(self, name: "jsToIOS")
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print("JS发送到IOS的数据====\(message.body), name=\(message.name)")
}
2.iOS调用js
iOS调用js
self.wkWebView!.evaluateJavaScript("navButtonAction('test1',18)") {
(response, error) in
print("message: \(response!)")
}
iOS向网页注入JS
let js = "document.getElementsByTagName('h2')[0].innerText='我是ios原生为h5注入的方法'"
let script = WKUserScript.init(source: js, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
wkWebView!.configuration.userContentController.addUserScript(script)
3.参考博客:
IOS-SwiftUI-IOS原生与JavaScript交互的应用 - 知乎
|