The local web page in WebView failed to load with XMLHttpRequest

Problem description

When using WebView to display local web pages, if developers use XMLHttpRequest to load additional local files, the following error messages will appear on some mobile phones:

Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///asset/content.txt'

Cause of the problem

The reason for this error is that Android, based on security considerations, has prohibited local web pages in WebView from using XMLHttpRequest to read local files since Android version 4.1. As a result, “phones before Android 4.1” can use XMLHttpRequest normally, while “phones after Android 4.1” cannot use XMLHttpRequest normally.

Solution

Use the “allowfileaccessfromfileurls” method provided by WebView to restart the function of XMLHttpRequest to read files. Subsequent local web pages executed in WebView can normally use XMLHttpRequest to read local file contents.

// WebSettings
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
   settings.setAllowFileAccessFromFileURLs(true);
}


Read More: