androidandroid-studiowebviewandroid-jetpack-composesavestate

How to Save and Restore WebView State in Android Jetpack Compose?


I was previously saving my WebView state in my Android app by overriding onSaveInstanceState(outState: Bundle) method inside the Activity class like this:

override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
    webView.saveState(outState)
}

Now, I am migrating my app to use Jetpack Compose, and I am wondering how I can achieve the same functionality to save and restore the WebView state.


Solution

  • Save and restore the WebView state in Jetpack Compose could be done by using the rememberSaveable state to keep the Bundle and leveraging the AndroidView composable. Below is a complete example showing how to achieve this:

    @Composable
    fun WebViewScreen(
        startUrl: String,
        modifier: Modifier = Modifier,
    ) {
        val bundle: Bundle = rememberSaveable { bundleOf() }
    
        AndroidView(
            factory = { context ->
                WebView(context)
            },
            modifier = modifier,
            onRelease = { webView ->
                webView.saveState(bundle)
            },
            update = { webView ->
                if (bundle.isEmpty) {
                    webView.loadUrl(startUrl)
                } else {
                    webView.restoreState(bundle)
                }
            }
        )
    
    }