How to Disable Cookies in Selenium Headless Chrome with RSpec
Learn how to clear cookies in Selenium Headless Chrome with RSpec, verify browser state, and understand why clearing is different from blocking future cookies.

Short answer: Selenium can delete cookies that already exist in the current browser context, but delete_all_cookies does not permanently prevent a page or browser from setting new cookies. In an RSpec test, start Chrome with --headless=new, navigate to the site, clear the current cookie jar, and then reload or continue the test while checking cookie state.
Headless mode and cookie policy are separate settings. Chrome’s documented options page lists --headless=new as a startup argument, while Selenium’s cookie API handles cookies for the current WebDriver context. The official APIs do not provide a universal, version-independent Ruby switch that blocks every first-party and third-party cookie. See the Selenium cookie documentation and Selenium Chrome options documentation.
What “disable cookies” can mean
| Goal | What to do | What it proves |
|---|---|---|
| Remove cookies already stored | Call driver.manage.delete_all_cookies in the current browser context. |
The cookies present at that moment were removed. |
| Test a first visit | Use a fresh driver or clear cookies, then navigate or reload and inspect state. | The page starts without the previous test’s cookie jar. |
| Restrict third-party cookies | Use a Chrome/DevTools Protocol control appropriate to the exact browser version. | Only the documented third-party restriction scope is exercised. |
| Block every cookie, including first-party cookies | Do not assume Selenium’s cookie deletion API provides this policy. | The reviewed official sources do not define a universal Ruby recipe for all-cookie blocking. |
Prerequisites
- Ruby and Bundler.
- The
selenium-webdrivergem and RSpec. - Chrome and a compatible ChromeDriver. Selenium’s Chrome guidance says the Chrome and ChromeDriver major versions should match.
bundle add selenium-webdriver rspec
bundle exec rspec --init

Clear all existing cookies in headless Chrome with RSpec
This example uses the documented Selenium cookie operations and Chrome’s headless argument. It intentionally demonstrates clearing existing state rather than claiming to block future cookie writes.
require 'selenium-webdriver'
RSpec.describe 'cookie behavior in headless Chrome' do
let(:driver) do
options = Selenium::WebDriver::Chrome::Options.new
options.add_argument('--headless=new')
options.add_argument('--window-size=1440,1000')
Selenium::WebDriver.for(:chrome, options: options)
end
after do
driver.quit
end
it 'clears cookies in the current browser context' do
driver.navigate.to('https://example.test')
driver.manage.delete_all_cookies
expect(driver.manage.all_cookies).to be_empty
end
end
Replace https://example.test with a test page you control. Selenium cookie operations are scoped to the current browser context and normally require the browser to have navigated to the relevant domain first.
Verify the state after the page runs
Deleting cookies is a point-in-time operation. JavaScript, redirects, analytics tags, consent managers, or server responses can set cookies again after the deletion. If your test is about behavior after a clean start, clear the cookies, navigate or reload as appropriate, wait for the page’s relevant state, and inspect the jar again.
it 'starts empty, then detects cookies created by the page' do
driver.navigate.to('https://example.test')
driver.manage.delete_all_cookies
expect(driver.manage.all_cookies).to be_empty
driver.navigate.refresh
cookies_after_load = driver.manage.all_cookies
puts cookies_after_load.map { |cookie| cookie[:name] }
end
A non-empty result after reload does not necessarily mean deletion failed. It usually means the page created a new cookie, the server set one in a response, or navigation moved to a different host or subdomain.
Use a fresh browser for test isolation
The most reliable way to avoid state leaking between examples is to create and quit a driver per example or per isolated context. Clearing cookies is useful when you deliberately want to reuse a session, but a fresh driver also removes other state such as local storage, session storage, cache, and service-worker data.

RSpec.describe 'isolated browser state' do
it 'gets a new browser context for this example' do
options = Selenium::WebDriver::Chrome::Options.new
options.add_argument('--headless=new')
driver = Selenium::WebDriver.for(:chrome, options: options)
begin
driver.navigate.to('https://example.test')
expect(driver.manage.all_cookies).to be_empty
ensure
driver.quit
end
end
end
Third-party cookie controls and CDP
Chrome DevTools Protocol’s Network domain documents methods including Network.clearBrowserCookies and Network.getCookies. The same documentation marks Network.setCookieControls as experimental and describes it as a control for third-party-cookie restriction. It is not documented as a switch that blocks every first-party and third-party cookie.
Read the exact protocol contract for your Chrome version in the Chrome DevTools Protocol Network documentation. Selenium exposes browser-specific DevTools functionality differently across language bindings and versions, so verify the Ruby binding, Chrome, and ChromeDriver versions before building a test around a CDP command. Keep the test’s scope explicit: clearing existing cookies, restricting third-party cookies, and blocking all cookies are different requirements.
Common errors and fixes
| Error or symptom | Likely cause | Fix |
|---|---|---|
invalid cookie domain |
A cookie was added before navigating to its domain, or the domain does not match the current page. | Navigate to the target host first and use a matching domain and path. |
| Cookies return after deletion | The page or a response set them again. | Inspect cookies after reload and test the page’s behavior, not only the instant after deletion. |
| Cookies from another host remain | Cookie operations are scoped to the current browser context and domain rules. | Navigate to the relevant host or use a fresh driver for complete test isolation. |
| Headless works differently from headed mode | Viewport, timing, browser version, or page behavior differs; headless is not a cookie policy. | Set a deterministic window size, wait for the application state, and compare browser versions. |
| Chrome session will not start | ChromeDriver and Chrome major versions are incompatible, or the binary is unavailable. | Check installed versions and Selenium’s Chrome setup guidance. |
| Assuming a flag blocks all cookies | A command-line argument or experimental protocol setting was applied outside its documented scope. | Document whether the test clears existing cookies or restricts third-party cookies; do not label either as universal all-cookie blocking. |
Timing and reliability practices
- Clear cookies after navigating to the target origin when the test concerns that origin.
- Use explicit waits for the application condition you care about instead of a fixed sleep wherever possible.
- Reload after clearing only when a reload is part of the behavior under test; an unnecessary reload can create new cookies.
- Quit every driver in an RSpec
afterhook, including when an expectation fails. - Record Chrome, ChromeDriver, Selenium, Ruby, and operating-system versions when diagnosing differences.
- For parallel tests, give each worker its own driver and profile. Shared profiles can reintroduce state.
Performance and cost notes
Deleting cookies is a small in-memory browser operation. The expensive parts of a test suite are usually starting Chrome, navigating, waiting for application state, and running the page’s JavaScript. Reusing a driver can reduce startup overhead but increases isolation work; creating a driver per example improves isolation and costs more time.
Cookie clearing does not prevent network requests, JavaScript execution, trackers, or resource downloads. If the goal is request control or privacy testing, define those requirements separately and use the browser or DevTools controls documented for the exact versions in your stack.
Or skip the browser setup
If your actual goal is to obtain a clean screenshot rather than test browser cookie behavior, ScreenshotNeo provides a one-request website screenshot API and MCP server. It accepts the consent banner like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and the response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers. An MCP server lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf.
See the ScreenshotNeo API documentation for all options.
cURL
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
Node.js
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`ScreenshotNeo returned ${res.status}`);
const body = Buffer.from(await res.arrayBuffer());
require('fs').writeFileSync('shot.webp', body);
ScreenshotNeo has a free plan with 1,000 screenshots per month and no card required. Paid plans start at $5 for 3,000 screenshots, and every feature is included on every plan. Create a free ScreenshotNeo account.
FAQ
Does delete_all_cookies disable cookies?
No. It deletes cookies currently stored in the current browser context. A page can create new cookies afterward.
Does --headless=new block cookies?
No. It selects Chrome’s headless mode. Cookie handling is a separate concern.
Should I clear cookies or start a new driver?
Clear cookies when you need to reuse a session deliberately. Start a new driver when you need stronger isolation from all browser state.
Can Selenium Ruby block every first-party and third-party cookie with one supported setting?
The reviewed official documentation does not provide a universal, version-specific Ruby recipe for that requirement. Define the scope and verify any Chrome or CDP control against your exact versions.
Why did a cookie appear immediately after I cleared the jar?
Navigation, redirects, JavaScript, consent software, analytics, or server responses can set it again. Inspect the jar after the page reaches the state under test.


