WebView Javascript cross domain from a local HTML file

40,196

Solution 1

Today morning I found solution that seems to be working.

The Java part

Initialize your WebView:

WebView _webView = (WebView) this.findViewById(R.id.id_of_your_webview_in_layout);

get WebView settings:

WebSettings settings = _webView.getSettings();

set following settings:

settings.setJavaScriptEnabled(true);
settings.setAllowFileAccessFromFileURLs(true); //Maybe you don't need this rule
settings.setAllowUniversalAccessFromFileURLs(true);

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

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

The Javascript part

Create XHR request by standard way

var xhr = new XMLHttpRequest();
xhr.open("get", "http://google.com", false);
xhr.send();

Print the result somewhere

document.body.innerHTML = xhr.responseText

NOTICE: This procedure works only on API level 16 or higher (At least the documentation says that).

Solution 2

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

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

Also make sure you are using JSONP requests (don't forget the &callback=? as stated above)

Solution 3

I load a local html file (from assets folder) to the app WebView

Note that you failed to say how you are doing this. I am going to guess that it was by a loadUrl() on a file:///android_asset URL.

Is there a way to allow the WebView in Android to load data from remote server on a local loaded HTML file?

Try using loadDataWithBaseURL() to load the content, supplying a URL on the remote server as the base URL.

Share:
40,196
oriharel
Author by

oriharel

I'm an Android developer currently working for Pageonce (www.pageonce.com). Also have web development skills (Javascript and HTMLS) and desktop development (Winforms). www.twitter.com/oriharel

Updated on September 23, 2020

Comments

  • oriharel
    oriharel over 3 years

    I load a local html file (from assets folder) to the app WebView. In the HTML I run a jQuery.getJSON(url). the url is a remote server.

    This action fails, and I'm guessing because of a different origin issue (cross domain). I run the same file on chrome and there it specifically says so.

    Is there a way to allow the WebView in Android to load data from remote server on a local loaded HTML file?