Compose WebView Part 6 | Bind JavaScript code to Android code

When developing a web application that's designed specifically for the WebView in your Android app, you can create interfaces between your JavaScript code and client-side Android code. For example, your JavaScript code can call a method in your Android code to display a Dialog, instead of using JavaScript's alert() function.

To bind a new interface between your JavaScript and Android code, call addJavascriptInterface(), passing it a class instance to bind to your JavaScript and an interface name that your JavaScript can call to access the class.

For example, you can include the following class in your Android app:

/** Instantiate the interface and set the context  */
class WebAppInterface(private val mContext: Context) {

    /** Show a toast from the web page  */
    @JavascriptInterface
    fun showToast(toast: String) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show()
    }
}

..

You can bind this class to the JavaScript that runs in your WebView with addJavascriptInterface() and name the interface Android. For example:

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

..

This creates an interface called Android for JavaScript running in the WebView. At this point, your web application has access to the WebAppInterface class. For example, here's some HTML and JavaScript that creates a toast message using the new interface when the user clicks a button:

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

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

..

Here is our complete code:

MainActivity.kt

package com.blogspot.boltuix

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.ViewGroup
import android.webkit.JavascriptInterface
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.viewinterop.AndroidView


class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            WebViewPage("https://www.boltuix.com/")
        }
    }
}

@SuppressLint("SetJavaScriptEnabled")
@Composable
fun WebViewPage(url: String){
    val infoDialog = remember { mutableStateOf(false) }

    AndroidView(factory = {
        WebView(it).apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
            webViewClient = WebViewClient()

            // to play video on a web view
            settings.javaScriptEnabled = true

            // Bind JavaScript code to Android code
            addJavascriptInterface(WebAppInterface(context,infoDialog), "Android")

            loadUrl(url)


        }
    }, update = {
        it.loadUrl(url)
    })


    if (infoDialog.value) {
        InfoDialog(
            title = "TEKHEIST",
            desc = "We are at the forefront of innovation.\n" +
                    "Discover with us the possibilities of your next project.",
            onDismiss = {
                infoDialog.value = false
            }
        )
    }
}

/** Instantiate the interface and set the context  */
class WebAppInterface(private val mContext: Context, var infoDialog: MutableState<Boolean>) {

    /** Show a toast from the web page  */
    @JavascriptInterface
    fun showToast(toast: String) {
        infoDialog.value=true
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show()
    }
}

..

Here is our HTML & JS code in website 

Website / index.html

<img src="https://www.tekheist.com/assets/img/favicon30f4.png" onclick="showAndroidToast('Hello Android!')"  />

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

..

GET full source code on Github:

https://github.com/BoltUIX/Compose-Web-View


..

Comments