This question is asked multiple times and it has answers that used to work. Recently in documentation said, they have removed this feature for security reasons. Only some li
Setting android:configChanges="orientation|screenSize"
for Activity in Manifest for retaining the state of activity that has Webview in it, if there is no difference in layout for portrait and landscape view.
You can save Webview state as:
override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) webView.saveState(outState)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle?) { super.onRestoreInstanceState(savedInstanceState) webView.restoreState(savedInstanceState)
}
and reload only if saved state is not null like:
if (savedInstanceState == null) {
webView.loadUrl("replace_with_your_url")
}
Finally I figured out the solution. There is no way to save the state of WebView and have all of the content, so we need to prevent reloading or recreating the webView. In order to have one instance of our activity that contains webView we should add the following code to our Manifest file:
<activity ...
android:launchMode="singleInstance"
android:alwaysRetainTaskState="true">
Then if through your application you needed to recreate the instance entirely to refresh the webView, you can use finish(); if it's inside of the activity or if you are in another activity and you want to recreate your webView activity, read this link to do it.