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:
-
Clear WebView's History: If you only want to clear the browsing history of WebView, you can call the
clearHistorymethod. This will clear all forward and backward navigation records in WebView.javawebView.clearHistory(); -
Clear Cache and Cookies: Additionally, if you want to thoroughly clear all browsing data, including cached files and cookies, you can call the
clearCacheandCookieManager'sremoveAllCookiesmethods:javawebView.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; iftrueis passed, it clears both memory and disk cache. -
Clear Autofill Form Data (if needed): If your WebView uses autofill and you want to clear this data, you can use the
clearFormDatamethod:javawebView.clearFormData(); -
Clear WebStorage (HTML5 Web Storage data): For applications using HTML5 Web Storage (e.g., LocalStorage and SessionStorage), you also need to clear this data:
javaWebStorage.getInstance().deleteAllData(); -
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:
javaprivate 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.