22

In my application I need a way to clear only the cache of the chrome browser before log out (except cookies - I do not want to delete cookies).

Can any one suggest me a way to click on the CLEAR DATA button in chrome. I have written the below code but the code is not working.

Configuration :

Chrome Version: Version 65.0.3325.181 (Official Build) (64-bit)

Selenium Version: 3.11.0

//Clear the cache for the ChromeDriver instance.
driver.get("chrome://settings/clearBrowserData");
Thread.sleep(10000);
driver.findElement(By.xpath("//*[@id='clearBrowsingDataConfirm']")).click();

enter image description here

VISHVAMBRUTH J T
  • 602
  • 4
  • 14
  • 29

13 Answers13

12

You are using here

driver.findElement(By.xpath("//*[@id='clearBrowsingDataConfirm']")).click();

Unfortunately, this won’t work because the Chrome settings page uses Polymer and WebComponents, need to use query selector using the /deep/ combinator, so selector in this case is * /deep/ #clearBrowsingDataConfirm.

Here is workaround to your problem...you can achieve the same using either one of the following...

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;

public class ClearChromeCache {

    WebDriver driver;

    /*This will clear cache*/
    @Test
    public void clearCache() throws InterruptedException {
        System.setProperty("webdriver.chrome.driver","C://WebDrivers/chromedriver.exe");
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("disable-infobars");
        chromeOptions.addArguments("start-maximized");
        driver = new ChromeDriver(chromeOptions);
        driver.get("chrome://settings/clearBrowserData");
        Thread.sleep(5000);
        driver.switchTo().activeElement();
        driver.findElement(By.cssSelector("* /deep/ #clearBrowsingDataConfirm")).click();
        Thread.sleep(5000);
    }

    /*This will launch browser with cache disabled*/
    @Test
    public void launchWithoutCache() throws InterruptedException {
        System.setProperty("webdriver.chrome.driver","C://WebDrivers/chromedriver.exe");
        DesiredCapabilities cap = DesiredCapabilities.chrome();
        cap.setCapability("applicationCacheEnabled", false);
        driver = new ChromeDriver(cap);
    }
}
Sodium
  • 1,016
  • 1
  • 9
  • 22
  • This is something I need, but I already use ChromeOptions (disable-infobars) so is there a way to use both ChromeOptions AND DesiredCapabilities or is there a way to disable cache through a ChromeOptions argument? @DebanjanB I'm tagging you too because you might also be able to answer this for me. – Bill Hileman Jul 22 '19 at 18:20
  • @BillHileman I suppose you are looking to configure _DesiredCapabilities_ and then use `merge()` from _MutableCapabilities_ to merge within _ChromeOptions_ which you can find an example in **Option B** of [this discussion](https://stackoverflow.com/questions/47671884/how-to-merge-chrome-driver-service-with-desired-capabilities-for-headless-using/47672910#47672910) – undetected Selenium Jul 22 '19 at 19:09
  • I know you're not supposed to use comments to thank people, but thanks @DebanjanB. – Bill Hileman Jul 22 '19 at 19:35
  • 4
    This solution no longer works either : https://developers.google.com/web/updates/2017/10/remove-shadow-piercing –  May 06 '20 at 18:16
7

Chrome supports DevTools Protocol commands like Network.clearBrowserCache (documentation). Selenium does not have an interface for this proprietary protocol by default.

You can add support by expanding Selenium's commands:

driver.command_executor._commands['SEND_COMMAND'] = (
    'POST', '/session/$sessionId/chromium/send_command'
)

This is how you use it:

driver.execute('SEND_COMMAND', dict(cmd='Network.clearBrowserCache', params={}))

Note: this example is for Selenium for Python, but it's also possible in Selenium for other platforms in a similar way by expanding the commands.

Blaise
  • 13,139
  • 9
  • 69
  • 97
6

YEAR 2020 Solution (using Selenium 4 alpha):

Using the devtools

    private void clearDriverCache(ChromeDriver driver) {
    driver.getDevTools().createSessionIfThereIsNotOne();
    driver.getDevTools().send(Network.clearBrowserCookies());
    // you could also use                
    // driver.getDevTools().send(Network.clearBrowserCache());
}
frzsombor
  • 2,274
  • 1
  • 22
  • 40
  • Which driver supports this get_dev_tools() method? –  May 06 '20 at 18:21
  • 1
    not the driver but rather the version of selenium , i think the alpha versions support this : https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java – Soufiane Azeroual May 07 '20 at 21:46
3

Don´t forget the send keys!!!!

For Selenium Basic, below code is functional.

Function clean_cache()

    Set driver = New ChromeDriver
    Dim keys As New Selenium.keys


                driver.Get "chrome://settings/clearBrowserData"
                Sleep 5000
                driver.SendKeys (keys.Tab)
                Sleep 1000
                driver.SendKeys (keys.Tab)
                Sleep 1000
                driver.SendKeys (keys.Tab)
                Sleep 1000
                driver.SendKeys (keys.Tab)
                Sleep 1000
                driver.SendKeys (keys.Tab)
                Sleep 1000
                driver.SendKeys (keys.Tab)
                Sleep 1000
                driver.SendKeys (keys.Tab)
                Sleep 1000
                driver.SendKeys (keys.Enter)
                Sleep 2000
                driver.Quit

End Function
Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47
  • This "approach" works python +chromedriver +chrome 81.0 driver.get('chrome://settings/clearBrowserData') wait_until(lambda: (driver.find_element_by_xpath('//settings-ui'))) ui = driver.find_element_by_xpath('//settings-ui') ui.send_keys(Keys.TAB) # todo: this dialog may change at any time ui.send_keys(Keys.TAB) ui.send_keys(Keys.TAB) ui.send_keys(Keys.TAB) ui.send_keys(Keys.TAB) ui.send_keys(Keys.TAB) ui.send_keys(Keys.ENTER) wait_until(lambda: (driver.find_element_by_xpath('//settings-ui')), timeout=60) –  May 06 '20 at 20:11
1

Method #1 worked for me in clearing JWT using python selenium and chromedriver 87.

# method 1
driver.execute_script('window.localStorage.clear()')

# method 2
driver.execute_script('window.sessionStorage.clear()')
Marcel Wilson
  • 3,842
  • 1
  • 26
  • 55
0

There is another way to click on Clear data button by traversing through shadow tree. If you are trying to locate clear data button by simply searching web element by locator strategy, it won't work due to Chrome browser version upgrade. You need to traverse through shadow tree. You can try below code to click on "Clear data" in advance tab:

package selenium.demo.test;

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;

public class Test {
static WebDriver driver;
public static void main(String[] args) {
 System.setProperty("webdriver.chrome.driver","F:\\selenium\\chromedriver.exe");
    // Instantiate a ChromeDriver class.       
 driver=new ChromeDriver();  
 driver.get("chrome://settings/clearBrowserData");
 WebElement root1 = driver.findElement(By.cssSelector("settings-ui"));
    // get 1st shadowroot element
    WebElement shadowRoot1 = expandRootElement(root1);

    // get 2nd parent
    WebElement root2 = shadowRoot1.findElement(By.cssSelector("settings-main"));
    // get 2nd shadowroot element
    WebElement shadowRoot2 = expandRootElement(root2);

    // get 3rd parent
    WebElement root3 = shadowRoot2.findElement(By.cssSelector("settings-basic-page"));
    // get 3rd shadowroot element
    WebElement shadowRoot3 = expandRootElement(root3);

    // get 4th parent
    WebElement root4 = shadowRoot3.findElement(By.cssSelector("settings-section > settings-privacy-page"));
    // get 4th shadowroot element
    WebElement shadowRoot4 = expandRootElement(root4);

    // get 5th parent
    WebElement root5 = shadowRoot4.findElement(By.cssSelector("settings-clear-browsing-data-dialog"));
    // get 5th shadowroot element
    WebElement shadowRoot5 = expandRootElement(root5);

    // get 6th parent
    WebElement root6 = shadowRoot5.findElement(By.cssSelector("#clearBrowsingDataDialog"));
    WebElement root7 = root6.findElement(By.cssSelector("cr-tabs[role='tablist']"));
    root7.click();

    WebElement clearDataButton = root6.findElement(By.cssSelector("#clearBrowsingDataConfirm"));


    clearDataButton.click(); // click that hard to reach button!
    driver.quit();

}
private static WebElement expandRootElement(WebElement element) {
    WebElement ele = (WebElement) ((JavascriptExecutor) driver)
            .executeScript("return arguments[0].shadowRoot", element);
    return ele;
}

}
0

Below snippet navigates to the the chrome settings for clearing the browser data and sends a keypress to the opened dialog. Then it waits for the tab to close. You could easily do these steps manual.

IWebDriver Driver = new ChromeDriver()
Driver.Navigate().GoToUrl("chrome://settings/clearBrowserData");
Driver.SwitchTo().ActiveElement();
Driver.FindElement(By.XPath("//settings-ui")).SendKeys(Keys.Enter);
var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(30));
wait.Until(wd => wd.Url.StartsWith("chrome://settings"));
Pierre
  • 9
  • 2
  • @ItamarMushkin The snippet navigates to the the chrome settings for clearing the browser data and sends a keypress to the opened dialog. Then it waits for the tab to close. You could easily to these steps manual. – Pierre Mar 06 '20 at 09:38
  • No, add the explanation as part of the answer, not in comments (after that, we can delete this whole comments discussion) – Itamar Mushkin Mar 08 '20 at 06:22
0

this way work for me : in step one =>

pip install keyboard

step2 : use it in your code =>

from time import sleep
self.driver.get('chrome://settings/clearBrowserData')
sleep(10)
keyboard.send("Enter")
mamal
  • 1,791
  • 20
  • 14
0

The correct solution is deprecated, I've solved the problem by following this guide:

https://www.browserstack.com/guide/how-to-handle-cookies-in-selenium#:~:text=Navigate%20to%20the%20chrome%20settings,to%20open%20Chrome%20Developer%20Tools.

Specifically, using the command:

driver.manage().deleteAllCookies();
Hayden Eastwood
  • 928
  • 2
  • 10
  • 20
Balt
  • 13
  • 4
0
self.driver.get('chrome://settings/clearBrowserData')
time.sleep(0.5)  # this is necessary
actions = ActionChains(self.driver)
actions.send_keys(Keys.TAB * 7 + Keys.ENTER)
actions.perform()
Devin
  • 61
  • 6
0

The controling protocol already have this task: https://chromedevtools.github.io/devtools-protocol/tot/Network/#method-clearBrowserCache

And selenium v4+ have this implemented in its API:

driver.getDevTools().send(Network.clearBrowserCache());

For older versions of selenium it's still possible to call this method natively using underlying protocol:

private void clearCache(ChromeDriverService service, WebDriver driver) throws IOException {
        Map<String, Object> commandParams = new HashMap<>();
        commandParams.put("cmd", "Network.clearBrowserCache");
        commandParams.put("params", emptyMap());
        ObjectMapper objectMapper = new ObjectMapper();
        HttpClient httpClient = HttpClientBuilder.create().build();
        String command = objectMapper.writeValueAsString(commandParams);
        String u = service.getUrl().toString() + "/session/" + driver.getSessionId() + "/chromium/send_command";
        HttpPost request = new HttpPost(u);
        request.addHeader("content-type", "application/json");
        request.setEntity(new StringEntity(command));
        httpClient.execute(request);
    }

Note: for chromium you should use "/chromium/send_command" endpoint, for chrome: "/goog/cdp/execute". But as of my experience, these both work the same way in both chrome and chromium.

msangel
  • 9,895
  • 3
  • 50
  • 69
0

Just add below code

driver.manage().deleteAllCookies();

-1

Getting NoSuchElement exception :

driver = new ChromeDriver(service, chromeOption());
        driver.manage().deleteAllCookies();
        driver.get("chrome://settings/clearBrowserData");
        staticWait(5);
        driver.switchTo().activeElement();
        driver.findElement(By.cssSelector("* /deep/ #clearBrowsingDataConfirm")).click();

Chrome Version : 97.0.4692.71

Pankaj
  • 1
  • 2
  • 1
    Please post only answers in the answer section. If you would like to ask a question, please post it as a new question. Thank you. – Ferro Jan 18 '22 at 13:01