Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to load local html file on API Level 30

My app load local html file that located under getFilesDir() via WebView#loadUrl().
Before targetSdkVersion = 29, below code is working.

        copyAssetsFile(this, "sample.html", getFilesDir().getAbsolutePath());
        webView.getSettings().setJavaScriptEnabled(true);
        String url = "file://" + getFilesDir().getAbsolutePath() + "/sample.html";
        webView.loadUrl(url);
    }

    private static void copyAssetsFile(Context context, String fileName, String directoryPath) {
        try {
            InputStream inputStream = context.getResources().getAssets().open(fileName);
            FileOutputStream fileOutputStream = new FileOutputStream(
                    new File(directoryPath, fileName), false);
            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(buffer)) >= 0) {
                fileOutputStream.write(buffer, 0, length);
            }

            fileOutputStream.close();
            inputStream.close();

Full example is here.

However, it's not working after change targetSdkVersion = 30.

  • WebView respond net::ERR_ACCESS_DINIED
  • Could load local html if it's located android_asset

How to load local html file on targetSdkVersion = 30?
Is it changed to be denied by Android FW??

like image 652
JchanKchan Avatar asked Jul 28 '20 07:07

JchanKchan


2 Answers

WebSettings#setAllowFileAccess() is default to false when your app is targeting R and above for security reasons, note that you need to set the API level 30. https://developer.android.com/reference/android/webkit/WebSettings#setAllowFileAccess(boolean)

like image 68
user14039297 Avatar answered Nov 13 '22 07:11

user14039297


Try setting webview.getSettings().setAllowFileAccess(true);

like image 43
Sunil Kumar Avatar answered Nov 13 '22 09:11

Sunil Kumar