WebView无法清理当前页面历史记录

转自 https://www.jianshu.com/p/6ee9fb05ee55

经过数个小时的Google任然没有答案后,我打算写下这篇文章,让之后遇到这个问题的小伙伴能快速解决问题

都知道,当wap页面进行多次跳转之后,我们是可以使用goBack()来做返回上一层页面的,或者goBackOrForward()来进行多层的跳转。

像这样:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_BACK) {
        if (webview.canGoBack()) {
            webview.goBack(); // goBack()表示返回webView的上一页面
            return true;
        }
    }
    return super.onKeyDown(keyCode, event);
}

现在有一个需求,当用户进行了一大堆的跳转之后,进入了最后的页面,并且执行成功了,这个时候,产品要点击返回的时候跳回的是首页,并且清除之前的历史记录。

是不是想到了clearHistory()方法,是的,但是这个方法有一个坑。它只能清除当前页面之前的历史记录,即在A清理的记录然后loadUrl(B),B还是可以返回A的,这不是我们想要的。怎么处理呢?百度和Google了一段时间后,有如下几种方法:

(测试不生效)

mWebView.clearHistory(); 
mWebView.loadUrl(B);

(测试不生效)

mWebView.loadUrl(B);

.......

@Override
public void onPageFinished(WebView view, String url) {
    super.onPageFinished(view, url);
    mWebView.clearHistory(); 
}

(测试不生效)
When there is only one item in WebView’s internal back/forward list, clearHistory() won’t clear anything. When there are more than one items in back/forward list, clearHistory() will clear all the items except the top one, or the current one.
The next question you might ask is when WebView adds an item to its back/forward list when loading a URL. By listening WebChromeClient.onProgressChanged(), we can know this, when new progress is bigger than 10, the loading URL will be added to its back/forward list. So when new progress is bigger than 10, loading URL becomes current item and thus you can clear previous loaded URLs by calling clearHistory().

mWebView.loadUrl(B);

.......

@Override
public void onProgressChanged(WebView view, int newProgress) {
    super.onProgressChanged(view, newProgress);
     if(newProgress > 10) {
        mWebView.clearHistory(); 
    }
}

(生效不合理)

mWebView.loadUrl("B")
mWebView.postDelayed(new Runnable() {
    @Override
    public void run() {
        mWebView.clearHistory();
    }
}, 1000);

在我经历数小时的百度、Google依然没有找到方法。
准备要放弃,使用上面这种延迟1秒或者数秒的方法的时候,再次进入WebView的源码中,我相信Google Coder会给一条生路的。果然,既然有onPageFinished()方法,那应该也有插入历史记录的方法调用吧?
最终使用了如下方法成功。

在WebViewClient中:

@Override
public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
    super.doUpdateVisitedHistory(view, url, isReload);
    if (needClearHistory) { 
        needClearHistory = false;
        webview.clearHistory();//清除历史记录
    }
}

解决!

It's very easy to be different but very difficult to be better

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值