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 :

     <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>

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

<script language="javascript">

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


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);
refuse = new Button(ctx);

Then I added javascript to my WebView :

// Enablejavascript
WebSettings ws = wv.getSettings();
// 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 :

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

Leave a Comment