November 3, 2020

How to clear chrome cache and browser history programmatically using Selenium C#

  November 3, 2020

While automating some test cases we may come across situations where we need to clear the browser history between two steps.

Since we are scripting the end-to-end flow, we cant manually clear the cache by going to browser settings.

Let's see how we can programmatically clear the cache using simple selenium actions.

Before doing this through automation we need to manually open the Clear browsing data screen of chrome and select the time range (this is a one-time thing). This time range will be cleared each time we run the code while running automation.


For the latest chrome browser, we can use the below code (Using JavaScript executer and CSS path) to do this. If this fails, try the other ones given below.

public void ClearChromeHistory()
    IJavaScriptExecutor executer = (IJavaScriptExecutor)driver;
    string buttonCssScript = "return document.querySelector('settings-ui').shadowRoot.querySelector('settings-main').shadowRoot.querySelector('settings-basic-page').shadowRoot.querySelector('settings-section > settings-privacy-page').shadowRoot.querySelector('settings-clear-browsing-data-dialog').shadowRoot.querySelector('#clearBrowsingDataDialog').querySelector('#clearBrowsingDataConfirm')";
    IWebElement clearButton = (IWebElement)executer.ExecuteScript(buttonCssScript);


Another way to clear the cache :


We can use this, just after the browser launch with the driver instance (This code directly acts on the UI ) There are other ways in which we can clear cache using the chrome options and driver capabilities. The method mentioned above can be used if other options are failed.

Note: This is specifically for the chrome browser. A similar one can be written for other browsers also

Thanks for reading How to clear chrome cache and browser history programmatically using Selenium C#

« Prev Post

No comments:

Post a Comment

Fixing javascript error: Cannot read properties of null (reading 'querySelector') issue when using CSS identifier in selenium

 JavaScript is another way to interact with web elements when normal selenium methods fail to act. But one issue with javascript is, it does...