swift - WKWebView JS 交互
2017-09-13 17:54
453 查看
本文介绍WKWebView怎么与js交互,至于怎么用WKWebView这里就不介绍了
结果
2.继承WKScriptMessageHandler 并重写userContentController方法,在该方法里接收JS传来的参数
3.结果
html代码
<html> <meta charset="UTF-8"> <head> <title> H5测试 </title> </head> <body> <h1 align="center">标题1(App调用Js使标题变成红色)</h1> <script> //js调用APP-传单个参数 function callNativeApp(){ try{ webkit.messageHandlers.callbackHandle.postMessage("Hello World") }catch(error){ console.error('The native context not exist ') } } //js调用APP-传多个参数 function callNativeApp2(){ try{ webkit.messageHandlers.callbackHandle2.postMessage({key: "Hello", value: "World"}) }catch(error){ console.error('The native context not exist ') } } //APP调用js function changeHead(){ document.querySelector('h1').style.color = "red" } </script> <button style="text-align:center;height:50px;width:200px;font-size:16px" onclick="callNativeApp()">调用APP(单个参数)</button> <button style="text-align:center;height:50px;width:220px;font-size:16px" onclick="callNativeApp2()">调用APP(多个个参数)</button> </body> </html>
APP调JS
代码//调用js webView.evaluateJavaScript("changeHead()", completionHandler: { (any, error) in if (error != nil) { Log.error("\(error)") } })
结果
JS给APP传参数
首先注册你需要监听的js方法名//监听js webView.configuration.userContentController.add(self, name: "callbackHandle") webView.configuration.userContentController.add(self, name: "callbackHandle2")
2.继承WKScriptMessageHandler 并重写userContentController方法,在该方法里接收JS传来的参数
@available(iOS 8.0, *) func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { switch message.name { case "callbackHandle": //单个参数 Log.info("\(message.body)") case "callbackHandle2": //多个参数 if let dic = message.body as? NSDictionary { let key: String = (dic["key"] as AnyObject).description let value: String = (dic["value"] as AnyObject).description Log.info("key: \(key)") Log.info("value: \(value)") } default: break } }
3.结果
相关文章推荐
- WKWebView的简单使用,与js交互(js调用OC或swift方法)
- WKWebView新特性及JS交互
- iOS 8 WkWebView 网页的配置和前进,后退,js 交互和进度条的加载
- UIWebView和WKWebView的使用及js交互
- [IOS开发]js与WKwebview交互Demo(调取二维码扫描)
- iOS 8 WkWebView 网页的配置和前进,后退,js 交互和进度条的加载
- ios WKWebView 与 JS 交互实战技巧
- oc与js交互-----WKWebView
- WKWebView、WebView和JS的交互方式详解
- WKWebView 与JS的交互
- WKWebView 与 JS 交互
- JS交互的方法(下)WKWebView
- WKwebView与JS交互(h5主动)
- iOS下OC与JS的交互(WKWebview-MessageHandler实现)
- WKWebView 与 JS 交互
- iOS OC与H5网页交互之OC传值给JS(WKWebView)
- WKWebView 基本使用及与JS交互
- WKWebView新特性及JS交互
- WKWebView OC与js的交互
- OC与JS交互之WKWebView