I'm facing an issue with the WebView in my Android Compose application. While the WebView works perfectly on iOS, in the browser, and with Flutter WebView on both Android and iOS, certain websites break and become unresponsive when using the WebView with Compose and Kotlin.
Here's the code I'm using:
@SuppressLint("SetJavaScriptEnabled")
@Composable
internal fun WebView(downloadListener: SDKDownloadListener, modifier: Modifier = Modifier) {
var showSplash by remember { mutableStateOf(true) }
Box(modifier = modifier) {
AndroidView(
factory = { context ->
WebView(context).apply {
// Clear various caches and preferences
clearCache(true)
// Configure WebView settings
settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
databaseEnabled = true
allowContentAccess = true
allowFileAccess = true
}
// Set WebView properties
webViewClient = WebViewClient()
webChromeClient = WebChromeClient()
// Set download listener
setDownloadListener(downloadListener)
// Add JavaScript interface
addJavascriptInterface(EventListenerJavascriptInterface(), JAVASCRIPT_INTERFACE)
// Load URL with POST data
postUrl("https://post.dev", body)
}
},
modifier = Modifier.matchParentSize(),
)
// Splash screen with animation
AnimatedVisibility(
visible = showSplash,
exit = slideOutVertically(targetOffsetY = { it }) + fadeOut(),
modifier = Modifier.matchParentSize()
) {
SplashView(onButtonPress = { showSplash = false })
}
}
}
Tried:
Despite these efforts, certain websites still break and are unresponsive. Has anyone encountered a similar issue or can provide insights into what might be going wrong? Any help would be appreciated!
Additional Information: The same websites work fine on iOS and in the browser. Flutter WebView works perfectly on both Android and iOS with the same websites.
Yep, had the same issue, couldn't load local js files. The solution is to wrap it with a FrameLayout
val myWebView = remember {
WebView(context).apply{
//your settings here
}
}
AndroidView(factory = {
FrameLayout(it).apply {
if (myWebView.parent != null) {
(myWebView.parent as ViewGroup).removeView(myWebView)
}
addView(myWebView)
}
}, modifier = Modifier.fillMaxSize())