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.

UPDATE

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()
{
    driver.Navigate().GoToUrl("chrome://settings/clearBrowserData");
    Thread.Sleep(3000);
    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);
    clearButton.Click();

}


Another way to clear the cache :

driver.Manage().Cookies.DeleteAllCookies();
driver.Navigate().GoToUrl("chrome://settings/clearBrowserData");
driver.FindElement(By.XPath("//settings-ui")).SendKeys(OpenQA.Selenium.Keys.Enter);

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
logoblog

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

Previous
« Prev Post

No comments:

Post a Comment

Bookmark this website for more workarounds and issue fixes.

Verify Zip file contents without extracting using C# + Selenium

While doing automation testing, we may get a scenario where we need to download a zip file and to validate the contents inside it. One way t...