37

I load local html file on IOS WKWebview using loadFileURL: allowingReadAccessToURL.. But when I send ajax request, it fails.

The error is:

Origin null is not allowed by Access-Control-Allow-Origin.

Can I set some properties to fix this error, like in Android,we can use setAllowUniversalAccessFromFileURLs?

skrrgwasme
  • 9,358
  • 11
  • 54
  • 84
Haoru Zhan
  • 381
  • 3
  • 4

5 Answers5

6

Have you tried setting it like this?

let config = WKWebViewConfiguration()
config.setValue(true, forKey: "allowUniversalAccessFromFileURLs")
cmilhench
  • 666
  • 5
  • 17
2

When HTML is loaded locally (file URL) with WkWebView below configuration setting to WkWebView worked for me

WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
WKUserContentController *userContentController = [[WKUserContentController alloc] init];

[theConfiguration.preferences setValue:@"TRUE" forKey:@"allowFileAccessFromFileURLs"];
[theConfiguration setValue:@"TRUE" forKey:@"allowUniversalAccessFromFileURLs"];

When you set above setting, origin will be passed as "file://" instead of null

Girish Adiga
  • 308
  • 3
  • 11
  • This makes the app crash for me with the error "this class is not key value coding-compliant for the key allowUniversalAccessFromFileURLs". – Tomáš Hübelbauer May 16 '22 at 17:29
  • Found a solution to "this class is not key value coding-compliant for the key allowUniversalAccessFromFileURLs", see my comment on https://stackoverflow.com/a/46127440/2715716. – Tomáš Hübelbauer May 16 '22 at 17:41
0

Try using loadRequest instead of loadFileURL. It worked for me :

NSString* path = [[NSBundle mainBundle] pathForResource:@"pageName" ofType:@"html"];
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
[self.webView loadRequest:request];

After that, my query worked fine while I had a 'Cannot make any requests from null' error before.

Matt Lacey
  • 8,227
  • 35
  • 58
CedricSoubrie
  • 6,657
  • 2
  • 39
  • 44
0

if you want to reading from localhtml file, you have to set allowReadAccess

let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let documentsURL = URL(fileURLWithPath: documentsPath, isDirectory: true)
let finalURL = URL(string: htmlurl)
webview.loadFileURL(finalURL!, allowingReadAccessTo: documentsURL)
Hun
  • 3,652
  • 35
  • 72
Janibyek
  • 21
  • 4
0

On Chrome, CORS requests won't work from localhost dispite proper CORS headers, just saying.. keep banging my head on that one

Pedro Rodrigues
  • 2,520
  • 2
  • 27
  • 26