norq
norq

Reputation: 1434

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?

Upvotes: 16

Views: 24277

Answers (3)

Roman Esin
Roman Esin

Reputation: 412

Now, when UIWebView is deprecated, you'll need to use syntax like this:

webView.evaluateJavaScript("document.documentElement.outerHTML") { (html, error) in
    guard let html = html as? String else {
        print(error)
        return
    }
    // Here you have HTML of the whole page.
}

After that you can create a function like this that'll easily get HTML from webView:

func getHTML(_ completion: @escaping (String) -> ()) {
    webView.evaluateJavaScript("document.documentElement.outerHTML") { (html, error) in
        guard let html = html as? String else {
            print(error)
            return
        }
        completion(html)
    }
}

getHTML { html in
    // Here you have HTML string
    print(html) // for example...
}

Upvotes: 8

Niccolò Passolunghi
Niccolò Passolunghi

Reputation: 6024

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.

Upvotes: 25

sheleshrawat
sheleshrawat

Reputation: 11

I Found the solution of problem regarding jqxWidget. That UIWebView content were referencing .js and .css file which is already bundled in App. I had just only add the base url of App's MainBundle.

NSString  *html = [self.webview1 stringByEvaluatingJavaScriptFromString: @"document.documentElement.outerHTML"]; //document.body.innerHTML

NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];

[objFullScreenViewCntrl.webview2 loadHTMLString:html baseURL:baseURL];

Upvotes: 0

Related Questions