compose-webview-multiplatform icon indicating copy to clipboard operation
compose-webview-multiplatform copied to clipboard

Bug: Bridge doesn't work

Open EnvOut opened this issue 3 months ago • 1 comments

versions: agp = "8.11.2" android-compileSdk = "36" android-minSdk = "24" android-targetSdk = "36" androidx-activity = "1.11.0" androidx-appcompat = "1.7.1" androidx-core = "1.17.0" androidx-espresso = "3.7.0" androidx-lifecycle = "2.9.4" androidx-testExt = "1.3.0" composeHotReload = "1.0.0-beta07" composeMultiplatform = "1.9.0" kotlin = "2.2.20" kotlinx-coroutines = "1.10.2" io.github.kevinnzou:compose-webview-multiplatform:2.0.3

Target: ios simulator

I have MessageHandler:

class VotingAttemptsReachedHandler : IJsMessageHandler {
    private val log: Logger = Logger.withTag("VotingAttemptsReachedHandler")

    override fun methodName(): String {
        return "VotingAttemptsReachedHandler"
    }

    override fun handle(
        message: JsMessage,
        navigator: WebViewNavigator?,
        callback: (String) -> Unit,
    ) {
        log.e {
            "VotingAttemptsReachedHandler: $message"
        }
        println("VotingAttemptsReachedHandler executed with result: $message")
//        val param = processParams<String>(message)
//        val data = GreetModel("KMP Received ${param.message}")
        // callback(dataToJsonString(data))
        callback("OK")
    }
}

Launched effect:

    val webViewState = rememberWebViewState("https://mysite.com")
    val webViewNavigator = rememberWebViewNavigator()
    val webViewJsBridge = rememberWebViewJsBridge(webViewNavigator)

    LaunchedEffect(webViewJsBridge) {
        webViewJsBridge.register(VotingAttemptsReachedHandler())

webView:

            WebView(
                state = webViewState,
                navigator = webViewNavigator,
                webViewJsBridge = webViewJsBridge,
                modifier = Modifier.fillMaxSize(),
                factory = { param ->
                    webViewConfig(sessionAutomationStore.sessionIdentifier, param)
                }
            )

and js code that send message into channel:

window.kmpJsBridge.callNative("VotingAttemptsReachedHandler","null", null);

But I haven't any message from the js code (should by "VotingAttemptsReachedHandler executed with result: $message")

How to solve it?

EnvOut avatar Sep 23 '25 06:09 EnvOut

I was having this issue in Desktop target, found a workaround dispatching the event "kmpJsBridgeReady" manually after loading the page

LaunchedEffect(state.loadingState, state.lastLoadedUrl) {
    if (state.loadingState is LoadingState.Finished && state.lastLoadedUrl.isNullOrEmpty().not()) {
        bridge.webView?.evaluateJavaScript(
            "window.dispatchEvent(new Event('kmpJsBridgeReady'));"
        )
    }
}

WebView(
    webViewJsBridge = bridge,
    ...
)

poncho10101 avatar Oct 29 '25 18:10 poncho10101