0

How can I run an XMLHttpRequest from within a WKWebView that I have created in Swift?

Currently, I use the WKWebView to access a page on a server I own. This page contains my Javascript. However, when I attempt to make an XMLHttpRequest by using WKWebView.evaluateJavaScript (i.e. call a javascript function that makes an XMLHttpRequest) the Javascript code executes successfully but the Safari debugger shows "Failed to load resource".

However, if I 'manually' make an XMLHttpRequest by using the console in the Safari debugger and then call my request function from my app, it works fine - but only once!

I'm at a bit of a loss as to why this is...


As mentioned in the comments, a better solution than bundling the Javascript with my swift library is to host the scripts on a page that is accessed via the WKWebView. Previous information maintained below;

Some background: I have been tasked with producing a Swift library that wraps our current Javascript API. I had hoped to use a WKWebView to simply load and execute our existing javascript code, however any XMLHttpRequests that I run simply return error (fire the onerror callback) instantly. The error object returned to onerror is {"position":0,"totalSize":0}

This thread seems to suggest that my WKWebView needs a 'parent' in order to execute javascript correctly. I have attempted to reproduce their code in Swift, but to no effect (see below)

let webConf = WKWebViewConfiguration()
WKWebView webView = WKWebView(frame: CGRectZero, configuration: webConf)
UIApplication.sharedApplication().keyWindow?.addSubview(webView)

In order to get to this point, I have had to set 'App Transport Security Settings -> Allow Arbitrary Loads' to 'YES' in my info.plist file, in order to enable non-https requests.

Community
  • 1
  • 1
DAVco
  • 325
  • 2
  • 3
  • 10
  • 1
    That wrapper seems like a very bad idea. You should either publish JS code to an internal webserver or translate it total to Swift. Using a `WKWebView` for it is inappropriate and overkill too. Read up on the [`JavascriptCore`](http://nshipster.com/javascriptcore/) framework – Code Different Jun 28 '16 at 17:35
  • Thanks @CodeDifferent. We've reached a similar conclusion here; rather than bundling our Javascript with our Swift library, we host an API page containing our scripts that is accessed via the WKWebView. – DAVco Jun 29 '16 at 09:19

0 Answers0