ihatetoregister ihatetoregister - 1 year ago 111
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download