Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle Webview click event in Android Java

I'm using WebView in my Android app. I want to run Push Notification when users click on a button. Can anyone help me to provide java code to handle the onClick button of WebView.

like image 372
Sabir Syed Avatar asked Sep 03 '26 11:09

Sabir Syed


1 Answers

You can achieve this in Android by using JavascriptInterface

Create class in your Activity, Name it as JavaScriptInterface class. create method
onButtonClick() inside the class

public class JavaScriptInterface {
        Context mContext;

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


        @JavascriptInterface
        public void onButtonClick() {
           // Handle your code

        }

    }

Add this class reference to WebView like below.

 webview.addJavascriptInterface(new JavaScriptInterface(this), "Android");

And in your WebPage you have to call onButtonClick() method in WebPage Button click

Below is code

<html>
    <body>
    <a onClick="onButtonClick()"> Click me, i am JS Button </a>
    </body>
</html>

This will call your Activity onButtonClick() method.

Hope this will help for more clarification you check this link

like image 113
Sukhbir Avatar answered Sep 05 '26 00:09

Sukhbir