添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
webView.evaluateJavascript(script, new ValueCallback<String>() {
   	@Override
   	public void onReceiveValue(String value) {
       		/* Action to perform on callback */

Prerequisite :

To achieve JavaScript output, enable javascript to WebView. To do that,

webView.getSettings().setJavaScriptEnabled(true);

Points to consider

  • Apply JavaScript after finishing the loading of the Web URL. Using WebViewClient class, you can get more control of the Web Page by receiving various callbacks like onPageStarted(), onPageFinished() etc.
  • JavaScript can be applied always on UI thread so best practice to use evaluateJavascript() is inside WebViewClient class’s onPageFinished() method which indicates that page loading is finished and you can apply your JavaScript code on the UI of WebPage.

How to Use evaluateJavascript?

  1. In Activity class, initialize WebView and enable Javascript to WebView:
WebView webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl("https://www.42gears.com/");
  1. Create WebViewClient class and set it to WebView using webView.setWebViewClient()
private class MyWebViewClient extends WebViewClient {
   @Override
   public void onPageFinished(WebView view, String url) {
       super.onPageFinished(view, url);
String script = "(function() { return 'JavaScript executed successfully.'; })();";
view.evaluateJavascript(script, new ValueCallback<String>() {
           @Override
           public void onReceiveValue(String value) {
Log.d("output", value); 
//prints:"JavaScript executed successfully."

In addition, if you want to perform any action on a callback response of JavaScript, you can decode callback response values in JSON Format as callback values will always be in JSON format. That can be a JSON array, JSON value, JSON object.
Below code will be executed and give same output without any error :

view.evaluateJavascript(script, new ValueCallback<String>() {
   @Override
   public void onReceiveValue(String value) {
JsonReader jsonReader = new JsonReader(new StringReader(value));
       jsonReader.setLenient(true);
       try {
if(jsonReader.peek() != JsonToken.NULL && jsonReader.peek()==JsonToken.STRING) {
               String msg = jsonReader.nextString();
               if(msg != null) {
                   Log.d("output", msg);
//prints:"JavaScript executed successfully."
           jsonReader.close();
       } catch (IOException e) {
Log.e("Exception", "evaluateJavascript IOException : ", e);
		

Leave A Comment Cancel reply

Your email address will not be published.