Dismiss a Cookie Consent Banner Once
Skip the consent banner in every test by pre-setting the cookie or storage key it checks, with a click fallback.
Problem
A consent banner covers the page on first load and intercepts clicks. Every test clicks “Accept”, which is slow, occasionally flaky, and pollutes the test with a step unrelated to it.
Solution
Find out how the banner remembers consent (a cookie or a localStorage key, visible in DevTools after accepting once), set it before the first page load, and keep a click fallback for the day the mechanism changes.
public static void preAcceptCookies(WebDriver driver, String baseUrl) { driver.get(baseUrl + "/robots.txt"); // any cheap page on the domain driver.manage().addCookie(new Cookie.Builder("cookie_consent", "accepted").path("/").build()); ((JavascriptExecutor) driver).executeScript( "localStorage.setItem('consent', JSON.stringify({analytics: true, marketing: false, ts: Date.now()}));");}
public static void dismissIfShown(WebDriver driver) { List<WebElement> accept = driver.findElements(By.cssSelector("#cookie-banner button.accept")); if (!accept.isEmpty() && accept.get(0).isDisplayed()) { accept.get(0).click(); new WebDriverWait(driver, Duration.ofSeconds(5)) .until(ExpectedConditions.invisibilityOfElementLocated(By.id("cookie-banner"))); }}
// Driver factory: preAcceptCookies(driver, baseUrl); then in page objects' open(): dismissIfShown(driver);def pre_accept_cookies(driver, base_url): driver.get(f"{base_url}/robots.txt") driver.add_cookie({"name": "cookie_consent", "value": "accepted", "path": "/"}) driver.execute_script( "localStorage.setItem('consent', JSON.stringify({analytics: true, marketing: false, ts: Date.now()}));")
def dismiss_if_shown(driver): accept = driver.find_elements(By.CSS_SELECTOR, "#cookie-banner button.accept") if accept and accept[0].is_displayed(): accept[0].click() WebDriverWait(driver, 5).until(EC.invisibility_of_element_located((By.ID, "cookie-banner")))async function preAcceptCookies(driver, baseUrl) {await driver.get(`${baseUrl}/robots.txt`);await driver.manage().addCookie({ name: 'cookie_consent', value: 'accepted', path: '/' });await driver.executeScript( "localStorage.setItem('consent', JSON.stringify({analytics: true, marketing: false, ts: Date.now()}));");}
async function dismissIfShown(driver) {const accept = await driver.findElements(By.css('#cookie-banner button.accept'));if (accept.length && (await accept[0].isDisplayed())) { await accept[0].click(); await driver.wait(until.stalenessOf(accept[0]), 5000);}}public static void PreAcceptCookies(IWebDriver driver, string baseUrl){ driver.Navigate().GoToUrl($"{baseUrl}/robots.txt"); driver.Manage().Cookies.AddCookie(new Cookie("cookie_consent", "accepted", "/")); ((IJavaScriptExecutor)driver).ExecuteScript( "localStorage.setItem('consent', JSON.stringify({analytics: true, marketing: false, ts: Date.now()}));");}
public static void DismissIfShown(IWebDriver driver){ var accept = driver.FindElements(By.CssSelector("#cookie-banner button.accept")); if (accept.Count > 0 && accept[0].Displayed) { accept[0].Click(); new WebDriverWait(driver, TimeSpan.FromSeconds(5)) .Until(d => d.FindElements(By.Id("cookie-banner")).All(e => !e.Displayed)); }}Why It Works
Consent managers check a cookie or storage key on load and skip the banner if it says consent was given. Setting it first means the banner never renders. Landing on a cheap page first satisfies the rule that cookies can only be set for the current domain.
Gotchas
- The key name and value format are specific to the consent tool (OneTrust, Cookiebot, custom); copy them from a real accepted session and expect them to include a timestamp or version.
- Keep at least one test that exercises the banner itself.
- Some managers store consent server-side per user; then the API or a test-account flag is the right approach.