加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift - WKWebView JS 交互

发布时间:2020-12-14 06:06:54 所属栏目:百科 来源:网络整理
导读:本文介绍WKWebView怎么与js交互,至于怎么用WKWebView这里就不介绍了 html代码 html meta charset = "UTF-8" head title H5测试 / title / head body h1 align = "center" 标题1(App调用Js使标题变成红色) / h1 script //js调用APP-传单个参数 function ca

本文介绍WKWebView怎么与js交互,至于怎么用WKWebView这里就不介绍了

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传参数

    1. 首先注册你需要监听的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.结果

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读