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

How to send email from current Outlook instance using Java + VBScript

If we are using .Net, we can easily access outlook and send emails using its own libraries. But what if we are using Java? Here we can seek ...