Disable cache in Selenium Chrome Driver

zablotski picture zablotski · May 1, 2015 · Viewed 18.4k times · Source

I’m using the Selenium ChromeDriver in order to measure performance of web pages. But by default in Chrome driver cache is enabled.

Option --disable-application-cache is deprecated now https://code.google.com/p/chromium/issues/detail?id=447206

Also I can initialize a new instanсe of driver each time, but it is not very convenient.

My question is there a way for properly disable cache?

Thanks!

Answer

Rahul L picture Rahul L · Jul 8, 2020

In Chrome Dev tools Network tab we can disable the cache by clicking on 'Disable Cache' checkbox. refer

Same behavior can be replicated using the Chrome DevTools Protocol support in the Selenium 4.

We can use 'Network.setCacheDisabled' from Chrome DevTools Protocol

Toggles ignoring cache for each request. If true, cache will not be used.
parameters

cacheDisabled
    boolean

    Cache disabled state.

Example is from the Selenium Test for DevTools

import org.openqa.selenium.devtools.network.Network;

 @Test
  public void verifyCacheDisabledAndClearCache() {

    ChromeDriver driver = new ChromeDriver();
    DevTools devTools = driver.getDevTools();
    devTools.createSession();
   

    devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.of(100000000)));

    driver.get("http://www.google.com");

    devTools.send(Network.setCacheDisabled(true));

    devTools.addListener(Network.responseReceived(), responseReceived -> assertEquals(false, responseReceived.getResponse().getFromDiskCache()));

   driver.get("http://www.google.com");

    devTools.send(Network.clearBrowserCache());

  }

getFromDiskCache() -- Specifies if request was served from the disk cache.

For above code it will be false

You can refer the selenium repository for all the example tests devtools/ChromeDevToolsNetworkTest.java

For Dev Tools Maven Dependency

<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-devtools -->
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-devtools</artifactId>
    <version>4.0.0-alpha-6</version>
</dependency>