iOS中WKWebview原生与网页端JS交互常用的方法是
首先在web view中注入标定好的方法名,例如标定一个request方法
let config = WKWebViewConfiguration() let userContent = WKUserContentController();
var dealMessage = DealMessage()
userContent.add(dealMessage, name: "request"); config.userContentController = userContent;
DealMessage类实现代理回掉方法
class DealMessage:NSObject,WKScriptMessageHandler{ func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { print("接收到消息:\(message.body)") guard let web = message.webView else { return } if message.name == "request" { print("接收到消息request:\(message.body)") }else if message.name == "gotoshop" { web.evaluateJavaScript("gotoshopDetail()") } } }
web端 JS调用swif
//js与原生交互 const para = { params: { innerHeight: window.innerHeight, screnHeight: window.screen.height, safeAreaHeightValue: safeAreaHeightValue, top: topSafeAreaHeight, bottom: bottomSafeAreaHeight, }, } const body = JSON.stringify(para) window.webkit.messageHandlers.request.postMessage(body)
Swift调JS就简单了
web.evaluateJavaScript("gotoshopDetail()")
web端提供IOS调用的方法
window.gotoshopDetail = () => { router.push({ name: 'shop', params: { id: props.data.id, }, }) }
标签:web,name,request,JS,window,SwiftUI,Webview,message From: https://www.cnblogs.com/duzhaoquan/p/17933421.html