Home Android WebView call JavaScript function from Java
Reply: 0

Android WebView call JavaScript function from Java

user1625
1#
user1625 Published in April 26, 2018, 5:27 pm

I am trying to call a JavaScript function from Java inside an WebView.

Java:

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

HTML file:

<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>

I have tried the HTML file in a web browser. It worked fine. First only Hello World is displayed, after calling draw() from the console the chart appears.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.314836 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO