Search code examples
swiftwkwebview

Get HTML from WKWebview in Swift


I log into a website using WKWebView and now i would like to parse the html of the website. How can I access the websites html in swift? I know how it works for a UIWebView but not for WKWebView.

Thanks for your help!


Solution

  • If you wait until the page has loaded you can use:

    webView.evaluateJavaScript("document.documentElement.outerHTML.toString()") {
        print(html)
    }
    

    You could also inject some javascript that returns you back the HTML.

    let script = WKUserScript(source: javascriptString, injectionTime: injectionTime, forMainFrameOnly: true)
    userContentController.addUserScript(script)
    self.webView.configuration.userContentController.addScriptMessageHandler(self, name: "didGetHTML")
    
    …
    
    func userContentController(userContentController: WKUserContentController,
            didReceiveScriptMessage message: WKScriptMessage) {
         
        guard message.name == "didGetHTML", 
            let html = message.body as? String else { 
            return 
        }
    
        print(html)
    }
    

    The javascript you could inject looks something like:

    webkit.messageHandlers.didGetHTML.postMessage(document.documentElement.outerHTML.toString());