WKWebView與JS互動

ken_ngai發表於2015-11-09

APP有時會套一個網頁在裡面,此時Native與網頁JS進行通訊也是經常要用的到的。貼上小小的粟子

let configuration = WKWebViewConfiguration()
configuration.preferences = WKPreferences()
configuration.preferences.javaScriptEnabled = true
//通過js與webview內容互動配置
configuration.userContentController = WKUserContentController()
        
//往HTML裡面注入指令碼
//let script = WKUserScript(source: "alert(`success`); ",injectionTime: .AtDocumentStart,// 在載入時就新增JS 此方法只在指定的時間點有效
forMainFrameOnly: true) // 只新增到mainFrame中 //configuration.userContentController.addUserScript(script) //JS呼叫Native時要註冊此方法,注意名字是個Key。這裡要注意第一個引數是要實現了WKScriptMessageHandler介面的類名 configuration.userContentController.addScriptMessageHandler(self, name: "ScanQRCode")
//好了,現在網頁JS可以通過以下指令碼與Native通訊了 //window.webkit.messageHandlers.<name>.postMessage({<content>}) for example: window.webkit.messageHandlers.ScanQRCode.postMessage({body:`hello guy`}) wkBrowser = WKWebView(frame: CGRectMake(0, 20, self.view.bounds.width, self.view.bounds.height-20), configuration: configuration)

 實現WKScriptMessageHandler內的方法,JS呼叫Native端會觸發此方法

func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
        if message.name == "ScanQRCode" { //這個名稱與上面配置的要一樣,
            
            //It work by this way
            //self.wkBrowser.evaluateJavaScript("document.getElementById(`abc`).innerHTML=`sssssss`", completionHandler: nil)
            //通過message.body獲取從JS傳遞過來的引數,可以傳JSON或者其它格式
            let id = message.body as! String
            
            /*let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ScanViewController") as! ScanViewController
            controller.delegate = self
            controller.htmlId = id
            //controller.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.9)
            self.modalPresentationStyle = UIModalPresentationStyle.FullScreen
            self.presentViewController(controller, animated: true, completion: { () -> Void in
                //controller.view.backgroundColor = UIColor.clearColor()
            })*/

        }

 從Native呼叫網頁的方法或者執行指令碼可以用到以下程式碼

self.wkBrowser.evaluateJavaScript("$(#"abc").val(`I am come from native`)", completionHandler: nil)

 


相關文章