Swift4 - WKWebView 에서 console.log 사용하기

Programming/Swift 2018.07.02 13:13 Posted by 파란크리스마스

출처

Code

    func initWebView(activityIndicator: UIActivityIndicatorView) {
        // 생략...
        contentController.add(self, name: "native_console_log")
        // 생략...
    }

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if(message.name == "native_console_log") {
            native_console_log(didReceive: message)
        }
    }

    func native_console_log(didReceive message: WKScriptMessage) {
        print(NSString(string: "console.log: \(message.body)"))
    }
 
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        #if CONSOLE_LOG
            let js = "var console = { log: function(message) { webkit.messageHandlers.native_console_log.postMessage(JSON.stringify(message)) } }"
            webView.evaluateJavaScript(js)
        #endif
    }

빌드 옵션 추가



 

티스토리 툴바