cordova-plugin-file: Accessing cdvfile:// from http://[network-url] in ajax throws CORS policy error on Android

While developing I run my app on an Android device. The app is served from a network url using cordova-plugin-webpack LiveReload (HMR) feature.

I’ve successfully implemented a download mechanism of JSON files and Audio files. I can embed the downloaded audio file using cdvfile protocol (obtained through .toInternalURL) but I can not get the JSON files using Ajax requests because of this error:

Access to XMLHttpRequest at ‘cdvfile://localhost/files/test/data.json’ from origin ‘http://10.123.123.123:8080’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, https.

Recap:

  • I can access APIs on the web via ajax.
  • I can download files using XHR and store them on the device.
  • I can embed the downloaded files through src=‘cdvfile://’
  • I can’t ajax ‘cdvfile://’

I have <access origin="*" /> and also tried <access origin="cdvfile://*" /> in config.xml I have <allow-navigation href="cdvfile:*" /> CSP is set as follow:

default-src * cdvfile: data: blob: ws: wss: gap://ready file: http: https: ‘unsafe-eval’; media-src * cdvfile:; style-src * ‘unsafe-inline’; script-src * cdvfile: ‘unsafe-inline’ ‘unsafe-eval’; connect-src * ws: wss:;"

Any help would be appreciated

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Comments: 16 (4 by maintainers)

Most upvoted comments

It appaers the “cdvfile://” protocol causes a lot of trouble.
Related issues: Issue #295 > PR #296 + PR #322 Issue #329 Issue #347 Issue #349

It seems like a solution similar to the one proposed in pull request #296, might also work for this situation.

@Lindsay-Needs-Sleep thanks! My project evolved, and now I need real XHR support to load not only json files but also binary content and possibly chunks of data (mainly encoded audio files).

Android I solved it using a slightly different version of PR #322 (i used the url format proposed in #296). It seems to work smoothly even if my www folder is on a remote host. I haven’t tested it yet in prod mode (www folder under file://) but I’m pretty confident it will work.

iOS I’m using cordova-plugin-wkwebview-engine but at the moment I have no access to xCode so I just have a few possible roads in mind:

  • try cordova-plugin-wkwebview-file-xhr that sounds pretty interesting
  • try WKURLSchemeHandler / setURLSchemeHandler approach as you suggested in your PR (targeting iOS >= 11)

everything started from your precious links to PR and Issues dealing with this. Thanks! The cordova-plugin-ionic-webview also sounds as a feasible plan B.