[英]Android webview, loading javascript file in assets folder
[英]Access android assets folder using javascript file
我正在向WebView注入一個javascript文件,並且該javascript文件需要從應用資產文件夾中加載更多文件。 我曾經從遠程服務器加載文件,但是現在我需要在本地加載它們。 我得到“不允許加載本地資源”。 這有可能嗎? 我在這里或使用Google找不到任何解決方案。 例:
...
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”時,出現“不允許加載本地資源”錯誤。
如果要將本地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);
}
資產文件夾:
我的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.