[英]Load HTML in WebView with local css and js
I am displaying a webview with a remote html content get as a string from a remote server.我正在显示一个带有远程 html 内容的 web 视图,该内容从远程服务器获取为字符串。 I store the html locally for a no connection use of my application.我将 html 存储在本地,以便我的应用程序无连接使用。
Moreover I also store a .js script and a .css style file locally.此外,我还在本地存储了一个 .js 脚本和一个 .css 样式文件。 These files can be updated by the server.这些文件可以由服务器更新。
I store all these files at the following paths :我将所有这些文件存储在以下路径中:
context.getFilesDir()+"content.css"
context.getFilesDir()+"content.js"
In the html string, css and js are referenced like this :在 html 字符串中,css 和 js 是这样引用的:
<link rel="stylesheet" href="/content.css" type="text/css" media="screen">
<script src="/content.js"></script>
I load the html using我使用加载 html
this.webView.loadDataWithBaseURL(getFilesDir().getAbsolutePath(), html, "text/html", "utf-8", "about:blank");
But the style and the js are not taken into account, so I think something is wrong with the path I use to reference them, or to load the webView.但是没有考虑样式和js,所以我认为我用来引用它们或加载webView的路径有问题。 So what is the way to do this ?那么有什么方法可以做到这一点? I found many answers that use the "assets" folder but I do not want to use it since I have to update the css and the js from the server.我找到了许多使用“assets”文件夹的答案,但我不想使用它,因为我必须从服务器更新 css 和 js。
Finally I have found the solution :最后我找到了解决方案:
The css (or js) file is saved in local using this method :使用此方法将 css(或 js)文件保存在本地:
public static void writeToFile(Context context, String content, String title) throws IOException {
OutputStreamWriter osw = new OutputStreamWriter(context.openFileOutput(title,Context.MODE_WORLD_READABLE)); osw.write(content); osw.close(); }
Then I refer it in the html file using然后我在 html 文件中引用它
<link rel="stylesheet" href="content.css" type="text/css" media="screen">
<script src="content.js"></script>
And finally I have opened the webview using :最后我使用以下方法打开了 webview:
this.webView = (WebView) findViewById(R.id.webview); this.webView.getSettings().setJavaScriptEnabled(true); this.webView.getSettings().setPluginsEnabled(true); this.webView.setHorizontalScrollBarEnabled(false); this.webView.setVerticalScrollBarEnabled(true); this.webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); this.webView.setWebViewClient(this.controller.getWebViewClient()); String basePath = "file://"+getFilesDir().getAbsolutePath()+"/"; this.webView.loadDataWithBaseURL(basePath, data, "text/html", "utf-8", "about:blank");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.