[英]How we can execute a javascript function and get a return value in our android application?
How we can execute a javascript function and get a return value in our android appplication ? 我们如何在我们的android应用程序中执行javascript函数并获得返回值?
We want to execute a javascript on a button press event, we need to pass parameters to the script and get return values, So we are using "WebChromeClient" to implement this, But we got Exception is "SyntaxError: Parse error at undefined:1" 我们想在按钮按下事件上执行javascript,我们需要将参数传递给脚本并获取返回值,所以我们使用“WebChromeClient”来实现它,但我们得到的异常是“SyntaxError:未定义的解析错误:1 “
Following is my code 以下是我的代码
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class FirstTab extends Activity
{
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.regis);
try{
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new MyWebChromeClient());
String customHtml = "<html><head><title>iSales</title><script type=\"text/javascript\"> function fieldsOnDelete(){ var x=123; return \"JIJO\"; } </script></head><body>hi</body></html>";
webView.loadData(customHtml, "text/html","UTF-8");
}catch(Exception e)
{
Log.v("JAC LOG",e.toString());
}
}
public void onResume()
{
super.onResume();
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
webView.loadUrl("javascript:alert(javascript:fieldsOnDelete())");
}
catch(Exception e)
{
Log.v("JAC LOG",e.toString());
}
}
});
}
final class MyWebChromeClient extends WebChromeClient {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.v("LogTag", message);
result.confirm();
return true;
}
}
}
you can use mWebView.loadUrl("javascript:checkName");
你可以使用
mWebView.loadUrl("javascript:checkName");
to call the method... 打电话给方法......
Then you can use addJavascriptInterface()
to add a Java object to the Javascript environment. 然后,您可以使用
addJavascriptInterface()
将Java对象添加到Javascript环境中。 Have your Java script call a method on that Java object to supply its "return value". 让Java脚本在该Java对象上调用一个方法来提供其“返回值”。
EDIT1: Or you can use following hack: 编辑1:或者您可以使用以下hack:
Add this Client to your WebView: 将此客户端添加到WebView:
final class MyWebChromeClient extends WebChromeClient {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.d("LogTag", message);
result.confirm();
return true;
}
}
Now in your java script call do: 现在在你的java脚本调用中执行:
webView.loadUrl("javascript:alert(functionThatReturnsSomething)");
Now in the onJsAlert call " message
" will contain the returned value. 现在在onJsAlert调用“
message
”中将包含返回的值。
Edit2: EDIT2:
So it does not work if we call javascript method just after call to load the URL since the page loads take time. 因此,如果我们在调用加载URL之后调用javascript方法,它就不起作用,因为页面加载需要时间。 So I created a test program to test that...
所以我创建了一个测试程序来测试......
Following is my html file (named test.html) store in the assets folder: 以下是我的资产文件夹中的html文件(名为test.html)商店:
<html>
<head>
<script language="javascript">
function fieldsOnDelete(message) {
alert("i am called with " + message);
window.myjava.returnValue(message + " JIJO");
}
</script>
<title>iSales android</title>
</head>
<body></body>
</html>
</body>
</html>
Following is my java class that would get that i would add to java script as interface and it would receive the return value: 以下是我的java类,我将添加到java脚本作为接口,它将收到返回值:
public class MyJS {
public void returnValue(String string){
Log.d(this.getClass().getSimpleName(), string);
}
}
And following is my activity class: 以下是我的活动课程:
public class CheckWebView extends Activity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_web_view);
webView = (WebView) findViewById(R.id.webview);
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onConsoleMessage(String message, int lineNumber,
String sourceID) {
super.onConsoleMessage(message, lineNumber, sourceID);
Log.d(this.getClass().getCanonicalName(), "message " + message
+ " :::line number " + lineNumber + " :::source id "
+ sourceID);
}
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
// TODO Auto-generated method stub
onConsoleMessage(consoleMessage.message(),
consoleMessage.lineNumber(), consoleMessage.sourceId());
Log.d(this.getClass().getCanonicalName(), "message::::: "
+ consoleMessage.message());
return super.onConsoleMessage(consoleMessage);
}
});
webView.addJavascriptInterface(new MyJS(), "myjava");
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginsEnabled(true);
webView.getSettings().setAllowFileAccess(true);
webView.loadUrl("file:///android_asset/test.html");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_check_web_view, menu);
return true;
}
/* (non-Javadoc)
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
webView.loadUrl("javascript:fieldsOnDelete('name');");
return super.onOptionsItemSelected(item);
}
}
The key here is that there should be some time interval between the call to load html file from assets folder and the call to javascript:method
. 这里的关键是在从assets文件夹加载html文件和调用
javascript:method
之间应该有一段时间间隔。 Here I am calling it from onOptionsItemSelected
and it is working fine.. if I move the webView.loadUrl("javascript:fieldsOnDelete('name');");
在这里,我从
onOptionsItemSelected
调用它,它工作正常..如果我移动webView.loadUrl("javascript:fieldsOnDelete('name');");
to the end of the onCreate() method the it shows the error that it can not find fieldsOnDelete()
method... 到onCreate()方法结束时,它显示错误,它无法找到
fieldsOnDelete()
方法...
Hope it Helps... 希望能帮助到你...
EDIT3: EDIT3:
Replace following in your code 在代码中替换以下内容
webView.loadUrl("javascript:alert(javascript:fieldsOnDelete())");
with 同
webView.loadUrl("javascript:alert(fieldsOnDelete())");
and try... 并试试......
In Android KitKat there is a new method evaluateJavascript that has a callback for a return value. 在Android KitKat中有一个新方法evaluateJavascript,它具有返回值的回调。 The callback returns a JSON value, object or array depending on what you return.
回调返回JSON值,对象或数组,具体取决于您返回的内容。
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// In KitKat+ you should use the evaluateJavascript method
mWebView.evaluateJavascript(javascript, new ValueCallback<String>() {
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onReceiveValue(String s) {
JsonReader reader = new JsonReader(new StringReader(s));
// Must set lenient to parse single values
reader.setLenient(true);
try {
if(reader.peek() != JsonToken.NULL) {
if(reader.peek() == JsonToken.STRING) {
String msg = reader.nextString();
if(msg != null) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
}
}
} catch (IOException e) {
Log.e("TAG", "MainActivity: IOException", e);
} finally {
try {
reader.close();
} catch (IOException e) {
// NOOP
}
}
}
});
}
You can see a full example here: https://github.com/GoogleChrome/chromium-webview-samples/tree/master/jsinterface-example 您可以在此处查看完整示例: https : //github.com/GoogleChrome/chromium-webview-samples/tree/master/jsinterface-example
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.