0

I am trying to obtain the data within the header of a web page that is being displayed in a UIWebView.

How do I get the raw (unformatted) HTML string from the UIWebView?

Also, I'm using iOS 9.

My question is similar to Reading HTML content from a UIWebView , but this post is from 6 years ago.

Community
  • 1
  • 1
JavaMaMocha
  • 70
  • 1
  • 11

3 Answers3

4

From the top answer on the question you linked:

NSString *html = [yourWebView stringByEvaluatingJavaScriptFromString: 
                                     @"document.body.innerHTML"];

would translate into Swift:

let html = yourWebView.stringByEvaluatingJavaScriptFromString("document.body.innerHTML")

stringByEvaluatingJavaScriptFromString returns a optional, so you'd probably want to later use an if let statement:

if let page = html {
    // Do stuff with the now unwrapped "page" string
}
Community
  • 1
  • 1
Andrew
  • 15,357
  • 6
  • 66
  • 101
  • Okay, I did get the HTML code using the translated swift code, but after I submitted a form in the web view, I tried to use the same code to get the HTML code. It still displays the same HTML code from the previous page. Do you know what the problem might be? I also tried webView.reload(), but it still didn't change – JavaMaMocha Nov 17 '15 at 02:22
  • As long as you waited until the page [completely loaded](http://stackoverflow.com/a/15916853/2446155) before calling the function, and you are using the same web view, it should work. – Andrew Nov 17 '15 at 02:23
0

swift 4:

if let html = self.webView.stringByEvaluatingJavaScript(from: "document.body.innerHTML"){

}
ingconti
  • 10,876
  • 3
  • 61
  • 48
0

Don't forgot get the html when the page render finished, if you got html too early, the result will be empty.

func webViewDidFinishLoad(webView: UIWebView) {
     print("pageDidFinished")
     if let html = webView.stringByEvaluatingJavaScriptFromString("document.documentElement.outerHTML") {
             print("html=[\(html)]")
      }

}
Chris Ho
  • 295
  • 4
  • 13