i used below code for add webview from Androidview in Compose, becuase i need to add js interface to it.
`
@SuppressLint("SetJavaScriptEnabled")
@Composable
private fun Webview(screenVM: MainScreenVM = hiltViewModel()) {
if (screenVM.showWebview.value) {
AndroidView(factory = {
val wv = WebView(it)
wv.apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
webViewClient = object : WebViewClientCompat() {
override fun onReceivedHttpError(
view: WebView,
request: WebResourceRequest,
errorResponse: WebResourceResponse
) {
super.onReceivedHttpError(view, request, errorResponse)
screenVM.showWebview.value = false
}
override fun onReceivedError(
view: WebView,
request: WebResourceRequest,
error: WebResourceErrorCompat
) {
super.onReceivedError(view, request, error)
screenVM.showWebview.value = false
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
}
}
settings.javaScriptEnabled = true
settings.allowContentAccess = true
settings.allowFileAccess = true
addJavascriptInterface(MyJavaScriptInterface(context, wv), "AndroidFunction")
loadUrl(URLS.SUPPORT_SHORTCUT_PAGE)
}
}, update = {
it.loadUrl(URLS.SUPPORT_SHORTCUT_PAGE)
})
}
`
but when load webview, screen blank for a second and later show webview. 1- i can add js interface to
accompanist-webview
?
2- else, why screen blank for a secon when load webview in compose?
Firslty, Yes you can add js interface in accompanist Webview onCreate lambda.
WebView(
modifier = Modifier.fillMaxSize(),
state = state
onCreated = {
it.settings.javaScriptEnabled = true
**it.addJavascriptInterface()**
},
client = webClient,
navigator = navigator,
)
I think the WebView is loading resources, which causes the screen to appear white for a while. Although it might not be the most ideal solution, I fixed it by placing the showLoading call in shouldOverrideUrlLoading and the hideLoading call in onPageFinished.
internal class MyWebClient(
private val showLoadingCircle: () -> Unit,
private val hideLoadingCircle: () -> Unit,
) : AccompanistWebViewClient() {
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
hideLoadingCircle()
}
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
showLoadingCircle()
return super.shouldOverrideUrlLoading(view, request)
}
}