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