Detect click on HTML button through javascript in Android WebView

I finally got it on my own after some reading. Kind of hard when you know nothing about javascript and when the doc is quite thin on the subject.
Here is my solution, hope this will help others :

With an HTML page containing 2 buttons at the end like that :

<div>
     <button type="button" id="ok" style="font-weight: 700; margin-right: 20px;" onclick="validClick();">J'accepte</button>
     <button type="button" id="no" onclick="refuseClick();">Je refuse</button>
</div>

I send the event of the click to the javascript at the top of my HTML page :

<script language="javascript">

   function validClick()
   {
      valid.performClick();
      document.getElementById("ok").value = "J'accepte";
   }
   function refuseClick()
   {
      refuse.performClick();
      document.getElementById("no").value = "Je refuse";
   }

</script>

valid and refuse are 2 java objects that I passed through the javascript interface to use their methods. So in java, I created 2 buttons (not really displayed in the Activity, only here for their methods and are sort of shadows of the HTML buttons :

valid = new Button(ctx);
valid.setOnClickListener(this);
refuse = new Button(ctx);
refuse.setOnClickListener(this);

Then I added javascript to my WebView :

// Enablejavascript
WebSettings ws = wv.getSettings();
ws.setJavaScriptEnabled(true);
// Add the interface to record javascript events
wv.addJavascriptInterface(valid, "valid");
wv.addJavascriptInterface(refuse, "refuse");

And finally, handle the click events in the onClick method :

@Override
public void onClick(View v) {
    if (v.equals(valid)) {
        //do Something
    } else if (v.equals(refuse)) {
        //do Something else }
}

Hope this will help some people


In case you also want to retrieve button value.

Java:

WebSettings ws = wv.getSettings();
ws.setJavaScriptEnabled(true);
wv.addJavascriptInterface(new Object()
{
   @JavascriptInterface           // For API 17+
   public void performClick(String strl)
   {
      stringVariable = strl;
      Toast.makeText (YourActivity.this, stringVariable, Toast.LENGTH_SHORT).show();
   }
}, "ok");

HTML:

<button type="button" value="someValue" onclick="ok.performClick(this.value);">OK</button>

Here's a simpler solution. On the Java side, create a listener for each button. It doesn't need to be any particular class, since the method will be looked up using reflection:

WebSettings ws = wv.getSettings();
ws.setJavaScriptEnabled(true);
wv.addJavascriptInterface(new Object()
{
  public void performClick()
  {
    // Deal with a click on the OK button
  }
}, "ok");

Then in the HTML, call it directly from the button tag:

<button type="button" onclick="ok.performClick();">OK</button>