2

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?

twodayslate
  • 2,803
  • 3
  • 27
  • 43

2 Answers2

5

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)
}
jake
  • 1,226
  • 8
  • 14
  • I get the following error when doing the first solution: `Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=TypeError: undefined is not an object (evaluating 'document.getElementsByTagName('pre')[0].innerHTML'), WKJavaScriptExceptionColumnNumber=40, WKJavaScriptExceptionSourceURL=about:blank, NSLocalizedDescription=A JavaScript exception occurred}` – twodayslate Jun 19 '19 at 00:07
  • 1
    Ah, evaludateJavaScript should be called in `webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)` – twodayslate Jun 19 '19 at 00:22
0

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.

twodayslate
  • 2,803
  • 3
  • 27
  • 43