swift - WKWebView JS 交互

本文介紹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-傳單個參數(shù)
             function callNativeApp(){
                try{
                    webkit.messageHandlers.callbackHandle.postMessage("Hello World")
                }catch(error){
                    console.error('The native context not exist ')
                }
            }
            //js調用APP-傳多個參數(shù)
            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(單個參數(shù))</button>
            
            <button style="text-align:center;height:50px;width:220px;font-size:16px" onclick="callNativeApp2()">調用APP(多個個參數(shù))</button>
    </body>
</html>

APP調JS

  • 代碼
//調用js
webView.evaluateJavaScript("changeHead()", completionHandler: {
            (any, error) in
            if (error != nil) {
                Log.error("\(error)")
            }
        })
  • 結果
result1.png

JS給APP傳參數(shù)

    1. 首先注冊你需要監(jiān)聽的js方法名
//監(jiān)聽js
webView.configuration.userContentController.add(self, name: "callbackHandle")
webView.configuration.userContentController.add(self, name: "callbackHandle2")
  • 2.繼承WKScriptMessageHandler 并重寫userContentController方法,在該方法里接收JS傳來的參數(shù)
@available(iOS 8.0, *)
func userContentController(_ userContentController: WKUserContentController,
                               didReceive message: WKScriptMessage) {

        switch message.name {
        case "callbackHandle":
            //單個參數(shù)
            Log.info("\(message.body)")
        case "callbackHandle2":
            //多個參數(shù)
            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.結果
result.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容