Recently encountered a requirement, load the page with WebView, select the filter condition, jump to the new WebView page and then return, the original filter condition has been cleared due to page refresh, how to solve the return time not to reload the page, many answers on the web is to set the WebView page cache, But it still doesn’t work on some H5 pages.

Some blogs say that you can jump to a new URL every time, you can addView a webView, return to the previous webView, this method is feasible, but if you add too many webViews, return, may have problems, finally by observing the implementation method of the browser found, Jumping from urlA to urlB solves this problem by restarting a new activity and then finsh the current activity directly on return.

Therefore, the final solution is to jump to a new activity page every time a new URL is loaded. We rewrite the shouldOverrideUrlLoading method of WebViewClient to block url jump to a new page.

  llWebView.webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(p0: WebView? , p1: String?) : Boolean {/ / intercept url, jump to a new activity page to open the url val intent = intent (this, WebViewActivity: : class. Java) intent. PutExtra ("url", url)
           toIntent(intent)
           return true}}Copy the code

Then run after found another problem, when the page redirects, will open a blank page first, and then open after a redirect page, and then return when the user will see there is a blank page, to solve the problem, you should first of all to know the url redirection, if you know a certain url redirects, We just need to determine that the redirected URL does not perform the jump to solve the problem.

If the link is redirected, shouldOverrideUrlLoading should precede onPageFinished by printing the Log of the redirected URL. A link that is not redirected is the opposite. From this conclusion, we can define a variable to indicate whether the link is redirected or not, and then determine whether it is redirected.

 var mIsRedirect: Boolean = falseLlwebview. webViewClient = object:WebViewClient() { override fun shouldOverrideUrlLoading(p0: WebView? , p1: String?) : Boolean {/ / intercept url, jump to a new activity page to open the url val intent = intent (this, WebViewActivity: : class. Java) intent. PutExtra ("url", url)
               toIntent(intent)
               return true} override fun onPageStarted(p0: WebView? , p1: String? , p2: Bitmap?) { super.onPageStarted(p0, p1, p2) mIsRedirect =true} override fun onPageFinished(p0: WebView? , p1: String?) { super.onPageFinished(p0, p1) mIsRedirect =false}}Copy the code

This way, like a browser, you can return to a webView page without refreshing the page or resetting the page state.