您的位置:首页 > 移动开发

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

2017-12-31 23:59 941 查看
转自 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  webview android