Loading javascript functions to webview in Android Kitkat

☆樱花仙子☆ 提交于 2020-01-03 03:23:06

问题


I am having problems with loading javascript functions, which are in external file, into webview in Android Kitkat. My approach for earlier versions was that i implemented my own webview client and in method onPageFinisned i called

mWebView.loadUrl("javascript:" + functions);

later, when i wanted to call some js method, i call same code, like

mWebView.loadUrl("javascript:" + someFunction);

In android kitkat there is new method evaluateJavascript, which replaces my code with calling that javascript functions. My problem is that now this and old approach throw this error:

Uncaught ReferenceError: function is not defined

It seems that problem is in loading that javascript functions to webview but i dont know how to load it other way. Thanks


回答1:


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.



来源:https://stackoverflow.com/questions/21207748/loading-javascript-functions-to-webview-in-android-kitkat

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