Skip to content
Star

Using it in Kotlin

The Android runtime is written in Kotlin. It receives messages from WebView, runs request/command handlers, and emits events to the web app. TypeScript is used only to analyze the contract and generate Kotlin code.

Install

During pre-release development, include this repository as a Gradle composite build.

kotlin
// settings.gradle.kts
includeBuild("../webview-bridge-kit") {
    dependencySubstitution {
        substitute(module("io.github.kimyounghee425:webview-bridge-kit"))
            .using(project(":webview-bridge-kit-android"))
    }
}
kotlin
// app/build.gradle.kts
dependencies {
    implementation("io.github.kimyounghee425:webview-bridge-kit:0.2.0")
}

The module also defines a Maven publication. Once published to a release repository, consumers can use the io.github.kimyounghee425:webview-bridge-kit:<version> coordinate.

Generate Kotlin code from the project containing the contract and add it to an Android source set.

bash
npx webview-bridge-kit-gen \
  --contract ./bridge-contract.ts \
  --lang kotlin \
  --package com.example.bridge \
  --out ./android/app/src/main/java/com/example/bridge/BridgeTypes.kt

Wire Android WebView

kotlin
import androidx.lifecycle.lifecycleScope
import com.example.bridge.*
import dev.webviewbridgekit.AndroidWebViewTransport
import dev.webviewbridgekit.NativeBridge

class AppBridgeHandlers : BridgeHandlers {
    override suspend fun kakaoLogin() =
        KakaoLoginResponse(accessToken = login(), expiresIn = null, nickname = null)

    override suspend fun sendLogs(payload: SendLogsPayload) {
        logger.write(payload.lines)
    }

    override suspend fun openCamera() {
        // Navigate to the camera.
    }
}

webView.settings.javaScriptEnabled = true
val transport = AndroidWebViewTransport(webView)
val bridge = NativeBridge(transport, lifecycleScope)
bridge.bind(AppBridgeHandlers())

bridge.emitPhotoTaken(photoPayload)

Call bridge.close() when the owning screen is destroyed. The default web transport automatically detects window.WebViewBridgeKit. If you choose another interface name, pass a custom web Transport.

Errors

  • An unregistered request returns an UNKNOWN_MESSAGE response.
  • Payload deserialization failure returns VALIDATION_FAILED.
  • BridgeHandlerException preserves its custom code and message.
  • Other handler failures return HANDLER_ERROR.

Load trusted content only

addJavascriptInterface exposes native functionality to JavaScript. Only load app-controlled HTTPS origins or bundled content, and do not navigate the same WebView to arbitrary external pages.