Search code examples
iosswiftuiwebview

How to get the html content from UIWebView?


I'm loading a web page using UIWebView

let urlStr = "http://duckduckgo.com"
let urlReq = NSMutableURLRequest(URL: NSURL(string: urlStr)!)
webView.loadRequest(urlReq)

Then, when the page has finished loading, I want to access the html content

func webViewDidFinishLoad(webView: UIWebView) {
    let href = webView.stringByEvaluatingJavaScriptFromString("window.location.href")
    println("window.location.href  = \(href)")

    let doc = webView.stringByEvaluatingJavaScriptFromString("document")
    println("document = \(doc)")
}

But document just return an empty string (Optional("")). The window.location.href part is working fine. What I'm I doing wrong?


Solution

  • I think you have to evaluate the javascript like this:

    let doc = webView.stringByEvaluatingJavaScriptFromString("document.documentElement.outerHTML")
    

    In this case you get the entire HTML.