Get JSON text from WKWebView

Viewed 3437

I want to get the contents of http://www.devpowerapi.com/fingerprint from a WKWebView

evaluateJavaScript("document.documentElement.innerHTML") returns <head></head><body></body> instead of the actual JSON

Is it possible to get the contents with a WKWebView?

2 Answers

Simplest way to do this (works for this specific case):

webView.evaluateJavaScript("document.getElementsByTagName('pre')[0].innerHTML", completionHandler: { (res, error) in
     if let fingerprint = res {
          // Fingerprint will be a string of JSON. Parse here...
          print(fingerprint)
     }
})

Possibly better way to do this:

So .innerHTML returns HTML, not a JSON header. JSON headers are notoriously difficult to grab with WKWebView, but you could try this method for that. First set:

webView.navigationDelegate = self

And then in the WKNavigationDelegate method:

public func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
    let res = navigationResponse.response as! HTTPURLResponse
    let header = res.allHeaderFields
    print(header)
}

I wouldn't say this is the correct solution but it is a solution none, the less. The request will be made in the context of the webView.

webView.evaluateJavaScript("""
var Httpreq = new XMLHttpRequest(); // a new request
Httpreq.open("GET",'http://www.devpowerapi.com/fingerprint',false);
Httpreq.send(null);
Httpreq.responseText;
""",
    completionHandler: {
       (innerHTML, error) in
       print(innerHTML, error)
})

I'm sure you could use any of the JavaScript solutions from this thread.

Related