20

I was trying to detect the HTML button click of webview into java code(In activity). I wrote my code after rferencing Detect click on HTML button through javascript in Android WebView but is not working.

My code:

index.html

<html>
    <head>
        <script language="javascript">
            function js1() {
                document.loginform.method="post";
                document.loginform.action = "https://example.com/chechlogin.asp";
            }
        </script>  
    </head>
    <body>
        <form name="loginform">
            <input type="text" name="empcode" value="58686" /><br/>
            <input type="password" name="emppassNTL" />
            <input type="submit" name="submit" id="submit_id" onclick="login.performClick();" />    
        </form>
    </body>
</html>

MainActivity.java

package com.example.webview;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity {

   private EditText field;
   private WebView browser;

   @Override        
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      field = (EditText)findViewById(R.id.urlField);
      browser = (WebView)findViewById(R.id.webView1);
      browser.getSettings().setJavaScriptEnabled(true);
      browser.setWebViewClient(new MyBrowser());
      browser.loadUrl("file:///android_asset/index.html");
   }


   @SuppressLint("JavascriptInterface")
   public void open(View view){
      String url = field.getText().toString();
      browser.getSettings().setLoadsImagesAutomatically(true);
      browser.getSettings().setJavaScriptEnabled(true);
      browser.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
      browser.loadUrl(url);
      browser.addJavascriptInterface(new Object()
      {
          @JavascriptInterface
        public void performClick()
        {
            Log.d("LOGIN::", "Clicked");
             Toast.makeText(MainActivity.this, "Login clicked", Toast.LENGTH_LONG).show();
        }
      }, "login");

   }
   private class MyBrowser extends WebViewClient {
      @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url) {
         view.loadUrl(url);
         return true;
      }
   }

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }

}  

But the performClick() method is not being called.

How can I correct this error?

3
  • Code from AndroidManifest <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" android:maxSdkVersion="19"/> <uses-permission android:name="android.permission.INTERNET"/> Commented Jan 4, 2014 at 5:17
  • refer this stackoverflow.com/questions/4065312/… Commented Jan 4, 2014 at 5:18
  • @Hardik I have also given the same link above and referred the same but not workking....Please have a look at my code Commented Jan 4, 2014 at 5:21

5 Answers 5

9

This is how i implemented:

public class FirstActivity extends Activity {

WebView mWebView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_first);

    mWebView = (WebView) findViewById(R.id.webView1);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setDomStorageEnabled(true);
    mWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
    mWebView.loadUrl("file:///android_asset/html/File1.html");
}

public class WebAppInterface {

    Context mContext;

    /** Instantiate the interface and set the context */
    WebAppInterface(Context c) {
        mContext = c;
    }

    /** Show a toast from the web page */
    @JavascriptInterface
    public void nextScreen(String pro_cat_id) {

            startActivity(new Intent(mContext,
         MainActivity.class));
    }

And, in html file:

javascript: file3.js

function saveId(_id)
{
    localStorage.setItem("id", _id);
    Android.nextScreen(_id);
}

HTML:

<html>
    <head>
        <script type="text/javascript" src="arel/js/File3.js"></script>
    </head>
    <body>
        <button onClick="saveId('1');">1</button>
        <button onClick="saveId('2');">2</button>
    </body>
</html>
Sign up to request clarification or add additional context in comments.

Comments

6

try to repalce this

 browser.addJavascriptInterface(new Object()
      {
          @JavascriptInterface
        public void performClick()
        {
            Log.d("LOGIN::", "Clicked");
             Toast.makeText(MainActivity.this, "Login clicked", Toast.LENGTH_LONG).show();
        }
      }, "login");

to this

Button btnLogin=new Button(ctx);
btnLogin.setOnClickListener(this);

browser.addJavascriptInterface(btnLogin,"login");

@Override
public void onClick(View v) {

        //do Something

}

and in index.html

<html>  <head>  <script language="javascript">  function js1() {
    document.loginform.method="post";  document.loginform.action = "https://example.com/chechlogin.asp";
           }
     </script>  </head>  <body>    <form name="loginform">
     <input type="text" name="empcode" value="58686" /><br/>
     <input type="password" name="emppassNTL" />
     <input type="submit" name="submit" id="submit_id" onclick="btnLogin.performClick();" />

More info here: https://developer.android.com/guide/webapps/webview.html#BindingJavaScript

3 Comments

what is btnLogin in html file ?? please explain.
@AnujSharma "btnLogin" is Button class variable. When you want to perform click via code you have to call "performClick()" method. see here developer.android.com/reference/android/view/…
What is ctx while creating button
3

You need to create and pass a JavaScript interface from Android to JavaScript. You can then use this interface as a bridge to pass function calls with arguments.

More details and examples here: http://developer.android.com/guide/webapps/webview.html#BindingJavaScript

Comments

2

Ooops!!!
performClick() method was at wrong place.
MainActivity.java should be something like this :

package com.example.webview;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity {

   private WebView browser;

   @Override        
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      browser = (WebView)findViewById(R.id.webView1);
      browser.getSettings().setJavaScriptEnabled(true);
      browser.getSettings().setLoadsImagesAutomatically(true);
      browser.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
      browser.setWebViewClient(new MyBrowser());
      browser.loadUrl("file:///android_asset/index.html");
   }


   private class MyBrowser extends WebViewClient {
      @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url) {
          view.loadUrl(url); 
          view.addJavascriptInterface(new Object()
          {
              @JavascriptInterface
            public void performClick() throws Exception
            {
                Log.d("LOGIN::", "Clicked");
                 Toast.makeText(MainActivity.this, "Login clicked", Toast.LENGTH_LONG).show();
            }
          }, "login");
         return true;
      }
   }

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }

}

Comments

0

Web code:

HTML Code :

 <button class="btn btn-success w-md waves-effect waves-light" id="btnsubmit" type="button" tabindex="3" onclick="getValues();ok.performClick(this.value);"> @Utility.GetDisplayName(Utility.ResourceKey.lblClicktoApp)</button>

Jquery :

var model = {
            "_id": nationalid,//if need to send as argument
            "btnId":"btnsubmit"
        };
        function getValues() {
            document.getElementById("btnsubmit").value = _id

        }
        document.getElementById("btnsubmit").addEventListener("click", function () {
            webkit.messageHandlers.callbackHandler.postMessage(model);
        });

Android:

 act_webview_WebView.addJavascriptInterface(MyJavaScriptInterface(mContext),"ok")

            act_webview_WebView!!.webViewClient = object : WebViewClient() {


                override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                    view?.loadUrl(url)

                    return true
                }

                override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                    super.onPageStarted(view, url, favicon)
                    try {
                        webview_progressBar.visibility = View.VISIBLE
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }

                override fun onPageFinished(view: WebView?, url: String?) {
                    super.onPageFinished(view, url)
                    try {
                        webview_progressBar.visibility = View.GONE
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }

                }

                override fun onReceivedError(
                    view: WebView?,
                    request: WebResourceRequest?,
                    error: WebResourceError?
                ) {
                    super.onReceivedError(view, request, error)

                    try {
                        webview_progressBar.visibility = View.GONE
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
            act_webview_WebView!!.loadUrl(URL)

act_webview_WebView.addJavascriptInterface(new Object() { @JavascriptInterface public void performClick() { Log.d("LOGIN::", "Clicked"); Toast.makeText(MainActivity.this, "Login clicked", Toast.LENGTH_LONG).show(); } }, "login");

Proguard :

# For webview
#Start
#-keep class * extends android.webkit.WebChromeClient { *; }
#-dontwarn im.delight.android.webview.*
-keep class android.support.v8.renderscript.** { *; }
-keepclassmembers class apppackage.WebviewFragments {
   public *;
}
-dontwarn
-keepattributes Signature
-keepattributes SetJavaScriptEnabled
-keepattributes JavascriptInterface
-keepattributes InlinedApi
-keepattributes SourceFile,LineNumberTable
-keepattributes *Annotation*

-keepclassmembers class * {
    @android.webkit.JavascriptInterface <methods>;
}

-keepclassmembers class * {
    @android.webkit.JavascriptInterface <methods>;
}

-keepclassmembers class **.*$MyJavaScriptInterface {
    *;
}
-keepclassmembers class **.*$JavaScriptInterface {
    *;
}

-keep public class **.*$MyJavaScriptInterface
-keep public class **.*$JavaScriptInterface
#END

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.