Loading javascript functions to webview in Android Kitkat

北城余情 提交于 2019-12-08 23:31:26

What works for me is to have the JavaScript functions inside a Web page, in <script> tags:

<html>
<head>
<title>Android GeoWebTwo Demo</title>
<script language="javascript">
    function whereami(lat, lon) {
        document.getElementById("lat").innerHTML=lat;
        document.getElementById("lon").innerHTML=lon;
    }

    function pull() {
        var location=JSON.parse(locater.getLocation());

        whereami(location.lat, location.lon);
    }
</script>
</head>
<body>
<p>
You are at: <br/> <span id="lat">(unknown)</span> latitude and <br/>
<span id="lon">(unknown)</span> longitude.
</p>
<p><a onClick="pull()">Update Location</a></p>
</body>
</html>

Then, I can successfully use evaluateJavascript():

public void onLocationChanged(Location location) {
  StringBuilder buf=new StringBuilder("whereami(");

  buf.append(String.valueOf(location.getLatitude()));
  buf.append(",");
  buf.append(String.valueOf(location.getLongitude()));
  buf.append(")");

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    browser.evaluateJavascript(buf.toString(), null);
  }
  else {
    browser.loadUrl("javascript:" + buf.toString());
  }
}

(both code snippets are from this sample app)

This works on old and new versions of Android. Now, in my case, my JavaScript happens to be messing with the DOM, so I needed a Web page anyway. Yours might have an empty <body>, with the Web page just there to supply the JavaScript functions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!