0

PS我的英语很差,我的文字有错误)))请抱歉!

如何使webview返回上一页并且不显示about:空白?这是我的代码:

@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();
        }
    }

例如,加载了谷歌页面,然后发生错误,并且加载了 about:blank,当页面重新加载时,WebView 重新加载 about:blank 而不是谷歌页面。如何让谷歌页面在重新加载时加载?

4

1 回答 1

0

如果 about:blank 页面已经加载,然后您正在通过调用重新加载 webview webView.reload(),它只会重新加载当前页面,即 about:blank。

如果你想加载上一页,只需调用webView.goBack()或者你可以像这样直接加载 url -> webView.loadUrl("<your.web.url>")

如果您想更好地控制 webview,请使用WebViewClientWebChromeClient 。

请参阅下面的代码

首先创建 WebViewClient 并将其分配给 webview。

var currentUrl : String = "https://www.google.com";
webview.webViewClient = MyWebViewClient()

在 WebViewClient 的shouldOverrideUrlLoading方法中,您可以拥有自己的逻辑来决定要加载哪个网页。

 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)
        }
    }
于 2020-10-06T05:23:33.897 回答