ihatetoregister ihatetoregister - 1 month ago 15x
Swift Question

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)!)

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 (
). The window.location.href part is working fine. What I'm I doing wrong?


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.