Android WebView throws “cross origin requests are only supported for http” exception while trying to load resource from disk

androidwebview

i have developed a single page game in html/js and am trying to host it inside an android webview. i have a folder src/main/assets/www/ and this line of code to bootstrap my app:

mWebView.loadUrl("file:///android_asset/www/index.html");

the index.html loads a app.js file which is my game. when i try to make an xhr request from within app.js to get assets/myimage.svg (physical location src/main/assets/www/assets/myimage.svg) :

var xhr = new XMLHttpRequest();
        xhr.open('get', 'assets/myimage.svg', true);
        xhr.send();

I get this error: cross origin requests are only supported for http. why is this a cross-origin request? what can i do to fix this? i cannot host the svg on a http webserver and cannot inline it in app.js – it has to be loaded from disk.

Best Solution

Not sure but you can try these steps and see if it helps:

a) Initialize your WebView:

b) get WebView settings:

WebSettings settings = _webView.getSettings();

c) set following settings:

settings.setAllowFileAccessFromFileURLs(true);
settings.setAllowUniversalAccessFromFileURLs(true);

d) now you can load your your html file by standard way:

mWebView.loadUrl("file:///android_asset/www/index.html");

e) Don't forget to add the internet permission in your manifest file:

<uses-permission android:name="android.permission.INTERNET"/>
Related Question