DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk6 min

How to Persist Cookie Consent Between Puppeteer Screenshot Runs

Keep consent state across Puppeteer screenshot runs by reusing a browser profile or restoring the target site’s actual storage into a fresh context.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To keep a site’s consent choice between separate Puppeteer launches, reuse the same browser profile by setting a stable userDataDir in puppeteer.launch(). If you need fresh, isolated browser contexts instead, save the site’s actual consent state and restore it before navigating to the page. First determine whether that site stores consent in cookies, localStorage, or another mechanism; Puppeteer does not carry state from one context to another automatically.

Choose how consent should persist

There are two practical approaches. Reusing a profile is simplest when a screenshot run should behave like a returning visitor. Explicitly restoring selected state is better when each run needs a clean, reproducible context. In either case, consent persistence depends on how the target site implements its consent manager.

As an Amazon Associate I earn from qualifying purchases.

Approach What it carries forward Best fit Trade-off
Reuse userDataDir Browser-profile state, including stored site state Separate launches that should use a returning-user profile Runs share state, so earlier activity can affect later runs; secure the profile directory.
Save and restore consent state Only the state you explicitly capture and seed Fresh contexts or test setups that need visible, repeatable initialization You must preserve relevant cookie metadata and handle localStorage or other storage if the site uses it.

Reuse a browser profile across launches

Set userDataDir to the same stable directory every time you launch Puppeteer. The directory must remain available between runs. Puppeteer documents this launch option as the user data directory path.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({
    headless: true,
    userDataDir: './puppeteer-profile',
  });

  try {
    const page = await browser.newPage();
    await page.goto('https://example.com', { waitUntil: 'networkidle2' });
    await page.screenshot({ path: 'page.png', fullPage: true });
  } finally {
    await browser.close();
  }
})();

Run that script again with the same directory to reuse the profile. The first run may still show a consent banner until you accept it; the later run can use the stored state if the site keeps it in that profile. Do not point simultaneous browser processes at the same profile directory: the safe operational choice is to give each active process its own profile.

Because a browser profile can contain cookies and other private browsing data, protect its directory with the same care as credentials. Avoid committing it to source control or sharing it as a build artifact.

Restore cookies into an isolated context

A new BrowserContext is isolated from other contexts: cookies and localStorage are not shared. This is useful for test isolation, but it also explains why a newly created context can show the banner again even when another context already accepted it. In Chrome, non-default contexts are incognito contexts. See Puppeteer’s BrowserContext API.

When the site uses cookies, read them after consent has been accepted, store the relevant records securely, and set them in the new context before navigating to the site. Current context-scoped methods are BrowserContext.cookies() and BrowserContext.setCookie(); the equivalent browser methods operate on the default context. Puppeteer’s cookie guide covers reading, writing, and deleting cookies: Puppeteer cookies guide.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({ headless: true });

  try {
    // Capture this state after accepting consent on the target site.
    const sourceContext = await browser.createBrowserContext();
    const sourcePage = await sourceContext.newPage();
    await sourcePage.goto('https://example.com', { waitUntil: 'networkidle2' });
    // Accept the site's consent banner here, using its actual UI.
    const consentCookies = await sourceContext.cookies('https://example.com');

    // In a later run, load securely saved consentCookies and seed a fresh context.
    const screenshotContext = await browser.createBrowserContext();
    await screenshotContext.setCookie(...consentCookies);
    const page = await screenshotContext.newPage();
    await page.goto('https://example.com', { waitUntil: 'networkidle2' });
    await page.screenshot({ path: 'page.png', fullPage: true });

    await sourceContext.close();
    await screenshotContext.close();
  } finally {
    await browser.close();
  }
})();

This example demonstrates the API sequence within one browser process; across separate runs, serialize the captured cookie records to an appropriately protected store and load them before calling setCookie(). Use only the consent cookies you need rather than blindly importing unrelated session state.

Preserve cookie details and expiry behavior

Keep the cookie’s relevant scope and attributes when saving and restoring it: domain, path, expiration, secure, httpOnly, and sameSite can affect whether it applies. An omitted expires means a session cookie, so it does not have the same lifetime semantics as a persistent cookie. Puppeteer documents cookie APIs and these properties in its Cookie API reference and BrowserContext.setCookie() reference.

Do not use the deprecated page-level cookie methods in new code. Use the browser- or context-level APIs instead; see Page.setCookie() API reference for the deprecation note.

Handle localStorage or other consent storage

Not every consent manager records its decision in a cookie. Inspect the target site’s storage after accepting consent, using browser developer tools or a controlled page inspection, and identify the mechanism that actually changes. Puppeteer’s general API documentation establishes that localStorage is isolated with the rest of context storage, but it does not provide a universal consent key or import format for websites.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If the site stores the choice in localStorage, capture the relevant origin-specific values after consent and seed them in the new page before the site’s scripts inspect them. One way is to install an initialization script before navigation:

const savedConsent = { 'actual-consent-key': 'actual-saved-value' };
await page.evaluateOnNewDocument((entries) => {
  for (const [key, value] of Object.entries(entries)) {
    localStorage.setItem(key, value);
  }
}, savedConsent);
await page.goto('https://example.com');

Replace the example key and value only with values verified for the target site. If it uses IndexedDB, session storage, a server-side account preference, or a consent platform-specific mechanism, cookie copying alone will not reproduce that state.

Sequence screenshots without confusing capture and persistence

Set or restore state before navigating to the page whose screenshot you want. Then wait for the site to render and take the image with Page.screenshot(). Capturing a screenshot does not itself save consent.

Puppeteer documents that BrowserContext.newPage(), Browser.newPage(), and Page.close() wait while a screenshot in the same context is in progress. That protects those lifecycle operations from interfering with an active capture; it is not a mechanism for persisting or transferring consent.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot consent banners that return

  • The banner appears in every new context: this is expected isolation behavior. Reuse the same profile, or restore the relevant state into each new context before navigation.
  • Restored cookies are present but the banner remains: check that you saved the correct site’s consent cookies and retained their domain, path, and other relevant attributes. The site may rely on localStorage or another mechanism instead.
  • Consent works in one run but expires later: inspect whether the cookie has an expiration. A cookie without expires is a session cookie, and site policies can also replace or expire consent state.
  • Cookie-setting code throws or the cookie is ignored: verify the cookie record’s scope and attributes and set it in the intended context before visiting the page. Use the context API for context-managed state.
  • Parallel jobs interfere with a shared profile: avoid concurrent launches against one user data directory; isolate jobs with distinct profiles or explicitly seed each job’s context.
  • A screenshot operation appears to block page or context changes: Puppeteer’s documented same-context lifecycle waits can cause that sequencing. Await the screenshot before creating or closing pages and contexts; this behavior does not alter storage persistence.

Or skip the browser setup

If the goal is a clean website screenshot rather than testing your own consent-persistence logic, ScreenshotNeo is a website screenshot API and MCP server. Its one-call endpoint accepts a URL and returns an image or PDF. See the ScreenshotNeo API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp

ScreenshotNeo accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers report the page verdict and billing status. Its MCP server offers take_screenshot, get_page_info, and capture_pdf for AI agents. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Sign up free for 1,000 screenshots a month with no card.

Frequently Asked Questions

Why does Puppeteer show the consent banner again in a new browser context?

A new BrowserContext has isolated storage, so it does not inherit another context’s cookies or localStorage. Reuse a profile or seed the new context with the target site’s consent state.

Can I copy cookies to persist consent between runs?

Yes, if the site stores its consent choice in cookies. Preserve the relevant cookie scope and attributes, and check whether the site also uses another storage mechanism.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.