The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →To use a logged-in session in headless Chrome, choose the method that matches where the session lives: launch Playwright with a dedicated persistent profile for ongoing browser continuity, save and reload Playwright storageState for repeatable isolated runs, or connect over Chrome DevTools Protocol (CDP) to a Chromium browser that is already logged in. Do not point automation at your everyday Chrome profile: Playwright warns this can prevent pages from loading or cause the browser to exit.
Choose the right way to reuse the session
“Headless” describes a browser running without its normal visible window; it does not, by itself, carry a login from one run to another. Your automation must either use browser data where the login is stored or connect to the process that already owns the session. The three approaches differ in how they persist state and how much of the existing browser they expose to your code.
| Approach | Best fit | What it reuses | Isolation and trade-off |
|---|---|---|---|
| Dedicated persistent profile | Repeated runs that should continue using the same automation account | A user-data directory, including browser session data such as cookies and local storage | Continuity is convenient, but the profile is stateful and only one browser instance can own a user-data directory at a time. |
storageState |
Reproducible tests or jobs that should start in a clean context | A saved snapshot of supported authentication state, including cookies and origin data | Easy to copy into a new context, but the file is a sensitive credential and can expire. |
| CDP attachment | Automation that must work with a Chromium process and live tabs already open | The existing browser process and its contexts | It does not create a fresh isolated browser context; anyone who can reach the debugging endpoint may control that browser. |
Use a separate profile or state file for each account. This keeps identities from bleeding into one another and makes it clearer which credentials a job is using.
Option 1: Keep a dedicated persistent profile
Playwright’s launchPersistentContext(userDataDir) opens a browser using a user-data directory that retains browser data between runs. Create a directory solely for automation; never substitute the profile directory used by ordinary Chrome browsing. Persistent contexts are useful when you want the browser to keep its own cookies and local storage rather than exporting and importing a state file.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11#1 Best Overall
- CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
- WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
- A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
Install Playwright and create the profile
In a new project, install Playwright and its Chromium browser:
npm init -y
npm install playwright
npx playwright install chromium
Save this as persistent-login.js. On its first run, it opens a visible browser so you can log in interactively; later runs launch that same dedicated profile in headless mode.
const { chromium } = require('playwright');
const path = require('path');
(async () => {
const userDataDir = path.resolve(__dirname, 'playwright', 'automation-profile');
const context = await chromium.launchPersistentContext(userDataDir, {
headless: process.env.HEADLESS === '1',
});
try {
const page = context.pages()[0] || await context.newPage();
await page.goto('https://example.com/login', { waitUntil: 'domcontentloaded' });
if (process.env.HEADLESS !== '1') {
console.log('Log in in the opened browser, then press Enter here to continue.');
await new Promise(resolve => process.stdin.once('data', resolve));
}
await page.goto('https://example.com/account', { waitUntil: 'domcontentloaded' });
console.log('Current URL:', page.url());
} finally {
await context.close();
}
})();
Replace both example URLs with the site’s login and authenticated destination. Run node persistent-login.js for the interactive login. Once the site has completed its redirects and established the session, run HEADLESS=1 node persistent-login.js on macOS or Linux to reuse the profile without a visible window. In Windows PowerShell, set the environment variable for that invocation with $env:HEADLESS='1'; node persistent-login.js.
Do not start two browser processes against this same directory. Browsers do not allow multiple instances to launch with one user-data directory; concurrent runs should use separate directories or a different approach. Close the persistent context after work so it releases the profile for the next run.
Rank #2
- CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
- SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
Option 2: Save and restore Playwright storageState
A state file separates the interactive login step from later automation. Log in once in a headed browser, save the context state after authentication finishes, and load that file into new contexts as needed. This is usually the better choice when each test or job should start with a fresh context rather than a long-lived profile.
Capture the state after login
Save this as save-auth.js. It pauses at the terminal while you complete login; press Enter only after any redirects are complete and the account page is available.
const { chromium } = require('playwright');
const fs = require('fs');
const path = require('path');
(async () => {
const authDir = path.resolve(__dirname, 'playwright', '.auth');
fs.mkdirSync(authDir, { recursive: true });
const browser = await chromium.launch({ headless: false });
const context = await browser.newContext();
const page = await context.newPage();
try {
await page.goto('https://example.com/login', { waitUntil: 'domcontentloaded' });
console.log('Complete login in the browser, then press Enter here.');
await new Promise(resolve => process.stdin.once('data', resolve));
await page.goto('https://example.com/account', { waitUntil: 'domcontentloaded' });
await context.storageState({ path: path.join(authDir, 'user.json') });
console.log('Saved Playwright state.');
} finally {
await browser.close();
}
})();
Then create a new context from the saved file:
const { chromium } = require('playwright');
const path = require('path');
(async () => {
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({
storageState: path.resolve(__dirname, 'playwright', '.auth', 'user.json'),
});
try {
const page = await context.newPage();
await page.goto('https://example.com/account', { waitUntil: 'domcontentloaded' });
console.log('Current URL:', page.url());
} finally {
await browser.close();
}
})();
These examples use CommonJS and the Playwright package installed above. Add the auth directory to .gitignore before saving credentials:
playwright/.auth/
The default state snapshot covers cookies and local storage. Playwright’s BrowserContext reference also describes support for IndexedDB, origin private file system data, and virtual WebAuthn credentials; enable relevant options for the Playwright version you use if your application relies on IndexedDB tokens or passkey-based authentication. Consult the installed version’s API reference for the precise option names rather than assuming a state file captures every browser storage mechanism.
Rank #3
- Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
- Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
- Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
- In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
- Ultra-thin bezels: Maximize your viewing experience with thin bezels.
SessionStorage needs separate handling
SessionStorage is domain-specific and is not included by Playwright’s direct state persistence API. The documented workaround is to serialize it from a page with page.evaluate, then restore it using context.addInitScript before the application starts. The initializer needs to run before page application code reads sessionStorage; adding it after navigation is too late. Treat this serialized data with the same care as the state file because it may include authentication material.
Option 3: Attach to an already logged-in Chromium browser
Use CDP when a Chromium process already has the profile, tabs, or live session you need. Unlike persistent-profile launch and storageState restoration, this attaches Playwright to the running browser rather than creating a fresh isolated context. Playwright documents connectOverCDP for Chromium-based browsers only.
Start Chromium with a protected debugging endpoint
Launch a dedicated Chromium process with a separate profile and a local debugging port. For example, on Linux:
chromium --remote-debugging-port=9222
--user-data-dir="$HOME/chrome-automation-profile"
https://example.com/login
Complete login in that browser window. Then use the browser’s local CDP endpoint from Playwright:
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Rank #4
- CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
- SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
- MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
- KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
- INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.connectOverCDP('http://localhost:9222');
const contexts = browser.contexts();
if (contexts.length === 0) {
throw new Error('No browser context is available at the CDP endpoint.');
}
const context = contexts[0];
const page = context.pages()[0] || await context.newPage();
try {
await page.goto('https://example.com/account', { waitUntil: 'domcontentloaded' });
console.log('Current URL:', page.url());
} finally {
await browser.close();
}
})();
CDP attachment is convenient for an existing live session, but it gives the attached automation access to that browser context. Treat the endpoint as highly trusted: bind it to a protected local interface, do not expose it publicly, and do not allow untrusted processes to connect. Close the browser process itself when its owner is finished; the attachment code’s browser handle is not a reason to make the debugging port generally available.
Protect authentication artifacts
A profile directory, state JSON, cookies, bearer headers, passkey credentials, and a CDP endpoint are all ways to exercise account access. Playwright explicitly warns that a state file can contain sensitive cookies and headers that could impersonate a user or test account. Apply the same controls you would apply to a password:
- Keep auth directories and state files out of version control, shared build artifacts, and public logs.
- Restrict filesystem permissions to the user or service that runs the automation.
- Use distinct profiles or state files for distinct accounts and environments.
- Delete or regenerate state when it expires or the account’s access should be revoked.
- Limit access to the machine and processes that can reach a CDP debugging endpoint.
Troubleshoot failed session reuse
- The page redirects to login: Confirm the login flow completed before saving state, then check whether the website expires or revokes the session. Reauthenticate and replace the stale state or profile data.
- The saved file exists but the site is still logged out: The login may depend on IndexedDB, sessionStorage, or another origin-specific mechanism rather than only cookies and local storage. Check which storage the application uses; enable supported IndexedDB snapshotting where appropriate, or implement the sessionStorage serialization and initialization workaround.
- Persistent-profile pages fail to load or Chrome exits: Verify that automation uses its own user-data directory, not your regular Chrome “User Data” directory. Check that another browser process is not already using the automation directory.
- CDP connection is refused: Confirm Chromium was started with the debugging port, that it is still running, and that the client is connecting to the same local endpoint. CDP attachment is for Chromium-based browsers.
- Automation reaches the wrong account: Check which profile or state file the run opened. Do not share one directory or state snapshot across accounts; create distinct artifacts and pass the intended one explicitly.
- Login works interactively but not in a later run: Make sure the script reuses the same persistent directory or loads the saved state file. Logging in in one temporary context does not automatically populate a different context.
Or skip the browser setup
If the goal is a screenshot of a public page rather than operating an already logged-in browser session, ScreenshotNeo can return an image or PDF from one GET request. It does not replace Playwright profile reuse or CDP attachment when your task depends on driving the live authenticated session. See the ScreenshotNeo API documentation for request options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
In this example, replace the target URL with the page you want to capture. ScreenshotNeo’s clean-shot flow accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and responses identify the page verdict and billing status in headers. Its MCP server offers take_screenshot, get_page_info, and capture_pdf for AI agents and MCP clients. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.
Free tools Windows power users keep installed
One-click scans. No signup required.
Sign up free for 1,000 screenshots a month with no card.
Best Value
- 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
- 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
- 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
Frequently Asked Questions
Can I use the saved Playwright state in another test project?
Yes. A project can load the same state file when it should use the same account, provided the file is kept private and the session remains valid.
Can the CDP method attach to Firefox or WebKit?
No. Playwright’s documented CDP connection support applies to Chromium-based browsers.
Will sessionStorage be restored by passing storageState?
No. Playwright does not provide direct sessionStorage persistence through storageState; it needs the serialize-and-initialize workaround described above.
Quick Recap
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.

