将数据传递到 android webView 中的本地 html 文件

Passing data to local html file in android webView

我在尝试将数据传递到我的 html 文件时遇到了一些困难。我的 html 文件位于资产文件夹内的项目根目录下。简而言之,我在 webView 中显示我的 html 文件。

这是我的 mainActivity.kt 的一部分,用于填充我的 webView

mWebView = findViewById(R.id.activity_main_webview);
val webSettings = mWebView.settings
webSettings.javaScriptEnabled = true
mWebView.loadUrl("file:///android_asset/googlechart.html");

这是我的 googlechart.html 的一部分,它存储在本地资产文件夹中

var dataRow = [["mushroom", 1], ["fish", 3]]
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows(dataRow);

我想将数据从 mainActivity.kt 传递到我的 googlechart.html,根据 Passing data from java class to Web View html 的回答,它没有解释如何将数据传递到 html 文件它存储在项目根目录中。我怎样才能做到这一点?

感谢任何帮助或见解。

简单的解决方案

  1. loadUrl()
  2. 时使用查询
  3. script
  4. 中获得document.location.href
  5. 处理您的数据
    • 解码字符串、拆分等

例子

如果数据是json

android

val json = JsonObject().apply {
    addProperty("age","28")
    addProperty("name","john")
    addProperty("contents","test")
}
val url = "file:///android_asset/test.html?$json"
binding.webView.loadUrl(url)

本地.html

<!DOCTYPE html>
<html>

<body>
    <H1>test</H1>
    <oi id="list">
    </oi>
    <script type="text/javascript">
        function makeList() {
            const getOiTag = document.getElementById("list");

            const decodeUrl = decodeURI(document.location.href);
            const jsonStr = decodeUrl.split("?")[1];
            const json = JSON.parse(jsonStr);

            for(i in json){
                const li = document.createElement("li")
                li.textContent = i + " : " + json[i];
                getOiTag.appendChild(li);
            }
        }
        makeList()

    </script>
</body>

</html>