How to invoke Webview button clickevent in Android?

90 views Asked by At

I am developing an android app with a web app loading on WebView. I want to invoke the web app button actions. I have implemented some changes on webpage to invoke native methods as shown below.

mWebview.addJavascriptInterface(new Object() {

        @JavascriptInterface // For API 17+
        public void callNativeHome() {

            Log.d("btnsetup", "btnsetup");

      

        }
    }, "btnsetup");

But now I can't make any changes on web end as it's not my web screen. How I can access the button click events by ID or class name?

1

There are 1 answers

0
Rumit Patel On

Web access is mandatory to Bind JavaScript code to Android code.

Android:

val webView: WebView = findViewById(R.id.webview)
webView.addJavascriptInterface(WebAppInterface(this), "Android")

Web:

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />

<script type="text/javascript">
    function showAndroidToast(toast) {
        Android.showToast(toast);
    }
</script>

You can simply follow Bind JavaScript code to Android code.


Another workaround is to find the navigation URL. You can check/compare the redirection URL called after clicking that button.

For more information, you can check Handle page navigation in webview.