I have a WKWebView
in my project which does some operations, after clicking submit inWKWebView
it displays JSON data in javaScript that I need to pars in my code.
Asked
Active
Viewed 3,546 times
3

Azza
- 33
- 2
- 7
-
Possible duplicate of [Swift Retrieve HTML data from Webview](https://stackoverflow.com/questions/33747752/swift-retrieve-html-data-from-webview) – Kuldeep Jan 17 '19 at 12:38
-
@Kuldeep, did you check with OP if he is using `UIWebView` or `WKWebView`? – vikingosegundo Jan 17 '19 at 12:43
4 Answers
2
Swift 5.1 examples:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("redirect didFinish")
print(webView)
webView.evaluateJavaScript("document.documentElement.outerHTML.toString()",
completionHandler: { (html: Any?, error: Error?) in
print(html as Any)
})
}

ikbal
- 1,110
- 12
- 21
1
You can get the HTML data in the form of string using this piece of code
in Objective C
NSString *html = [yourWebView stringByEvaluatingJavaScriptFromString: @"document.body.innerHTML"];
in Swift
let yourWebView = UIWebView();
let html : String = yourWebView.stringByEvaluatingJavaScript(from: "document.body.innerHTML") ?? "";
You have to analyze, what you have received, and do later process accordingly.
In your case, you might get the full json in the string.

Talha Ahmad Khan
- 3,416
- 5
- 23
- 38
1
You can get source code of your UIWebView
page.
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
webView.evaluateJavaScript("document.getElementsByTagName('html')[0].innerHTML") { innerHTML, error in
print(innerHTML!)
}
}

Emre
- 186
- 6
-
this worked with me ,,,, func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { do{ let content = try String(contentsOf: webView.url!) if let data = content.data(using: String.Encoding.utf8) { let obj = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] } catch{ } } – Azza Jan 19 '19 at 11:56
1
your JSON comes in body tag then use this code or change from web side to give JSON in body tag
if let html = webView.stringByEvaluatingJavaScript(from: "document.body.innerHTML"){
let data = html.data(using: .utf8)!
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? Dictionary<String,Any>
{
print(jsonArray) // use the json here
} else {
print("bad json")
}
} catch let error as NSError {
print(error)
}
}

Sagar Bhut
- 657
- 6
- 28