Android WebView从Java调用JavaScript函数

时间:2018-01-12 23:49:17

标签: javascript java android webview

我试图在WebView内从Java调用JavaScript函数。

爪哇:

webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/html/chart.html");
webView.evaluateJavascript("draw();", null);

HTML文件:

<html>
<head>
    Hello World!
</head>

<body>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
function draw(){
    google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

  function drawChart() {

    // Create the data table.
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Topping');
    data.addColumn('number', 'Slices');
    data.addRows([
      ['Mushrooms', 3],
      ['Onions', 1],
      ['Olives', 1],
      ['Zucchini', 1],
      ['Pepperoni', 2]
    ]);

    // Set chart options
    var options = {'title':'How Much Pizza I Ate Last Night',
                   'width':400,
                   'height':300};

    // Instantiate and draw our chart, passing in some options.
    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }
}
</script>
<div id="chart_div"></div>
</body>
</html>

我在网络浏览器中尝试过HTML文件。它工作正常。首先显示Hello World,在从控制台调用draw()后,会显示图表。

0 个答案:

没有答案