Bypass a cookie consent banner
Get past a consent overlay by clicking accept, pre-setting the cookie, or blocking the CMP script.
A consent overlay covers the page and blocks the elements a test needs. Pick one of three ways past it, from the most realistic to the fastest.
Option 1: click accept
The closest approach to the real user flow is to dismiss the banner through the UI. Do it once at the start, then continue with the test.
$page->goto('https://example.com');
$page->getByRole('button', ['name' => 'Accept all'])->click();
This exercises the real banner. The downside is that it depends on the CMP rendering the same button every run.
Option 2: pre-set the consent cookie
Most consent managers store the choice in a cookie. Add it to the context before navigating, and the banner never shows.
$context->addCookies([
[
'name' => 'cookie_consent',
'value' => 'accepted',
'domain' => 'example.com',
'path' => '/',
],
]);
$page = $context->newPage();
$page->goto('https://example.com');
Read the real cookie name and value from your CMP first. This skips the banner without touching the UI, which keeps every other test stable.
Option 3: block the CMP script
If the consent manager loads from a known third party, abort its script so the banner is never injected.
use Playwright\Network\RouteInterface;
$page->route('https://cdn.consentmanager.example/**', static function (RouteInterface $route): void {
$route->abort();
});
$page->goto('https://example.com');
Register the route before goto(), or the script may already be on its way. Block only the CMP host: a broad pattern can drop assets the page needs.
Which to pick
Pre-setting the cookie is the usual default: it is fast and does not depend on the banner's markup. Click accept when the consent flow itself is what you are testing. Block the script only when the cookie approach does not stop the banner.
Expected result
The overlay no longer covers the page and the next user-facing assertion can target the real content. For the cookie path, verify the banner stays hidden after the first navigation.
Go next
- Block unwanted requests: aborting third-party requests
- Handling authentication: the same state-and-cookie tools for sign-in