How to Clear Cache in Chrome Using Selenium Webdriver Java

Selenium is an open-source web-based automation tool that is implemented using a web driver. We will be using chromedriver because Selenium 3 enables chrome driver as the custom WebDriver implementation for the Chrome browser.

Pre-requisites:

  1. chromedriver.exe
  2. maven dependency selenium
 <dependency>
    <groupid>org.seleniumhq.selenium</groupid>
	<artifactid>selenium-java</artifactid>  
	<version>4.1.1</version> 
 </dependency>

Steps:

The following 6 steps will automate the process:

  1. Set webdriver.gecko.driver and its' path as a system property.
  2. Set the firefox diver.
  3. Typecast web driver as Javascript executor. 
  4. Browse the website.
  5. Get a clear cache button using the Javascript path.
  6. Execute the following script to execute and hit click:
    return document.querySelector("body > settings-ui").shadowRoot.querySelector("#main").shadowRoot.querySelector("settings-basic-page").shadowRoot.querySelector("#basicPage > settings-section:nth-child(9) > settings-privacy-page").shadowRoot.querySelector("settings-clear-browsing-data-dialog").shadowRoot.querySelector("#clearBrowsingDataConfirm")
Let’s see all the above steps in the code. We will use executeScript() function to get clear cache button.
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import java.util.List;


public class ClearCache {

    public static String CHROMEDRIVER_PATH = "F:\\WORK\\SeleniumShortTasks\\ChromeCache\\src\\main\\resources\\chromedriver.exe";

    public static void main(String[] args) {
        //set Chrome webdriver
        System.setProperty("webdriver.chrome.driver", CHROMEDRIVER_PATH);
        WebDriver driver = new ChromeDriver();
        JavascriptExecutor js = (JavascriptExecutor) driver;

        //get the browser & Browse to the Settings
        String siteLink = "chrome://settings/clearBrowserData";
        driver.get(siteLink);

        //wait for setting window to load
        try {
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //get clear cache button
        WebElement clearBtn = (WebElement) js.executeScript("return document.querySelector(\"body > settings-ui\").shadowRoot.querySelector(\"#main\").shadowRoot.querySelector(\"settings-basic-page\").shadowRoot.querySelector(\"#basicPage > settings-section:nth-child(9) > settings-privacy-page\").shadowRoot.querySelector(\"settings-clear-browsing-data-dialog\").shadowRoot.querySelector(\"#clearBrowsingDataConfirm\")");
        //Click
        clearBtn.click();

    }
}

Output:

All resources used in this tutorial are attached:
  • source code
  • geckdriver.exe
Download

Comments