乐闻世界logo
搜索文章和话题

How to clear webview history?

1个答案

1

When using WebView in your application, you may need to clear history to protect user privacy or ensure the WebView behaves as if it were a fresh instance. In Android, you can clear history by calling methods provided by WebView. Here are the steps to do this:

  1. Clear WebView's History: If you only want to clear the browsing history of WebView, you can call the clearHistory method. This will clear all forward and backward navigation records in WebView.

    java
    webView.clearHistory();
  2. Clear Cache and Cookies: Additionally, if you want to thoroughly clear all browsing data, including cached files and cookies, you can call the clearCache and CookieManager's removeAllCookies methods:

    java
    webView.clearCache(true); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.removeAllCookies(null); cookieManager.flush();

    Here, the boolean parameter in clearCache(true) indicates whether to clear cache on disk; if true is passed, it clears both memory and disk cache.

  3. Clear Autofill Form Data (if needed): If your WebView uses autofill and you want to clear this data, you can use the clearFormData method:

    java
    webView.clearFormData();
  4. Clear WebStorage (HTML5 Web Storage data): For applications using HTML5 Web Storage (e.g., LocalStorage and SessionStorage), you also need to clear this data:

    java
    WebStorage.getInstance().deleteAllData();
  5. Note: Clearing WebView data may affect running JavaScript code, so when performing these operations, ensure no JavaScript operations are running or reload the WebView after clearing data.

Example: If you are developing a browser application, users may not want their browsing history retained, especially when using privacy mode. You can use the above methods when opening a new incognito window to ensure the WebView does not retain any history, as shown in the code below:

java
private void openIncognitoTab() { WebView webView = new WebView(context); // Clear history, cache, and cookies webView.clearHistory(); webView.clearCache(true); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.removeAllCookies(null); cookieManager.flush(); // Clear form data webView.clearFormData(); // Clear Web Storage data WebStorage.getInstance().deleteAllData(); // ... load the required URL next webView.loadUrl("https://example.com"); }

By following these steps, you can ensure the WebView is completely "clean" when opened, with no user browsing traces left behind.

2024年6月29日 12:07 回复

你的答案