kotlin安卓在Jetpack Compose 框架下使用webview , 网页中的JavaScript代码如何与native交互
"SetJavaScriptEnabled") ( fun ComposableWebView( url: String, modifier: Modifier = Modifier, onWebViewReady: (WebView) -> Unit = {} ) { val context = LocalContext.current Box(modifier) { val webView = remember { WebView(context) } webView.settings.javaScriptEnabled = true webView.settings.setCacheMode(LOAD_DEFAULT) val deviceId = getAndroidId(context) ?: "" val checkSum = getTodayCheckSum(deviceId) setCookie( context, url, mutableMapOf( "deviceId4Zhibo" to deviceId, "checkSum4Zhibo" to checkSum ) ) Log.i("xudong debug", "开始注入接口 Android") // 添加 JavaScript 接口 webView.addJavascriptInterface( WebAppInterface(context), "Android" ) Log.i("xudong debug", "完成注入接口 Android") webView.webViewClient = object : WebViewClient() { override fun onPageFinished(view: WebView?, url: String?) { super.onPageFinished(view, url) // WebView 加载完成后的回调 onWebViewReady(webView) } } // 加载URL Log.i("xudong debug", "加载url: $url") webView.loadUrl(url) // 将 WebView 嵌入到 Compose 中 AndroidView({ webView }) } } // JavaScript 接口类 class WebAppInterface(private val context: Context) { fun playAudio(message: String) { Toast.makeText(context, "playAudio: $message", Toast.LENGTH_SHORT).show() } fun stopAudio() { Toast.makeText(context, "stopAudio", Toast.LENGTH_SHORT).show() } }