October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk6 min

Chrome Headless Screenshot With Cookies and Session Storage: How to Set It Up

A practical Playwright setup for headless Chrome screenshots with cookies and sessionStorage, including readiness checks, security cautions, and troubleshooting.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To capture an authenticated page with headless Chrome, set its cookies on a fresh browser context and seed sessionStorage with an initialization script before navigating. Then wait for the page’s actual ready state and take the screenshot. This guide uses Playwright for the concrete setup; the same sequence—prepare state, navigate, wait, capture—applies in Puppeteer, though the exact session-storage setup depends on the Puppeteer version you use.

Why cookies and sessionStorage need separate setup

Cookies are browser-context data that you can add with Playwright’s context.addCookies(). sessionStorage belongs to a page origin and is not included in Playwright’s documented storage-state workflow, so seed it separately. The order matters: register an initialization script before navigating so the values exist before the site’s JavaScript reads them. See Playwright’s authentication guide and BrowserContext API.

As an Amazon Associate I earn from qualifying purchases.

Headless mode changes how Chromium runs, not the need to establish the correct browser state. Chrome’s Headless mode documentation describes headless operation; the example below uses Playwright to launch Chromium headlessly.

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

Set up a headless screenshot with Playwright

1. Install Playwright

In a new project, install Playwright and its Chromium browser:

#1 Best Overall
Yubico - Security Key C NFC - Basic Compatibility - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB-C or NFC, FIDO Certified
  • POWERFUL SECURITY KEY: The Security Key C NFC is the essential physical passkey for protecting your digital life from phishing attacks. It ensures only you can access your accounts.
  • WORKS WITH 1000+ ACCOUNTS: Compatible with Google, Microsoft, and Apple. A single Security Key C NFC secures 100 of your favorite accounts, including email, password managers, and more.
  • FAST & CONVENIENT LOGIN: Plug in your Security Key C NFC via USB-C and tap it, or tap it against your phone (NFC) to authenticate. No batteries, no internet connection, and no extra fees required.
  • TRUSTED PASSKEY TECHNOLOGY: Uses the latest passkey standards (FIDO2/WebAuthn & FIDO U2F) but does not support One-Time Passwords. For complex needs, check out the YubiKey 5 Series.
  • BUILT TO LAST: Made from tough, waterproof, and crush-resistant materials. Manufactured in Sweden and programmed in the USA with the highest security standards.
npm init -y
npm install playwright
npx playwright install chromium

Run the script below from the project directory. Supply the session cookie and a JSON object of session-storage keys through environment variables rather than putting credentials directly in source code.

2. Add cookies and seed sessionStorage before navigation

import { chromium } from 'playwright';

const browser = await chromium.launch({ headless: true });
const context = await browser.newContext();

const sessionCookie = process.env.SESSION_COOKIE;
if (!sessionCookie) {
  throw new Error('Set SESSION_COOKIE before running this script.');
}

await context.addCookies([
  {
    name: 'session-id',
    value: sessionCookie,
    domain: 'example.com',
    path: '/',
    httpOnly: true,
    secure: true,
    sameSite: 'Lax',
  },
]);

const sessionStorageValues = JSON.parse(process.env.SESSION_STORAGE_JSON ?? '{}');
await context.addInitScript(({ hostname, values }) => {
  if (window.location.hostname === hostname) {
    for (const [key, value] of Object.entries(values)) {
      window.sessionStorage.setItem(key, value);
    }
  }
}, { hostname: 'example.com', values: sessionStorageValues });

const page = await context.newPage();
await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });

// Replace this with a selector or other signal that means the target UI is ready.
await page.locator('main').waitFor({ state: 'visible' });
await page.screenshot({ path: 'screenshot.png', fullPage: true });

await context.close();
await browser.close();

Change example.com, the cookie name and attributes, the target URL, and the readiness selector to match the site. The selector main is only an example; it does not guarantee that a page’s data or animations have finished loading.

Rank #2
Yubico - YubiKey 5C NFC - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB-C or NFC, FIDO Certified - Protect Your Online Accounts
  • POWERFUL SECURITY KEY: The YubiKey 5C NFC is the most versatile physical passkey, protecting your digital life from phishing attacks. It ensures only you can access your accounts
  • WORKS WITH 1000+ ACCOUNTS: Compatible with popular accounts like Google, Microsoft, and Apple. A single YubiKey 5C NFC secures 100+ of your favorite accounts, including email, password managers, and more
  • FAST & CONVENIENT LOGIN: Plug in your YubiKey 5C NFC via USB and tap it, or tap it against your phone (NFC), to authenticate. No batteries, no internet connection, and no extra fees required
  • MOST SECURE PASSKEY: Supports FIDO2/WebAuthn, FIDO U2F, Yubico OTP, OATH-TOTP/HOTP, Smart card (PIV), and OpenPGP. That means it’s versatile, working almost anywhere you need it
  • PRIMARY & SPARE KEYS: Just like having a spare house key, we recommend buying two YubiKeys - one for daily use and one as a spare. That way you’ll never get locked out of your accounts

Example environment setup on macOS or Linux:

export SESSION_COOKIE='your-session-cookie-value'
export SESSION_STORAGE_JSON='{"accessToken":"your-token","view":"dashboard"}'
node screenshot.js

Each session-storage value must be a string, as required by sessionStorage.setItem(). If your application stores structured data, JSON-stringify it before placing it in the environment variable and parse it in the page code as the application expects.

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

Cookie scope and attributes

Playwright requires a cookie’s domain and path. Match the site’s actual cookie scope and attributes: secure, httpOnly, and sameSite can affect whether the browser sends or exposes it as intended. A leading dot in a cookie domain can apply it to subdomains, according to the BrowserContext API. Use the domain that matches the page you visit; do not assume a cookie for one host authenticates another.

Rank #3
Yubico - YubiKey 5 NFC - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB-A or NFC, FIDO Certified - Protect Your Online Accounts
  • POWERFUL SECURITY KEY: The YubiKey 5 NFC is the most versatile physical passkey, protecting your digital life from phishing attacks. It ensures only you can access your accounts
  • WORKS WITH 1000+ ACCOUNTS: Compatible with popular accounts like Google, Microsoft, and Apple. A single YubiKey 5 NFC secures 100+ of your favorite accounts, including email, password managers, and more
  • FAST & CONVENIENT LOGIN: Plug in your YubiKey 5 NFC via USB and tap it, or tap it against your phone (NFC), to authenticate. No batteries, no internet connection, and no extra fees required
  • MOST SECURE PASSKEY: Supports FIDO2/WebAuthn, FIDO U2F, Yubico OTP, OATH-TOTP/HOTP, Smart card (PIV), and OpenPGP. That means it’s versatile, working almost anywhere you need it
  • PRIMARY & SPARE KEYS: Just like having a spare house key, we recommend buying two YubiKeys - one for daily use and one as a spare. That way you’ll never get locked out of your accounts

Origin guard and initialization timing

The script checks window.location.hostname before writing values. This prevents the credentials from being seeded on unrelated hosts that the context might visit. The BrowserContext API says addInitScript() runs after document creation but before page scripts, including in newly created or navigated pages and frames. Register it before goto(). If you add multiple initialization scripts at context and page level, their evaluation order is not defined, so avoid relying on one script running before another.

Wait for the right page state before capturing

page.goto() reaching a navigation milestone does not necessarily mean the application has finished rendering. Choose a condition tied to the visible state you need: a known heading, account menu, loaded data element, or another site-specific signal. In the example, main is a placeholder readiness check; replace it with a selector whose visibility actually indicates that the authenticated view is ready.

Rank #4
Yubico - Security Key NFC - Basic Compatibility - Multi-Factor Authentication (MFA) Key, Connect via USB-A or NFC, FIDO Certified
  • POWERFUL SECURITY KEY: The Security Key NFC is the essential physical passkey for protecting your digital life from phishing attacks. It ensures only you can access your accounts.
  • WORKS WITH 1000+ ACCOUNTS: Compatible with Google, Microsoft, and Apple. A single Security Key NFC secures 100 of your favorite accounts, including email, password managers, and more.
  • FAST & CONVENIENT LOGIN: Plug in your Security Key NFC via USB-A and tap it, or tap it against your phone (NFC) to authenticate. No batteries, no internet connection, and no extra fees required.
  • TRUSTED PASSKEY TECHNOLOGY: Uses the latest passkey standards (FIDO2/WebAuthn & FIDO U2F) but does not support One-Time Passwords. For complex needs, check out the YubiKey 5 Series.
  • BUILT TO LAST: Made from tough, waterproof, and crush-resistant materials. Manufactured in Sweden and programmed in the USA with the highest security standards.

For pages that render asynchronously, waiting for a meaningful application signal is more reliable than immediately capturing after navigation. A full-page capture uses fullPage: true; omit it when you only want the current viewport. Playwright’s screenshot API supports page screenshots, while Puppeteer likewise documents page.screenshot() in its Page API.

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

Use Playwright storageState for repeatable authentication

When you need to reuse an authenticated setup, Playwright can save context state with storageState() and use that state to populate another context. Its documented storage state covers cookies, local storage, IndexedDB, and virtual WebAuthn credentials; sessionStorage still needs a separate save-and-restore step. The authentication guide demonstrates restoring sessionStorage with a hostname check.

Best Value
FIDO2 U2F Security Key Passkey Two-Factor Authentication (2FA) USB Key PIN+Touch (Non-Biometric) USB-A Type TrustKey T110
  • Security Key : Protect your online accounts against unauthorized access by using FIDO2 and U2F authentication with T110. It's the world's most protective security key that works with windows, Mac OS, Linux as well as Chrome, Firefox, Edge and many other major browsers.
  • Certified with the new FIDO2 standard, T110 provides the benefit of fast login and strong protection against phishing, account takeover as well as many other online attactks.
  • Works with : Bank of America, Github, Google, Microsoft, DUO, Twitter, Facebook, Dropbox, Apple, ebay, BINANCE, mor and more.
  • Fits USB-A port : Insert the T110 security key into the USB-A port of each service and log in conveniently with one touch
  • For the driver download and user guide, please visit TrustKey Solutions Home support page.

Saved authentication state can contain sensitive cookies and headers that grant account access. Keep state files out of public repositories and restrict access to them; use a limited test account when practical. For one-off or custom state, explicit cookie insertion plus the initialization script above makes the setup visible in the test code.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Using Puppeteer instead

Puppeteer’s browser-management documentation describes browser contexts as isolated sessions: cookies and local storage are not shared between contexts. Its Page API provides page.screenshot(). The setup concept is therefore to create the intended context, arrange authentication state before application code relies on it, navigate, wait for the target UI, and capture. This guide does not assume a particular Puppeteer API for seeding sessionStorage; check the documentation for the Puppeteer version you are using and verify the value is present before relying on it.

For Chrome’s headless behavior itself, consult the Chrome Headless documentation. Browser automation APIs and their storage behavior are the parts that determine how you prepare this capture.

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.

Troubleshooting common failures

  • The page redirects to login: Confirm that the cookie name, value, domain, path, and security attributes match the target site and that the cookie belongs to the host you are visiting. Check whether the application also requires a sessionStorage value or another authentication step.
  • The app behaves as if sessionStorage is empty: Ensure addInitScript() is registered before navigation, the hostname guard matches the page’s hostname exactly, and the values supplied through SESSION_STORAGE_JSON are valid JSON strings. Remember that sessionStorage is scoped to the page origin.
  • The screenshot shows a loading shell or incomplete data: Replace the example readiness selector with one that appears only when the desired authenticated content is rendered. Navigation completion alone may not be the application’s ready signal.
  • Cookie works on one host but not a subdomain: Recheck the cookie domain and scope. A cookie only applies where its domain and path allow it; use a leading dot only when the intended subdomain coverage calls for it.
  • Authentication state leaks or is committed: Remove state files from version control, keep them in a protected local location, and rotate credentials if a usable session value was exposed. Playwright cautions that stored authentication state is sensitive.
  • Different setup scripts appear to race: Do not depend on ordering among multiple context-level and page-level initialization scripts; the API does not define their relative evaluation order. Consolidate dependent setup into one script.

Or skip the browser setup

If you do not need to seed a private authenticated session yourself, ScreenshotNeo can return a screenshot with one GET request. Its documented features include accepting cookie/consent banners and removing 60+ known consent platforms, newsletter popups, and chat widgets before capture; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed. It also offers an MCP server for AI agents, and 1,000 screenshots a month are free without a card, with paid plans starting at $5 for 3,000 shots. See ScreenshotNeo and the 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

Use your ScreenshotNeo API key in place of YOUR_API_KEY and the page URL you want to capture. Sign up free for 1,000 screenshots a month with no card.

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
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.