Playwright is a powerful tool for browser automation, and one of its lesser-known features is the ability to run tests using existing browser profiles. This can be incredibly useful when you need to test scenarios that require specific browser configurations, extensions, or saved login states. In this article, we'll explore how to use Playwright to launch Microsoft Edge or Google Chrome with custom profiles.
Setting Up the Environment
Before we dive into the code, make sure you have Playwright installed in your project:
npm install @playwright/test
Create a file named codegen.mjs
in your project directory. We'll use this file to run our Playwright scripts.
Launching a Browser with the Default Profile
Let's start with a basic example that launches Microsoft Edge with the default profile:
import { chromium } from '@playwright/test';
(async () => {
const context = await chromium.launchPersistentContext('C:\\Users\\YourUsername\\AppData\\Local\\Microsoft\\Edge\\User Data', {
headless: false,
channel: 'msedge',
});
// For macOS, use:
// Microsoft Edge: '/Users/YourUsername/Library/Application Support/Microsoft Edge'
// Google Chrome: '/Users/YourUsername/Library/Application Support/Google/Chrome'
const page = context.pages()[0];
await page.pause(); // This will open Codegen if needed
await context.close();
})();
This script does the following:
- Imports the
chromium
object from Playwright. - Launches a persistent context using the default Edge profile.
- Gets the first page from the context.
- Pauses the execution, which opens the Playwright Inspector (Codegen) for interactive debugging.
- Closes the context when done.
Using a Specific Browser Profile
To use a different profile, we need to add the --profile-directory
argument. The profile directory might be different to the profile
name. In order to find out the profile directory, you can navigate to chrome://version
in the browser and look for the Profile Path
field. The last part of the path is the profile directory name.
import { chromium } from '@playwright/test';
(async () => {
// Setup
const context = await chromium.launchPersistentContext('C:\\Users\\YourUsername\\AppData\\Local\\Microsoft\\Edge\\User Data', {
headless: false,
channel: 'msedge',
args: [`--profile-directory=Profile 2`]
});
// For macOS, use:
// Microsoft Edge: '/Users/YourUsername/Library/Application Support/Microsoft Edge'
// Google Chrome: '/Users/YourUsername/Library/Application Support/Google/Chrome'
const page = context.pages()[0];
await page.pause();
await context.close();
})();
The key difference here is the args
option in the launchPersistentContext
method, which specifies the profile directory to use.
Remember to replace YourUsername
with your actual username on your system.
Using Playwright Codegen
In both examples, we've included await page.pause();
. This line opens the Playwright Inspector, also known as Codegen. This tool allows you to:
- Inspect the page structure
- Record actions and generate code
- Step through your script
- Modify and rerun parts of your script
Running the Script
To run the script, use the following command in your terminal:
node codegen.mjs
Important Notes
Profile Availability: Ensure that the browser profile you're trying to use isn't already open. If it is, Playwright won't be able to launch it.
Profile Names: The profile directory names (e.g., "Profile 2") should match exactly with the names in your browser's profile directory.
Browser Channel: In our examples, we've used
channel: 'msedge'
for Microsoft Edge. For Google Chrome, you would usechannel: 'chrome'
. Make sure to adjust the profile path accordingly.Path Accuracy: Double-check that the path to your browser's user data directory is correct. It may vary depending on your operating system and browser version.
Top comments (2)
Thank you very much for the contribution
To add to 1. Profile Availability: Ensure that the browser profile you're trying to use isn't already open. If it is, Playwright won't be able to launch it.
I had to terminate all Microsoft Edge tasks via the task manager in order to fulfill this instruction. It wasn't enough just to make sure that Edge was no longer open in the taskbar.
The error message was:
node:internal/process/promises:394
triggerUncaughtException(err, true /* fromPromise */);
^
browserType.launchPersistentContext: Target page, context or browser has been closed
Browser logs:
C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe --disable-field-trial-config --disable-background-networking --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-back-forward-cache --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-component-update --no-default-browser-check --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync,Translate,HttpsUpgrades,PaintHolding,ThirdPartyStoragePartitioning,LensOverlay,PlzDedicatedWorker --allow-pre-commit-input --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --force-color-profile=srgb --metrics-recording-only --no-first-run --enable-automation --password-store=basic --use-mock-keychain --no-service-autorun --export-tagged-pdf --disable-search-engine-choice-screen --unsafely-disable-devtools-self-xss-warnings --no-sandbox --user-data-dir=C:\Users<michael's user>\AppData\Local\Microsoft\Edge\User Data --remote-debugging-pipe about:blank
pid=14096
[pid=14096]
[pid=14096] starting temporary directories cleanup
Call log:
[pid=14096] starting temporary directories cleanup
at C:\Users<michael's user>\Documents\myProject\async file:\C:\Users<michael's user>\Documents\myProject\codegen.mjs:5:19
Node.js v22.12.0