我们如何执行 javascript 函数并在我们的 android 应用程序中获取返回值?
我们想在按钮按下事件上执行一个javascript,我们需要将参数传递给脚本并获取返回值,所以我们使用“WebChromeClient”来实现这个,但是我们得到的异常是“SyntaxError: Parse error at undefined:1 "
以下是我的代码
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;
}
}
}