Electron
Added in: v1.9Playwright has experimental support for Electron automation. You can access electron namespace via:
const { _electron } = require('playwright');An example of the Electron automation script would be:
const { _electron: electron } = require('playwright');
(async () => {
// Launch Electron app.
const electronApp = await electron.launch({ args: ['main.js'] });
// Evaluation expression in the Electron context.
const appPath = await electronApp.evaluate(async ({ app }) => {
// This runs in the main Electron process, parameter here is always
// the result of the require('electron') in the main app script.
return app.getAppPath();
});
console.log(appPath);
// Get the first window that the app opens, wait if necessary.
const window = await electronApp.firstWindow();
// Print the title.
console.log(await window.title());
// Capture a screenshot.
await window.screenshot({ path: 'intro.png' });
// Direct Electron console to Node terminal.
window.on('console', console.log);
// Click button.
await window.click('text=Click me');
// Exit app.
await electronApp.close();
})();Supported Electron versions are:
- v21+
Known issues:
If you are not able to launch Electron and it will end up in timeouts during launch, try the following:
- Ensure that
nodeCliInspect(FuseV1Options.EnableNodeCliInspectArguments) fuse is not set tofalse.
Mocking native dialogs:
Playwright does not intercept the native Electron dialog API (dialog.showOpenDialog, dialog.showSaveDialog, dialog.showMessageBox, etc.) because those calls happen in the Electron main process and go straight to OS APIs. Use electronApplication.evaluate() to replace the relevant methods in the main process so tests run deterministically without any OS-level UI:
// Stub the open dialog to always return a fixed path.
await electronApp.evaluate(({ dialog }, filePaths) => {
dialog.showOpenDialog = () => Promise.resolve({ canceled: false, filePaths });
}, ['/path/to/file.txt']);
// Stub the save dialog.
await electronApp.evaluate(({ dialog }, filePath) => {
dialog.showSaveDialog = () => Promise.resolve({ canceled: false, filePath });
}, '/path/to/saved.txt');
// Stub showMessageBox to click the first button.
await electronApp.evaluate(({ dialog }) => {
dialog.showMessageBox = () => Promise.resolve({ response: 0, checkboxChecked: false });
});The replacement persists until the application is closed. Synchronous variants (showOpenDialogSync, showSaveDialogSync, showMessageBoxSync) can be stubbed the same way — just return the value directly instead of a Promise.
Methods
electron.launch()
Added in: v1.9 asyncLaunches electron application specified with the executablePath.
Arguments
acceptDownloadsboolean(optional) Added in: v1.12Whether to automatically download all the attachments. Defaults to
truewhere all the downloads are accepted.Additional arguments to pass to the application when launching. You typically pass the main script name here.
artifactsDirpath(optional) Added in: v1.59If specified, artifacts (traces, videos, downloads, HAR files, etc.) are saved into this directory. The directory is not cleaned up when the browser closes. If not specified, a temporary directory is used and cleaned up when the browser closes.
bypassCSPboolean(optional) Added in: v1.12Toggles bypassing page's Content-Security-Policy. Defaults to
false.chromiumSandboxboolean(optional) Added in: v1.59Enable Chromium sandboxing. Defaults to
false.colorSchemenull | "light" | "dark" | "no-preference"(optional) Added in: v1.12Emulates prefers-colors-scheme media feature, supported values are
'light'and'dark'. Seepage.emulateMedia()for more details. Passingnullresets emulation to system defaults. Defaults to'light'.Current working directory to launch application from.
envObject<string, string>(optional)Specifies environment variables that will be visible to Electron. Defaults to
process.env.executablePathstring(optional)Launches given Electron application. If not specified, launches the default Electron executable installed in this package, located at
node_modules/.bin/electron.extraHTTPHeadersObject<string, string>(optional) Added in: v1.12An object containing additional HTTP headers to be sent with every request. Defaults to none.
geolocationObject(optional) Added in: v1.12latitudefloatAdded in: v1.12Latitude between -90 and 90.
longitudefloatAdded in: v1.12Longitude between -180 and 180.
accuracyfloat(optional) Added in: v1.12Non-negative accuracy value. Defaults to
0.
httpCredentialsObject | Array<Object>(optional) Added in: v1.12Credentials for HTTP authentication. If no origin is specified, the username and password are sent to any servers upon unauthorized responses.
Pass an array to use different credentials for different origins. The first entry that matches the request origin is used, and entries with no origin match any request.
usernamestringAdded in: v1.12passwordstringAdded in: v1.12originstring(optional) Added in: v1.12Restrain sending http credentials on specific origin (scheme://host:port).
send"unauthorized" | "always"(optional) Added in: v1.12This option only applies to the requests sent from corresponding APIRequestContext and does not affect requests sent from the browser.
'always'-Authorizationheader with basic authentication credentials will be sent with the each API request.'unauthorized- the credentials are only sent when 401 (Unauthorized) response withWWW-Authenticateheader is received. Defaults to'unauthorized'.
ignoreHTTPSErrorsboolean(optional) Added in: v1.12Whether to ignore HTTPS errors when sending network requests. Defaults to
false.localestring(optional) Added in: v1.12Specify user locale, for example
en-GB,de-DE, etc. Locale will affectnavigator.languagevalue,Accept-Languagerequest header value as well as number and date formatting rules. Defaults to the system default locale. Learn more about emulation in our emulation guide.offlineboolean(optional) Added in: v1.12Whether to emulate network being offline. Defaults to
false. Learn more about network emulation.recordHarObject(optional) Added in: v1.12Enables HAR recording for all pages into
recordHar.pathfile. If not specified, the HAR is not recorded. Make sure to awaitbrowserContext.close()for the HAR to be saved.omitContentboolean(optional) Added in: v1.12Optional setting to control whether to omit request content from the HAR. Defaults to
false. Deprecated, usecontentpolicy instead.content"omit" | "embed" | "attach"(optional) Added in: v1.12Optional setting to control resource content management. If
omitis specified, content is not persisted. Ifattachis specified, resources are persisted as separate files or entries in the ZIP archive. Ifembedis specified, content is stored inline the HAR file as per HAR specification. Defaults toattachfor.zipoutput files and toembedfor all other file extensions.pathpathAdded in: v1.12Path on the filesystem to write the HAR file to. If the file name ends with
.zip,content: 'attach'is used by default.mode"full" | "minimal"(optional) Added in: v1.12When set to
minimal, only record information necessary for routing from HAR. This omits sizes, timing, page, cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults tofull.urlFilterstring | RegExp(optional) Added in: v1.12A glob or regex pattern to filter requests that are stored in the HAR. When a
baseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor. Defaults to none.
recordVideoObject(optional) Added in: v1.12Enables video recording for all pages into
recordVideo.dirdirectory. If not specified videos are not recorded. Make sure to awaitbrowserContext.close()for videos to be saved.dirpath(optional) Added in: v1.12Path to the directory to put videos into. If not specified, the videos will be stored in
artifactsDir(seebrowserType.launch()options).sizeObject(optional) Added in: v1.12Optional dimensions of the recorded videos. If not specified the size will be equal to
viewportscaled down to fit into 800x800. Ifviewportis not configured explicitly the video size defaults to 800x450. Actual picture of each page will be scaled down if necessary to fit the specified size.widthintAdded in: v1.12Video frame width.
heightintAdded in: v1.12Video frame height.
fpsint(optional) Added in: v1.12Frame rate of the recorded videos in frames per second. Defaults to
25. Firefox and WebKit currently capture up to 25 frames per second.showActionsObject(optional) Added in: v1.12If specified, enables visual annotations on interacted elements during video recording.
durationfloat(optional) Added in: v1.12How long each annotation is displayed in milliseconds. Defaults to
500.position"top-left" | "top" | "top-right" | "bottom-left" | "bottom" | "bottom-right"(optional) Added in: v1.12Position of the action title overlay. Defaults to
"top-right".fontSizeint(optional) Added in: v1.12Font size of the action title in pixels. Defaults to
24. Deprecated, usestyle.titleinstead.cursor"none" | "pointer"(optional) Added in: v1.12Cursor decoration shown for pointer actions.
"pointer"(the default) renders a mouse pointer that animates from the previous action point to the next one."none"disables the cursor decoration.styleObject(optional) Added in: v1.12Styles of the action decorations.
pointstring(optional) Added in: v1.12CSS declarations for the zero-sized marker centered on the action point. Not shown when omitted.
highlightstring(optional) Added in: v1.12CSS declarations for the box that covers the target element. Not shown when omitted.
titlestring(optional) Added in: v1.12CSS declarations for the action title.
timeoutfloat(optional) Added in: v1.15Maximum time in milliseconds to wait for the application to start. Defaults to
30000(30 seconds). Pass0to disable timeout.timezoneIdstring(optional) Added in: v1.12Changes the timezone of the context. See ICU's metaZones.txt for a list of supported timezone IDs. Defaults to the system timezone.
tracesDirpath(optional) Added in: v1.36If specified, traces are saved into this directory.
Returns
Promise<ElectronApplication>