这个问题在这里并不新鲜,但在我出错的地方仍然无法得到它。我只是想评估一些javascript。
我的简单代码如下:
WebView wv = new WebView(context);
WebSettings settings = wv.getSettings();
settings.setJavaScriptEnabled(true);
JavaBridgeToJS bridgeToJS = new JavaBridgeToJS();
wv.addJavascriptInterface(bridgeToJS, "javaCallback");
String src = "javascript: var result= 3 + 3; window.javaCallback.resultOfAdd(result)";
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
Log.d(TAG, "Newer than JellyBean.");
ValueCallback<String> result = new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
Log.d(TAG, "Got in onReceiveValue: " + value);
}
};
wv.evaluateJavascript(src, result);
}else {
Log.d(TAG, "Older than Kitkat");
wv.loadUrl(src);
}
和
public class JavaBridgeToJS {
@JavascriptInterface
public void resultOfAdd(String result) {
Log.d(TAG, "Here is: " + result);
}
}
适用于API 19 + ,即使没有 if 并且检查版本(我的意思是它适用于loadUrl以及evaluateJavascript)
但是当我尝试 API 18 时,不会调用java中的回调。 我环顾四周(remove line break或quotes missing(可能已感染,在手机上观看),等等......)
到目前为止,我没有运气。有什么想法吗?
修改
好吧,我已经添加了处理JS内部错误的代码,以防我错过了什么。
wv.setWebChromeClient(new CustomWebChromeClient());
作为
public class CustomWebChromeClient extends WebChromeClient {
private CustomWebChromeClient() {
super();
}
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
UILog.d(TAG, consoleMessage.message());
return super.onConsoleMessage(consoleMessage);
}
}
我很惊讶:
E/dalvikvm: Could not find class 'android.webkit.PermissionRequest', referenced from method com.example.WebViewDoll$CustomWebChromeClient.access$super
VFY: unable to resolve check-cast 1896 (Landroid/webkit/PermissionRequest;) in Lcom/example/WebViewDoll$CustomWebChromeClient;
E/dalvikvm: Could not find class 'android.webkit.WebChromeClient$FileChooserParams', referenced from method com.example.WebViewDoll$CustomWebChromeClient.access$super
VFY: unable to resolve check-cast 1899 (Landroid/webkit/WebChromeClient$FileChooserParams;) in Lcom/example/WebViewDoll$CustomWebChromeClient;
E/dalvikvm: Could not find class 'android.webkit.PermissionRequest', referenced from method com.example.WebViewDoll$CustomWebChromeClient.access$super
D/WebViewDoll: Uncaught TypeError: Cannot call method 'resultOfAdd' of undefined
E/Web Console: Uncaught TypeError: Cannot call method 'resultOfAdd' of undefined at null:1
答案 0 :(得分:0)
我没有找到答案,为什么这不起作用,但在using js in webview的帮助下,我能够做出解决方法......
我必须将我的js注入一个html页面。所以我的包装器arround js看起来像:
String src = "<html><head><script type=\"text/javascript\">" +
"function myFunction()" +
"{" +
" javaCallback.resultOfAdd(3+3);" +
"}" +
"</script></head><body onload=\"myFunction()\"/>" +
"</html>";
而不是wv.loadUrl我用过:
wv.loadData(src, "text/html", "UTF-8");
此组合具有所需的相同结果。