使用javascript文件访问android资源文件夹

时间:2018-04-19 07:51:52

标签: javascript java android android-studio webview

我正在向WebView注入一个javascript文件,而javascript文件需要从app assets文件夹中加载更多文件。 我曾经从远程服务器加载文件,但现在我需要在本地加载它们。 我得到“不允许加载本地资源”。 这有可能吗?我在这里找不到任何解决方案或使用谷歌。 例如:

...
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文件中,我想注入位于app资源文件夹内的css背景图像。当我试图访问“file:/// android_asset”时,我得到“不允许加载本地资源”错误。

1 个答案:

答案 0 :(得分:0)

如果要将本地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

相关问题