Android 在 WebView 中调用 JavaScript 函数 [英] Android Calling JavaScript functions in WebView
问题描述
我正在尝试调用一些 javascript 函数,这些函数位于在 android webview 中运行的 html 页面中.下面的代码尝试执行的操作非常简单 - 从 android 应用程序中,调用带有测试消息的 javascript 函数,该函数又调用回通过 toast 显示测试消息的 android 应用程序中的 java 函数.
I am trying to call some javascript functions sitting in an html page running inside an android webview. Pretty simple what the code tries to do below - from the android app, call a javascript function with a test message, which inturn calls a java function back in the android app that displays test message via toast.
javascript 函数如下所示:
The javascript function looks like:
function testEcho(message){
window.JSInterface.doEchoTest(message);
}
从 WebView,我尝试通过以下方式调用 javascript,但没有成功:
From the WebView, I have tried calling the javascript the following ways with no luck:
myWebView.loadUrl("javascript:testEcho(Hello World!)");
mWebView.loadUrl("javascript:(function () { " + "testEcho(Hello World!);" + "})()");
我确实在 WebView 上启用了 javascript
I did enable javascript on the WebView
myWebView.getSettings().setJavaScriptEnabled(true);
// register class containing methods to be exposed to JavaScript
myWebView.addJavascriptInterface(myJSInterface, "JSInterface");
这里是 Java 类
public class JSInterface{
private WebView mAppView;
public JSInterface (WebView appView) {
this.mAppView = appView;
}
public void doEchoTest(String echo){
Toast toast = Toast.makeText(mAppView.getContext(), echo, Toast.LENGTH_SHORT);
toast.show();
}
}
我花了很多时间在谷歌上搜索,看看我可能做错了什么.我发现的所有示例都使用这种方法.有人看到这里有什么问题吗?
I've spent a lot of time googling around to see what I may be doing wrong. All examples I have found use this approach. Does anyone see something wrong here?
还有其他几个外部 javascript 文件被引用 &在 html 中使用,它们可能是问题吗?
There are several other external javascript files being referenced & used in the html, could they be the issue?
推荐答案
我发现了问题所在:testEcho() 参数中缺少引号.这就是我接到工作电话的方式:
I figured out what the issue was : missing quotes in the testEcho() parameter. This is how I got the call to work:
myWebView.loadUrl("javascript:testEcho('Hello World!')");
这篇关于Android 在 WebView 中调用 JavaScript 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!