使用 Jetpack Compose 时,如何使用 Webview 实现 javascript 接口?

How to implement javascript interface with Webview, when using Jetpack Compose?

如何在使用 Jetpack Compose 时实现 WebAppInterface(javascript webview 接口)?

我正在关注 this documentation

这是我到目前为止的进展,但未调用 showToast()。将 @Composable 添加到 showToast() 没有帮助。

/** 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()
    }
}

@SuppressLint("SetJavaScriptEnabled")
@Composable
fun WebPageScreen(urlToRender: String) {
    AndroidView(factory = {
        WebView(it).apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
            webViewClient = WebViewClient()
            addJavascriptInterface(WebAppInterface(getContext()), "Android")
            loadUrl(urlToRender)
        }
    }, update = {
        it.loadUrl(urlToRender)
    })
}

HTML/JS 来自 Android 文档的代码:

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

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

您在参考文档中错过了一个步骤:

WebView(context).apply {
    layoutParams = ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.MATCH_PARENT
    )
    webViewClient = WebViewClient()
    settings.javaScriptEnabled = true // <-- This line
    addJavascriptInterface(WebAppInterface(getContext()), "Android")
}