How to detect click on HTML button through javascript in Android WebView using Kotlin?

This example demonstrates how to detect click on HTML buttons through javascript in Android WebView using Kotlin.This example demonstrates how to detect click on HTML buttons through javascript in Android WebView using Kotlin.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.



   
   

Step 3 − Create an asset folder and create a file.htm and add the following code −


First name: 
Last name:

Step 4 − Add the following code to src/MainActivity.kt

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
   }
   @SuppressLint("JavascriptInterface")
   fun loadPage(view: View) {
      val browser = WebView(this)
      browser.settings.javaScriptEnabled = true
      browser.loadUrl("file:///android_asset/page.html")
      setContentView(browser)
      val ws = browser.settings
      ws.javaScriptEnabled = true
      browser.addJavascriptInterface(object:Any() {
         @JavascriptInterface // For API 17+
         fun performClick(string:String) {
            Toast.makeText(this@MainActivity, string, Toast.LENGTH_SHORT).show()
         }
      }, "ok")
   }
}

Step 5 − Add the following code to androidManifest.xml



   
      
         
            
            
         
      
   

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run iconPlay from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.

Updated on: 2020-11-30T06:56:01+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements