Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebView Javascript cross domain from a local HTML file

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?

like image 406
oriharel Avatar asked Dec 27 '11 19:12

oriharel


People also ask

How do I open an HTML file in WebView?

The WebView method to load our file takes a URI , so we need to access the HTML file using that URI . Since we stored it in the assets folder, we can access it using file:///android_asset/{file_name} .

Which method is used to load HTML content in WebView?

The loadUrl() and loadData() methods of Android WebView class are used to load and display web page.

Can WebView run JavaScript?

WebView is a special component in Android which serves as kind of built-in browser inside Android applications. If you want to execute HTML, CSS or JavaScript code in your Android app, or you need to allow users visit a URL without leaving your application, WebView is the way to go.


1 Answers

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).

like image 66
Stepan Vrany Avatar answered Sep 28 '22 03:09

Stepan Vrany