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

Reference to local JS and CSS files inside local HTML file

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

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

/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);
    }

然后只需使用 urls

<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();
    }

至于你说的 "security issue",你没有分享足够的数据。

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