引用本地HTML文件中的本地JS和CSS文件

时间:2015-04-16 11:15:04

标签: android webview

让我们看看这个例子:Loading existing .html file with android WebView 我加载了我的HTML文件,但它包含对其他本地 css和js文件的引用。我是否需要在HTML文件中使用相同的文件:/// URL?

2 个答案:

答案 0 :(得分:0)

不,你的结构应该是这样的:

/assets/html/index.html

/assets/scripts/index.js

/assets/css/index.css

然后做(Android WebView: handling orientation changes

    //in onCreate() for Activity, or in onCreateView() for Fragment
    if(WebViewStateHolder.INSTANCE.getBundle() == null) { //this works only on single instance of webview, use a map with TAG if you need more
        webView.loadUrl("file:///android_asset/html/index.html");
    } else {
        webView.restoreState(WebViewStateHolder.INSTANCE.getBundle());
    }

确保添加

    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
    }

然后只使用网址

<html>
<head>
    <meta charset="utf-8">
    <title>Zzzz</title>
    <script src="../scripts/index.js"></script>
    <link rel="stylesheet" type="text/css" href="../css/index.css">

编辑:

只有在添加我链接的代码

时,该特定代码才有效
public class WebViewFragment extends Fragment { //could be activity
    private enum WebViewStateHolder
    {
        INSTANCE;

        private Bundle bundle;

        public void saveWebViewState(WebView webView)
        {
            bundle = new Bundle();
            webView.saveState(bundle);
        }

        public Bundle getBundle()
        {
            return bundle;
        }
    }

    @Override
    public void onPause()
    {
        WebViewStateHolder.INSTANCE.saveWebViewState(myWebView);
        super.onPause();
    }

至于任何&#34;安全问题&#34;你说的是,你没有分享足够的数据。

答案 1 :(得分:0)

根据Rendering HTML in a WebView with custom CSS,您不必指定每个CSS或JS。将它们包含在HTML文件中。