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 desk7 min

How to Capture a Webpage Screenshot with an AI Agent Using Authenticated Cookies

A practical Playwright workflow for an AI agent to authenticate, verify a protected page, and save the right screenshot without exposing browser state.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use an authorized Playwright browser context to sign in, confirm the protected page has loaded, and then capture it with page.screenshot(). Playwright’s reusable authentication state can include more than cookies, so the right setup depends on how the site authenticates you. Keep that state private: anyone who obtains it may be able to act as your account.

How the workflow fits together

An AI agent can direct browser automation, but the browser still needs a legitimate signed-in session. The dependable sequence is:

As an Amazon Associate I earn from qualifying purchases.

  1. Authenticate: sign in through the site’s normal flow in an isolated browser context, or load a previously saved state for an authorized account.
  2. Verify: navigate to the target and check that the expected signed-in page—not a login redirect or error—has loaded.
  3. Capture: choose viewport, full-page, or clipped output, then save the screenshot and handle it as private data if appropriate.

Playwright’s authentication guide describes saving and reusing browser state. Its BrowserContext documentation explains isolated contexts, and the Page API documents screenshot options.

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

What “authenticated cookies” means in Playwright

Cookies are only one possible part of an authenticated session. Playwright storage state can include cookies, local storage, IndexedDB, and passkey-related state, depending on the site’s authentication model. A site may also rely on session storage; the standard storage-state method does not persist it. If reusing saved state still leads to a login page, investigate the site’s authentication requirements rather than assuming the screenshot call is at fault.

#1 Best Overall
Sale
Samsung Galaxy A17 5G Smart Phone 128GB US 1 Yr Manufacturer Warranty Black | Large AMOLED, High-Res Camera, Durable Design, Super Fast Charging, Expandable Storage, Circle to Search, 2025
  • YOUR CONTENT, SUPER SMOOTH: The ultra-clear 6.7" FHD+ Super AMOLED display of Galaxy A17 5G helps bring your content to life, whether you're scrolling through recipes or video chatting with loved ones.¹
  • LIVE FAST. CHARGE FASTER: Focus more on the moment and less on your battery percentage with Galaxy A17 5G. Super Fast Charging powers up your battery so you can get back to life sooner.²
  • MEMORIES MADE PICTURE PERFECT: Capture every angle in stunning clarity, from wide family photos to close-ups of friends, with the triple-lens camera on Galaxy A17 5G.
  • NEED MORE STORAGE? WE HAVE YOU COVERED: With an improved 2TB of expandable storage, Galaxy A17 5G makes it easy to keep cherished photos, videos and important files readily accessible whenever you need them.³
  • BUILT TO LAST: With an improved IP54 rating, Galaxy A17 5G is even more durable than before.⁴ It’s built to resist splashes and dust and comes with a stronger yet slimmer Gorilla Glass Victus front and Glass Fiber Reinforced Polymer back.

Set up a private, reusable signed-in state

This example signs in through the site’s normal UI, waits for a reliable signed-in signal, then writes storage state for a later capture. Replace the example URL, selectors, and credentials source with values appropriate to your application. Do not put a real password directly in source code.

  1. Install Playwright for Node.js with npm install playwright and install the browser you intend to use, for example npx playwright install chromium.
  2. Provide credentials through your approved secret store or environment. The example reads APP_USERNAME and APP_PASSWORD.
  3. Run the script once, then reuse the generated state only in a suitably protected environment.
const { chromium } = require('playwright');

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

  try {
    await page.goto('https://example.com/login', { waitUntil: 'domcontentloaded' });
    await page.getByLabel('Email').fill(process.env.APP_USERNAME);
    await page.getByLabel('Password').fill(process.env.APP_PASSWORD);
    await page.getByRole('button', { name: 'Sign in' }).click();

    // Replace this with a stable signal that only appears when signed in.
    await page.getByRole('link', { name: 'Account' }).waitFor({ state: 'visible' });
    await context.storageState({ path: 'playwright/.auth/state.json' });
  } finally {
    await browser.close();
  }
})();

The login page labels and post-login signal above are illustrative; use the actual accessible labels and a page-specific indicator. Waiting for a signed-in signal helps avoid saving state before redirects or authentication cookies have completed.

Rank #2
Tracfone Motorola Moto G 2025, 64GB, Saphire Blue (Locked to
  • Carrier: This phone is locked to Tracfone, which means this device can only be used on the Tracfone wireless network. Tracfone plan required, activating is easy, just 3 steps.
  • DISPLAY: Immersive viewing on a 6.7-inch super-bright 120Hz display with powerful stereo speakers and Bass Boost for cinematic entertainment.
  • CAMERA SYSTEM: Advanced 50MP Quad Pixel camera captures sharp, detailed photos and videos in any lighting condition
  • PERFORMANCE: Lightning-fast 5G connectivity paired with a powerful processor and RAM Boost for smooth multitasking.
  • BATTERY LIFE: Long-lasting 5000mAh battery with TurboPower charging technology delivers hours of power in minutes.

Protect the state file

Playwright warns: “The browser state file may contain sensitive cookies and headers that could be used to impersonate you or your test account.” Keep it out of source control, restrict who and what can read it, and remove or refresh it when it expires or is no longer needed. Treat it like a credential, not a harmless test artifact.

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

Load the state, verify the target, and take the screenshot

Use a fresh context initialized with the saved state. The verification step should check a target-specific element or URL; a screenshot of a login redirect is a valid image file but not the intended result.

Rank #3
Sale
Samsung Galaxy A17 5G Smart Phone 128GB, US 1 Yr Manufacturer Warranty Blue | Large AMOLED, High-Res Camera, Durable Design, Super Fast Charging, Expandable Storage, Circle to Search, 2025
  • YOUR CONTENT, SUPER SMOOTH: The ultra-clear 6.7" FHD+ Super AMOLED display of Galaxy A17 5G helps bring your content to life, whether you're scrolling through recipes or video chatting with loved ones.¹
  • LIVE FAST. CHARGE FASTER: Focus more on the moment and less on your battery percentage with Galaxy A17 5G. Super Fast Charging powers up your battery so you can get back to life sooner.²
  • MEMORIES MADE PICTURE PERFECT: Capture every angle in stunning clarity, from wide family photos to close-ups of friends, with the triple-lens camera on Galaxy A17 5G.
  • NEED MORE STORAGE? WE HAVE YOU COVERED: With an improved 2TB of expandable storage, Galaxy A17 5G makes it easy to keep cherished photos, videos and important files readily accessible whenever you need them.³
  • BUILT TO LAST: With an improved IP54 rating, Galaxy A17 5G is even more durable than before.⁴ It’s built to resist splashes and dust and comes with a stronger yet slimmer Gorilla Glass Victus front and Glass Fiber Reinforced Polymer back.
const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({
    storageState: 'playwright/.auth/state.json'
  });
  const page = await context.newPage();

  try {
    await page.goto('https://example.com/account/report', { waitUntil: 'domcontentloaded' });
    await page.getByRole('heading', { name: 'Account report' }).waitFor({ state: 'visible' });

    await page.screenshot({ path: 'page.png', fullPage: true });
  } finally {
    await browser.close();
  }
})();

Replace the URL and heading with the protected destination and a reliable marker for its intended signed-in view. If the page renders essential content after the initial document load, wait for that content or another reliable readiness signal before capturing.

Choose the screenshot scope and appearance

page.screenshot() supports several useful choices. Pick them based on what the recipient needs, since full-page and device-scale captures can produce much larger images than a viewport capture.

Rank #4
Sale
Samsung Galaxy S26 Ultra, Unlocked Android Smartphone, 512GB, Black | Privacy Display, Galaxy AI, AI Camera, Super Fast Charging 3.0, Durable Battery, 2026, US 1 Year Warranty
  • PRIVACY DISPLAY: Automatically hide your screen from those beside you. The built-in privacy display can be preset¹ to turn on when receiving notifications, typing passwords, or using specific apps
  • TYPE IT IN. TRANSFORM IT FAST: Enhance any shot in seconds on your smartphone by using Photo Assist² with Galaxy AI.³ Add objects, restore details, or apply new styles by simply typing or tapping
  • NIGHTS, CAPTURED CLEARLY: From gigs to city lights, record and capture moments after dark with clarity using Nightography so your photos and videos stay crisp and clear on your Samsung Galaxy
  • MAKE IT. EDIT IT. SHARE IT: Turn everyday moments into something personal with creative tools built right into your mobile phone, whether it’s a special contact photo, custom wallpaper, an invitation or more⁴
  • HELP THAT KEEPS UP: Stay in the moment while Now Nudge with Galaxy AI helps you respond faster and stay organized with smart suggestions⁵ that appear exactly when you need them on your phone
Need Option Effect
Only what is currently visible Default screenshot Captures the viewport.
All scrollable page content fullPage: true Captures the full page; very long pages can create very tall images.
A defined rectangular area clip Limits output to a specified rectangle.
Control output destination or format path and type Set a file path and image type as needed.
Choose image density scale: 'css' | 'device' CSS scale uses one image pixel per CSS pixel; device scale uses device-pixel ratio and can yield larger output.
Reduce movement in the image animations: 'disabled' Disables animations during capture; this changes their behavior rather than preserving a particular animated moment.
Obscure matching visible content mask with locators Covers matching elements in the screenshot, but does not sanitize the page or browser-state file.

For example, a clipped viewport capture can be written as:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
await page.screenshot({
  path: 'account-panel.png',
  type: 'png',
  clip: { x: 0, y: 0, width: 900, height: 600 },
  animations: 'disabled'
});

To capture a full page while masking a visible account identifier, first create a locator for the relevant element and pass it in mask:

Best Value
Tracfone Moto g Play 2024 Prepaid Phone with a 1-Yr Plan Included
  • Carrier: This phone is locked to Tracfone, which means this device can only be used on the Tracfone wireless network. Activating is easy, just 3 steps.
  • ACTIVATION Promotion: Includes 1500 min, 1500 texts & 1500 MB Data + add more as you need it
  • CAMERA SYSTEM: 50MP Quad Pixel camera. Capture sharper, more vibrant photos day or night with 4x the light sensitivity.
  • PERFORMANCE: Blazing-fast Qualcomm performance. Get the speed you need for great entertainment with a Snapdragon 680 processor and 4GB of RAM.
  • 64GB built-in storage. Get plenty of room for photos, movies, songs, and apps. Made for US
await page.screenshot({
  path: 'report.png',
  fullPage: true,
  mask: [page.locator('[data-private-account-id]')]
});

A mask only changes pixels in the screenshot; it does not redact other files, page data, cookies, or authentication state.

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

Make the workflow safe for an AI agent

  • Use an account and target page you are authorized to access; the Playwright documentation describes browser mechanics, not a universal authorization policy for every site or agent.
  • Give the agent only the browser actions and files needed for this task. Avoid exposing saved state in prompts, logs, source repositories, or shared artifacts.
  • Check page identity and signed-in status before capture. Prefer a stable page-specific locator over relying only on a URL, since redirects can vary.
  • Store and share the resulting image with care when it contains private page content. Masking can hide selected visible elements in the image, but does not protect the underlying browser state.
  • Use a separate browser context for the task. Playwright contexts are isolated sessions, and non-persistent contexts do not write browsing data to disk unless you explicitly save data such as storage state.

Troubleshooting common failures

Symptom Likely cause What to check
The target shows a login page State is expired, incomplete, or the site uses authentication data not restored by standard storage state. Sign in again, wait for a reliable signed-in signal before saving state, and check whether the site depends on session storage or another site-specific mechanism.
The state file exists but is not accepted It may have been created before authentication finished, or it may no longer be valid. Repeat the normal sign-in flow and save only after the authenticated UI appears. Keep state files current and protected.
The screenshot is blank or missing page content The capture happened before the relevant content rendered, or the wrong destination loaded. Verify the URL and wait for the specific content element that marks page readiness before calling screenshot().
Only part of the page appears The default captures the viewport, or a clip rectangle restricts the output. Use fullPage: true for all scrollable content, or adjust/remove clip when only a region was not intended.
Private details are visible in the output The capture was not masked, or the chosen locator did not match the sensitive element. Check the locator and apply a screenshot mask; remember this does not redact the state file or other artifacts.
Output is unexpectedly large The page is unusually tall or device-scale output has more pixels. Capture the viewport or a clip instead, or choose CSS scale when device-pixel density is unnecessary.

Or skip the browser setup

For a public page, ScreenshotNeo can return an image or PDF from one GET request. Its clean-shot steps accept cookie or consent banners like a visitor and remove more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response identifies the page verdict and billing status in headers. ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for AI agents.

This is not a substitute for signing in to a protected page: the stated API facts do not establish a way to provide this workflow’s authenticated browser state to ScreenshotNeo. For the authenticated page in this guide, use the Playwright context above. For a page the API can access, the call is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo documentation for request details. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Learn about ScreenshotNeo or sign up for 1,000 free screenshots a month, with no card.

Frequently asked questions

Can an AI agent reuse my browser login without storing a password?

It can reuse saved browser state rather than repeat a password-based login, but that state may itself allow account impersonation. Protect it accordingly and use an authorized account.

Will a screenshot mask hide the private data from the website?

No. A mask covers matching pixels in the screenshot only; it does not change what the page loaded or protect the saved authentication state.

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.

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

Leave a Reply

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

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.

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
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

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.