使用JavaScript文件访问Android资产文件夹

3

我正在向WebView注入一个javascript文件,该javascript文件需要从应用程序的资产文件夹中加载更多文件。 我以前是从远程服务器加载文件,但现在我需要本地加载它们。 我得到了“不允许加载本地资源”的错误。 这是否可能?我无法在此处或使用谷歌找到任何解决方案。 示例:

...
webView.loadUrl("javascript:(function() {" +
                    "var parent = document.getElementsByTagName('head').item(0);" +
                    "var script = document.createElement('script');" +
                    "script.type = 'text/javascript';" +
                    "script.innerHTML = window.atob('" + encoded + "');" +
                    "parent.appendChild(script)" +
                    "})()");

这会将一个名为"script.js"的文件注入到Webview中。 在script.js文件中,我想要注入位于应用程序资产文件夹中的CSS背景图像。当尝试访问“file:///android_asset”时,会出现“不允许加载本地资源”的错误。

1个回答

1

如果您想将本地HTML页面和资源加载到Web视图中,应使用webView.loadDataWithBaseURL。

  public void loadLocalHtmlToWebView() throws IOException {

        WebView mWebView = findViewById(R.id.my_webview);

        File publicDir = new File(getCacheDir(), "public");

        if (publicDir.exists() == false) {

            publicDir.mkdirs();

            String[] ls = getAssets().list("public");


            for (int i = 0; i < ls.length; i++) {

                InputStream inputStream = getAssets().open("public/" + ls[i]);

                File outFileLocation = new File(publicDir, ls[i]);

                outFileLocation.createNewFile();

                Log.e("AMIR", "Wrinting to : " + outFileLocation.getPath());

                FileOutputStream fileOutputStream = new FileOutputStream(outFileLocation);

                byte[] buffer = new byte[1024];

                while (inputStream.read(buffer) != -1) {

                    fileOutputStream.write(buffer);

                }

                fileOutputStream.flush();
                fileOutputStream.close();

                inputStream.close();


            }

        }


        String indexHtml="";

        BufferedReader bufferedReader=new BufferedReader(new FileReader(new File(publicDir,"index.html")));

        String ln="";

        while((ln=bufferedReader.readLine())!=null){

            indexHtml+=ln;

        }

        bufferedReader.close();

        Log.e("AMIR","Html : "+indexHtml);


        String baseUrl = "file://" + publicDir.getPath() + "/";

        mWebView.loadDataWithBaseURL(baseUrl, indexHtml, "text/html", "UTF-8", null);

    }

资产文件夹:

Assets folder

我的 index.html 代码:

<html>

<head>

<title>Hello</title>

<head>

<body>
Hello
<img src="./img.jpg"/>

<body>

</html>

这是一篇关于WebView的好而且解释得很清楚的教程:

http://tutorials.jenkov.com/android/android-web-apps-using-android-webview.html


谢谢你的帮助,但是我无法使用你的解决方案使我的示例工作。 - izik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接