P.S my English very bad and I have mistakes in text))) please sorry!
How to make to webview returns to the previous page and does not show about: blank? here is my code:
@Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
return;
}
else {
finish();
}
super.onBackPressed();
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
mbErrorOccured = true;
showErrorLayout();
super.onReceivedError(view, errorCode, description, failingUrl);
loadErrorPage();
}
}
private void showErrorLayout() {
mlLayoutRequestError.setVisibility(View.VISIBLE);
}
private void loadErrorPage() {
if(mWebView!=null){
String htmlData ="<html><body><div align= center >Check your internet!</div></body>" ;
mWebView.loadUrl("about:blank");
mWebView.loadDataWithBaseURL(null,htmlData, "text", "utf-8",null);
mWebView.invalidate();
}
}
For example, the Google page loaded, then an error occurred and about: blank was loaded, and when the page is reloaded, the WebView reloads about: blank and not the Google page. How to make the Google page load on reload?
If about:blank page is already loaded and then you are reloading webview by calling webView.reload()
, it will just reload the current page i.e. about:blank.
If you want to load previous page, just call webView.goBack()
or you can directly load the url like this -> webView.loadUrl("<your.web.url>")
Use WebViewClient and WebChromeClient if you want to have a better control on webview.
See the code below
First create WebViewClient and assign it to webview.
var currentUrl : String = "https://www.google.com";
webview.webViewClient = MyWebViewClient()
In WebViewClient's shouldOverrideUrlLoading
method, you can have you own logic to decide which web page you want's to load.
class MyWebViewClient : WebViewClient(){
override fun onReceivedError(
view: WebView?,
request: WebResourceRequest?,
error: WebResourceError?
) {
super.onReceivedError(view, request, error)
// here display your custom error message with retry feature
displayErrorDialog()
}
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
// update current url
if (url != null) {
currentUrl = url
}
return super.shouldOverrideUrlLoading(view, url)
}
}