Modern Android WebView & JavascriptInterface Two-Way Bridge

Many enterprise applications combine high-performance native screens with web-powered content — such as rich checkout flows, interactive dashboards, terms of service, and existing React/Vue widgets. Android WebView provides an embedded Chromium browser engine inside your application, accompanied by a powerful two-way JavaScript Bridge.

Android WebView and Trusted Web Activities Bridge

Figure 35.1: Web to Native Integration — Option A: Embedded WebView with JavascriptInterface Bridge; Option B: Fullscreen Trusted Web Activity (TWA).

Two-Way Bridge Architecture

  • JavaScript to Android (Native Invocation): The webpage's JavaScript calls window.AndroidBridge.someMethod(), invoking a Kotlin method annotated with @JavascriptInterface.
  • Android to JavaScript (DOM Mutation): Kotlin code executes webView.evaluateJavascript("myJsFunction(data)", callback) to trigger web functions or inject data directly into the DOM.

Complete Kotlin & HTML/JS Bridge Implementation

1. The Kotlin Android Bridge Class

import android.content.Context
import android.webkit.JavascriptInterface
import android.widget.Toast
import android.os.Vibrator
import android.os.VibrationEffect
import android.os.Build

class WebAppInterface(private val context: Context) {

    // Must annotate with @JavascriptInterface for security!
    @JavascriptInterface
    fun showToast(toastMessage: String) {
        Toast.makeText(context, toastMessage, Toast.LENGTH_SHORT).show()
    }

    @JavascriptInterface
    fun triggerHapticFeedback() {
        val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            vibrator.vibrate(VibrationEffect.createOneShot(50, VibrationEffect.DEFAULT_AMPLITUDE))
        } else {
            vibrator.vibrate(50)
        }
    }

    @JavascriptInterface
    fun getAppVersion(): String {
        return "2026.1.0-PROD"
    }
}

2. Configuring WebView Safely in Jetpack Compose

import android.webkit.WebView
import android.webkit.WebViewClient
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import androidx.compose.runtime.Composable
import androidx.compose.ui.viewinterop.AndroidView

@Composable
fun HybridWebScreen(url: String) {
    AndroidView(
        factory = { context ->
            WebView(context).apply {
                settings.apply {
                    javaScriptEnabled = true // Enable JS
                    domStorageEnabled = true  // Enable localStorage
                    databaseEnabled = true
                    // Security best practices:
                    allowFileAccess = false
                    allowContentAccess = false
                }

                webViewClient = object : WebViewClient() {
                    override fun onPageFinished(view: WebView?, url: String?) {
                        super.onPageFinished(view, url)
                        // Example: Call web JavaScript function from Kotlin
                        view?.evaluateJavascript("window.updateTheme('dark')", null)
                    }
                }

                webChromeClient = WebChromeClient()

                // Expose the bridge interface to window.AndroidBridge
                addJavascriptInterface(WebAppInterface(context), "AndroidBridge")

                loadUrl(url)
            }
        }
    )
}

3. Client-Side Web HTML/JavaScript Code

<!DOCTYPE html>
<html>
<head>
    <title>Veewom Hybrid Web Portal</title>
</head>
<body>
    <h2>Web to Native Integration</h2>
    <button onclick="callNative()">Vibrate Device from Web!</button>

    <script>
        function callNative() {
            // Verify bridge is present before calling
            if (window.AndroidBridge) {
                window.AndroidBridge.triggerHapticFeedback();
                window.AndroidBridge.showToast("Triggered directly from Web JavaScript!");
            } else {
                console.log("Not running inside Android native WebView.");
            }
        }

        // Called from Kotlin onPageFinished:
        window.updateTheme = function(mode) {
            document.body.style.backgroundColor = (mode === 'dark') ? '#04121F' : '#FFFFFF';
        };
    </script>
</body>
</html>

Critical WebView Security Best Practices

Never add a @JavascriptInterface to a WebView that loads untrusted, third-party public web URLs! Malicious third-party scripts could invoke your native methods to access user hardware or execute arbitrary code. Only attach bridge interfaces to local trusted HTML assets or verified HTTPS domains you control.

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. Why is allowFileAccess set to false in modern WebViews?

Setting `allowFileAccess = true` allows JavaScript within the WebView to access private local files inside your app's `/data/data//` sandbox via `file://` URLs, potentially exposing private SQLite databases and credentials to Cross-Site Scripting (XSS) attacks.

Q2. What is the difference between WebViewClient and WebChromeClient?

`WebViewClient` handles page navigation, URL overrides, SSL certificate errors, and page loading events. `WebChromeClient` handles browser-level UI events such as JavaScript alert dialogs, file upload pickers, video fullscreen mode, and webpage title changes.

Q3. Can I inspect and debug WebView JavaScript using Chrome DevTools on a PC?

Yes! In your Application class, call `WebView.setWebContentsDebuggingEnabled(true)`. Then connect your device via USB, open Google Chrome on your PC, navigate to `chrome://inspect`, and you can use full Chrome DevTools to inspect DOM elements, debug console logs, and inspect network traffic.

Explore Related Android Development Classes & Next Steps

Broaden your foundational and advanced Android application development skills across our curriculum:

Trusted Web Activities (TWA)

Compare embedded WebView bridge with full-screen TWA PWA packaging.

Deep Linking & Verified App Links

Intercept web URLs and redirect them to native app screens.

Passkeys & Biometric Security

Bridge WebAuthn passkey requests between web views and native biometric prompt.

WebView Security Best Practices

Prevent cross-site scripting (XSS) and disable file access in WebView.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!