WebView in Compose: JavaScript Bridge & Cookie Management
WebView integration in Compose lets you embed web content while maintaining native app control. JavaScript bridges enable communication between Kotlin and JavaScript.
Basic WebView in Compose
@Composable
fun WebViewScreen() {
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = { context ->
WebView(context).apply {
settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
}
loadUrl("https://example.com")
}
}
)
}
JavaScript Bridge Setup
class WebInterface(private val context: Context) {
@JavascriptInterface
fun showToast(message: String) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
@JavascriptInterface
fun getDeviceInfo() = "Android ${Build.VERSION.RELEASE}"
}
// Add bridge to WebView
webView.addJavascriptInterface(WebInterface(context), "NativeApp")
JavaScript Calling Native Code
In your HTML/JavaScript:
// JavaScript can call native methods
document.getElementById("button").onclick = () => {
NativeApp.showToast("Button clicked from JS!");
const info = NativeApp.getDeviceInfo();
console.log(info);
}
Cookie Management
@Composable
fun WebViewWithCookies() {
val cookieManager = CookieManager.getInstance()
cookieManager.setAcceptCookie(true)
cookieManager.setAcceptThirdPartyCookies(webView, true)
AndroidView(
factory = { context ->
WebView(context).apply {
loadUrl("https://example.com")
}
}
)
}
Secure WebView Configuration
webView.settings.apply {
javaScriptCanOpenWindowsAutomatically = false
mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
allowFileAccess = false
allowContentAccess = false
}
WebView bridges create seamless native-web integration. Always validate JavaScript input and restrict bridge access to safe operations.
8 Android app templates available on Gumroad
Top comments (0)