How to implement the WebAppInterface
(javascript interface for webview) when using Jetpack Compose?
I'm following this documentation
This is how far I've got so far, but showToast()
is not called. Adding @Composable
to showToast()
didn't help.
/** 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 code from Android docs:
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
CodePudding user response:
You missed one step in the documentation you refer to:
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")
}