Skip to content

Instantly share code, notes, and snippets.

@digitalchild
Created June 24, 2025 04:24
Show Gist options
  • Save digitalchild/16fbd486a80de6783b5ae9b2e91b6216 to your computer and use it in GitHub Desktop.
Save digitalchild/16fbd486a80de6783b5ae9b2e91b6216 to your computer and use it in GitHub Desktop.
Playwright session persistance
const { chromium } = require('playwright');
async function createPersistentSession() {
// Create a persistent context (saves cookies, localStorage, etc.)
const context = await chromium.launchPersistentContext('./user-data', {
headless: false, // Set to true for production
viewport: { width: 1920, height: 1080 },
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
args: [
'--disable-blink-features=AutomationControlled',
'--disable-features=VizDisplayCompositor',
'--no-first-run',
'--disable-default-apps'
]
});
// Anti-detection setup
await context.addInitScript(() => {
Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
window.chrome = { runtime: {} };
Object.defineProperty(navigator, 'plugins', {
get: () => [1, 2, 3, 4, 5]
});
});
const page = await context.newPage();
// First request - establish session
await page.goto('https://example.com');
await page.waitForTimeout(2000);
return { context, page };
}
// Usage for subsequent requests
async function useExistingSession() {
const context = await chromium.launchPersistentContext('./user-data', {
headless: true // Session data persists
});
const page = await context.newPage();
await page.goto('https://example.com/protected-page');
return page;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment