Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
chore(electron): revert #40184 (move Electron API to a separate package) (#40733)
Yury Semikhatsky7d139824b284
diff --git a/docs/src/electron-api/class-electron.md b/docs/src/electron-api/class-electron.mdindex 3c11689c40..1df55a214a 100644--- a/docs/src/electron-api/class-electron.md+++ b/docs/src/electron-api/class-electron.md@@ -2,10 +2,16 @@* since: v1.9* langs: js-Playwright has **experimental** support for Electron automation, exposed as `_electron`. An example of the Electron automation script would be:+Playwright has **experimental** support for Electron automation. You can access electron namespace via:```js-import { _electron as electron } from 'playwright';+const { _electron } = require('playwright');+```++An example of the Electron automation script would be:++```js+const { _electron: electron } = require('playwright');(async () => {// Launch Electron app.@@ -45,109 +51,6 @@ If you are not able to launch Electron and it will end up in timeouts during lau* Ensure that `nodeCliInspect` ([FuseV1Options.EnableNodeCliInspectArguments](https://www.electronjs.org/docs/latest/tutorial/fuses#nodecliinspect)) fuse is **not** set to `false`.-**Migrating from v1.59**--A number of launch options have been removed after v1.59. See below for alternatives.--* `recordHar` - use [`method: Tracing.startHar`].- ```js- const electronApp = await electron.launch({ args: ['main.js'] });- await electronApp.context().tracing.startHar('network.har');- // ... drive the app ...- await electronApp.context().tracing.stopHar();- await electronApp.close();- ```--* `recordVideo` - use [`method: Screencast.start`] on each window.- ```js- const electronApp = await electron.launch({ args: ['main.js'] });- const window = await electronApp.firstWindow();- await window.screencast.start({ path: 'video.webm' });- // ... drive the window ...- await window.screencast.stop();- await electronApp.close();- ```--* `colorScheme` - use [`method: Page.emulateMedia`] on each window.- ```js- const window = await electronApp.firstWindow();- await window.emulateMedia({ colorScheme: 'dark' });- ```--* `extraHTTPHeaders` - use [`method: BrowserContext.setExtraHTTPHeaders`].- ```js- await electronApp.context().setExtraHTTPHeaders({ 'X-My-Header': 'value' });- ```--* `geolocation` - use [`method: BrowserContext.setGeolocation`].- ```js- await electronApp.context().setGeolocation({ latitude: 48.858455, longitude: 2.294474 });- ```--* `httpCredentials` - use [`method: BrowserContext.setHTTPCredentials`].- ```js- await electronApp.context().setHTTPCredentials({ username: 'user', password: 'pass' });- ```--* `offline` - use [`method: BrowserContext.setOffline`].- ```js- await electronApp.context().setOffline(true);- ```--* `bypassCSP` - disable CSP at the `BrowserWindow` level via Electron's [web preferences](https://www.electronjs.org/docs/latest/api/structures/web-preferences). Note that `webSecurity: false` also disables CORS and the Same-Origin Policy.-- ```js- const win = new BrowserWindow({- webPreferences: {- webSecurity: false,- },- });- ```--* `ignoreHTTPSErrors`-- There are several ways to relax HTTPS checks in Electron. Pick the one that matches the scope you need.-- Per-window, allow mixed content through [web preferences](https://www.electronjs.org/docs/latest/api/structures/web-preferences):-- ```js- const win = new BrowserWindow({- webPreferences: {- allowRunningInsecureContent: true,- },- });- ```-- Process-wide, ignore certificate errors via Chromium command-line switches- (must run before the `ready` event):-- ```js- const { app } = require('electron');- app.commandLine.appendSwitch('ignore-certificate-errors');- // Optional: also ignore localhost certificate errors when testing on an IP.- app.commandLine.appendSwitch('allow-insecure-localhost', 'true');- ```-- Per-request, accept the certificate manually via the- [`certificate-error`](https://www.electronjs.org/docs/latest/api/app#event-certificate-error)- event:-- ```js- app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {- event.preventDefault();- callback(true);- });- ```--* `timezoneId` - set an environment variable at the very top of the main file, before any other logic or Chromium windows are initialized.- ```js- // main.js- process.env.TZ = 'Europe/London';-- const { app } = require('electron');- // ... rest of your app logic- ```-## async method: Electron.launch* since: v1.9- returns: <[ElectronApplication]>@@ -186,5 +89,59 @@ Specifies environment variables that will be visible to Electron. Defaults to `pMaximum time in milliseconds to wait for the application to start. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.+### option: Electron.launch.acceptdownloads = %%-context-option-acceptdownloads-%%+* since: v1.12++### option: Electron.launch.bypassCSP = %%-context-option-bypasscsp-%%+* since: v1.12++### option: Electron.launch.colorScheme = %%-context-option-colorscheme-%%+* since: v1.12++### option: Electron.launch.extraHTTPHeaders = %%-context-option-extrahttpheaders-%%+* since: v1.12++### option: Electron.launch.geolocation = %%-context-option-geolocation-%%+* since: v1.12++### option: Electron.launch.httpcredentials = %%-context-option-httpcredentials-%%+* since: v1.12++### option: Electron.launch.ignoreHTTPSErrors = %%-context-option-ignorehttpserrors-%%+* since: v1.12++### option: Electron.launch.locale = %%-context-option-locale-%%+* since: v1.12++### option: Electron.launch.offline = %%-context-option-offline-%%+* since: v1.12++### option: Electron.launch.recordhar = %%-context-option-recordhar-%%+* since: v1.12++### option: Electron.launch.recordharpath = %%-context-option-recordhar-path-%%+* since: v1.12++### option: Electron.launch.recordHarOmitContent = %%-context-option-recordhar-omit-content-%%+* since: v1.12++### option: Electron.launch.recordvideo = %%-context-option-recordvideo-%%+* since: v1.12++### option: Electron.launch.recordvideodir = %%-context-option-recordvideo-dir-%%+* since: v1.12++### option: Electron.launch.recordvideosize = %%-context-option-recordvideo-size-%%+* since: v1.12++### option: Electron.launch.timezoneId = %%-context-option-timezoneid-%%+* since: v1.12++### option: Electron.launch.tracesDir = %%-browser-option-tracesdir-%%+* since: v1.36++### option: Electron.launch.artifactsDir = %%-browser-option-artifactsdir-%%+* since: v1.59+### option: Electron.launch.chromiumSandbox = %%-browser-option-chromiumsandbox-%%* since: v1.59diff --git a/docs/src/electron-api/class-electronapplication.md b/docs/src/electron-api/class-electronapplication.mdindex 3006801d26..87e7975b35 100644--- a/docs/src/electron-api/class-electronapplication.md+++ b/docs/src/electron-api/class-electronapplication.md@@ -7,7 +7,7 @@ obtain the application instance. This instance you can control main electron proas well as work with Electron windows:```js-import { _electron as electron } from 'playwright';+const { _electron: electron } = require('playwright');(async () => {// Launch Electron app.diff --git a/package-lock.json b/package-lock.jsonindex bdbbb7e2a1..57606e7c09 100644--- a/package-lock.json+++ b/package-lock.json@@ -2044,10 +2044,6 @@"resolved": "packages/dashboard","link": true},- "node_modules/@playwright/electron": {- "resolved": "packages/playwright-electron",- "link": true- },"node_modules/@playwright/experimental-ct-core": {"resolved": "packages/playwright-ct-core","link": true@@ -9750,17 +9746,6 @@"node": ">=18"}},- "packages/playwright-electron": {- "name": "@playwright/electron",- "version": "0.0.0",- "license": "Apache-2.0",- "dependencies": {- "playwright": "*"- },- "engines": {- "node": ">=18"- }- },"packages/playwright-firefox": {"version": "1.61.0-next","hasInstallScript": true,diff --git a/packages/isomorphic/protocolMetainfo.ts b/packages/isomorphic/protocolMetainfo.tsindex 6fac0420d9..8a0dcb4ab1 100644--- a/packages/isomorphic/protocolMetainfo.ts+++ b/packages/isomorphic/protocolMetainfo.ts@@ -115,10 +115,16 @@ export const methodMetainfo = new Map<string, MethodMetainfo>([['EventTarget.waitForEventInfo', { title: 'Wait for event "{info.event}"', snapshot: true, }],['AndroidDevice.waitForEventInfo', { title: 'Wait for event "{info.event}"', snapshot: true, }],['BrowserContext.waitForEventInfo', { title: 'Wait for event "{info.event}"', snapshot: true, }],+ ['ElectronApplication.waitForEventInfo', { title: 'Wait for event "{info.event}"', snapshot: true, }],['WebSocket.waitForEventInfo', { title: 'Wait for event "{info.event}"', snapshot: true, }],['Page.waitForEventInfo', { title: 'Wait for event "{info.event}"', snapshot: true, }],['Debugger.waitForEventInfo', { title: 'Wait for event "{info.event}"', snapshot: true, }],['Worker.waitForEventInfo', { title: 'Wait for event "{info.event}"', snapshot: true, }],+ ['Electron.launch', { title: 'Launch electron', }],+ ['ElectronApplication.browserWindow', { internal: true, }],+ ['ElectronApplication.evaluateExpression', { title: 'Evaluate', }],+ ['ElectronApplication.evaluateExpressionHandle', { title: 'Evaluate', }],+ ['ElectronApplication.updateSubscription', { internal: true, }],['Frame.evalOnSelector', { title: 'Evaluate', snapshot: true, pause: true, }],['Frame.evalOnSelectorAll', { title: 'Evaluate', snapshot: true, pause: true, }],['Frame.addScriptTag', { title: 'Add script tag', snapshot: true, pause: true, }],diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.tsindex cb4cfb3767..f3488dd71a 100644--- a/packages/playwright-client/types/types.d.ts+++ b/packages/playwright-client/types/types.d.ts@@ -16702,6 +16702,450 @@ class TimeoutError extends Error {export const devices: Devices;+//@ts-ignore this will be any if electron is not installed+type ElectronType = typeof import('electron');++/**+ * Electron application representation. You can use+ * [electron.launch([options])](https://playwright.dev/docs/api/class-electron#electron-launch) to obtain the+ * application instance. This instance you can control main electron process as well as work with Electron windows:+ *+ * ```js+ * 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();+ * })();+ * ```+ *+ */+export interface ElectronApplication {+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a [Promise], then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * would wait for the promise to resolve and return its value.+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a non-[Serializable] value, then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by+ * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ */+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a [Promise], then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * would wait for the promise to resolve and return its value.+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a non-[Serializable] value, then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by+ * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ */+ evaluate<R, Arg>(pageFunction: PageFunctionOn<ElectronType, Arg, R>, arg: Arg): Promise<R>;+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a [Promise], then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * would wait for the promise to resolve and return its value.+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a non-[Serializable] value, then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by+ * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ */+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a [Promise], then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * would wait for the promise to resolve and return its value.+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a non-[Serializable] value, then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by+ * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ */+ evaluate<R>(pageFunction: PageFunctionOn<ElectronType, void, R>, arg?: any): Promise<R>;++ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression)+ * as a [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * The only difference between+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * and+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * is that+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * If the function passed to the+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns a [Promise], then+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * would wait for the promise to resolve and return its value.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression).+ */+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression)+ * as a [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * The only difference between+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * and+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * is that+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * If the function passed to the+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns a [Promise], then+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * would wait for the promise to resolve and return its value.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression).+ */+ evaluateHandle<R, Arg>(pageFunction: PageFunctionOn<ElectronType, Arg, R>, arg: Arg): Promise<SmartHandle<R>>;+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression)+ * as a [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * The only difference between+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * and+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * is that+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * If the function passed to the+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns a [Promise], then+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * would wait for the promise to resolve and return its value.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression).+ */+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression)+ * as a [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * The only difference between+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * and+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * is that+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * If the function passed to the+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns a [Promise], then+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * would wait for the promise to resolve and return its value.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression).+ */+ evaluateHandle<R>(pageFunction: PageFunctionOn<ElectronType, void, R>, arg?: any): Promise<SmartHandle<R>>;+ /**+ * This event is issued when the application process has been terminated.+ */+ on(event: 'close', listener: () => any): this;++ /**+ * Emitted when JavaScript within the Electron main process calls one of console API methods, e.g. `console.log` or+ * `console.dir`.+ *+ * The arguments passed into `console.log` are available on the+ * [ConsoleMessage](https://playwright.dev/docs/api/class-consolemessage) event handler argument.+ *+ * **Usage**+ *+ * ```js+ * electronApp.on('console', async msg => {+ * const values = [];+ * for (const arg of msg.args())+ * values.push(await arg.jsonValue());+ * console.log(...values);+ * });+ * await electronApp.evaluate(() => console.log('hello', 5, { foo: 'bar' }));+ * ```+ *+ */+ on(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;++ /**+ * This event is issued for every window that is created **and loaded** in Electron. It contains a+ * [Page](https://playwright.dev/docs/api/class-page) that can be used for Playwright automation.+ */+ on(event: 'window', listener: (page: Page) => any): this;++ /**+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ */+ once(event: 'close', listener: () => any): this;++ /**+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ */+ once(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;++ /**+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ */+ once(event: 'window', listener: (page: Page) => any): this;++ /**+ * This event is issued when the application process has been terminated.+ */+ addListener(event: 'close', listener: () => any): this;++ /**+ * Emitted when JavaScript within the Electron main process calls one of console API methods, e.g. `console.log` or+ * `console.dir`.+ *+ * The arguments passed into `console.log` are available on the+ * [ConsoleMessage](https://playwright.dev/docs/api/class-consolemessage) event handler argument.+ *+ * **Usage**+ *+ * ```js+ * electronApp.on('console', async msg => {+ * const values = [];+ * for (const arg of msg.args())+ * values.push(await arg.jsonValue());+ * console.log(...values);+ * });+ * await electronApp.evaluate(() => console.log('hello', 5, { foo: 'bar' }));+ * ```+ *+ */+ addListener(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;++ /**+ * This event is issued for every window that is created **and loaded** in Electron. It contains a+ * [Page](https://playwright.dev/docs/api/class-page) that can be used for Playwright automation.+ */+ addListener(event: 'window', listener: (page: Page) => any): this;++ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ removeListener(event: 'close', listener: () => any): this;++ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ removeListener(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;++ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ removeListener(event: 'window', listener: (page: Page) => any): this;++ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ off(event: 'close', listener: () => any): this;++ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ off(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;++ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ off(event: 'window', listener: (page: Page) => any): this;++ /**+ * This event is issued when the application process has been terminated.+ */+ prependListener(event: 'close', listener: () => any): this;++ /**+ * Emitted when JavaScript within the Electron main process calls one of console API methods, e.g. `console.log` or+ * `console.dir`.+ *+ * The arguments passed into `console.log` are available on the+ * [ConsoleMessage](https://playwright.dev/docs/api/class-consolemessage) event handler argument.+ *+ * **Usage**+ *+ * ```js+ * electronApp.on('console', async msg => {+ * const values = [];+ * for (const arg of msg.args())+ * values.push(await arg.jsonValue());+ * console.log(...values);+ * });+ * await electronApp.evaluate(() => console.log('hello', 5, { foo: 'bar' }));+ * ```+ *+ */+ prependListener(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;++ /**+ * This event is issued for every window that is created **and loaded** in Electron. It contains a+ * [Page](https://playwright.dev/docs/api/class-page) that can be used for Playwright automation.+ */+ prependListener(event: 'window', listener: (page: Page) => any): this;++ /**+ * Returns the BrowserWindow object that corresponds to the given Playwright page.+ * @param page Page to retrieve the window for.+ */+ browserWindow(page: Page): Promise<JSHandle>;++ /**+ * Closes Electron application.+ */+ close(): Promise<void>;++ /**+ * This method returns browser context that can be used for setting up context-wide routing, etc.+ */+ context(): BrowserContext;++ /**+ * Convenience method that waits for the first application window to be opened.+ *+ * **Usage**+ *+ * ```js+ * const electronApp = await electron.launch({+ * args: ['main.js']+ * });+ * const window = await electronApp.firstWindow();+ * // ...+ * ```+ *+ * @param options+ */+ firstWindow(options?: {+ /**+ * Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The+ * default value can be changed by using the+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout).+ */+ timeout?: number;+ }): Promise<Page>;++ /**+ * Returns the main process for this Electron Application.+ */+ process(): ChildProcess;++ /**+ * This event is issued when the application process has been terminated.+ */+ waitForEvent(event: 'close', optionsOrPredicate?: { predicate?: () => boolean | Promise<boolean>, timeout?: number } | (() => boolean | Promise<boolean>)): Promise<void>;++ /**+ * Emitted when JavaScript within the Electron main process calls one of console API methods, e.g. `console.log` or+ * `console.dir`.+ *+ * The arguments passed into `console.log` are available on the+ * [ConsoleMessage](https://playwright.dev/docs/api/class-consolemessage) event handler argument.+ *+ * **Usage**+ *+ * ```js+ * electronApp.on('console', async msg => {+ * const values = [];+ * for (const arg of msg.args())+ * values.push(await arg.jsonValue());+ * console.log(...values);+ * });+ * await electronApp.evaluate(() => console.log('hello', 5, { foo: 'bar' }));+ * ```+ *+ */+ waitForEvent(event: 'console', optionsOrPredicate?: { predicate?: (consoleMessage: ConsoleMessage) => boolean | Promise<boolean>, timeout?: number } | ((consoleMessage: ConsoleMessage) => boolean | Promise<boolean>)): Promise<ConsoleMessage>;++ /**+ * This event is issued for every window that is created **and loaded** in Electron. It contains a+ * [Page](https://playwright.dev/docs/api/class-page) that can be used for Playwright automation.+ */+ waitForEvent(event: 'window', optionsOrPredicate?: { predicate?: (page: Page) => boolean | Promise<boolean>, timeout?: number } | ((page: Page) => boolean | Promise<boolean>)): Promise<Page>;+++ /**+ * Convenience method that returns all the opened windows.+ */+ windows(): Array<Page>;++ [Symbol.asyncDispose](): Promise<void>;+}+export type AndroidElementInfo = {clazz: string;desc: string;@@ -16807,6 +17251,7 @@ export type AndroidKey ='Copy' |'Paste';+export const _electron: Electron;export const _android: Android;//@ts-ignore this will be any if electron is not installed@@ -16818,7 +17263,7 @@ type ElectronType = typeof import('electron');* application instance. This instance you can control main electron process as well as work with Electron windows:** ```js- * import { _electron as electron } from 'playwright';+ * const { _electron: electron } = require('playwright');** (async () => {* // Launch Electron app.@@ -16854,22 +17299,151 @@ export interface ElectronApplication {* [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).** If the function passed to the- * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a [Promise], then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * would wait for the promise to resolve and return its value.+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a non-[Serializable] value, then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by+ * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ */+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a [Promise], then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * would wait for the promise to resolve and return its value.+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a non-[Serializable] value, then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by+ * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ */+ evaluate<R, Arg>(pageFunction: PageFunctionOn<ElectronType, Arg, R>, arg: Arg): Promise<R>;+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a [Promise], then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * would wait for the promise to resolve and return its value.+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a non-[Serializable] value, then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by+ * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ */+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a [Promise], then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * would wait for the promise to resolve and return its value.+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a non-[Serializable] value, then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by+ * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ */+ evaluate<R>(pageFunction: PageFunctionOn<ElectronType, void, R>, arg?: any): Promise<R>;++ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression)+ * as a [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * The only difference between+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * and+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * is that+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * If the function passed to the+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns a [Promise], then+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * would wait for the promise to resolve and return its value.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression).+ */+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression)+ * as a [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * The only difference between+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * and+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * is that+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * If the function passed to the+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns a [Promise], then+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * would wait for the promise to resolve and return its value.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression).+ */+ evaluateHandle<R, Arg>(pageFunction: PageFunctionOn<ElectronType, Arg, R>, arg: Arg): Promise<SmartHandle<R>>;+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression)+ * as a [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * The only difference between+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * and+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * is that+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * If the function passed to the+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)* returns a [Promise], then- * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)* would wait for the promise to resolve and return its value.- *- * If the function passed to the- * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)- * returns a non-[Serializable] value, then- * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)- * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by- * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.* @param pageFunction Function to be evaluated in the main Electron process.* @param arg Optional argument to pass to- * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression).*/- evaluate: JSHandle<ElectronType>['evaluate'];/*** Returns the return value of* [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression)@@ -16892,7 +17466,7 @@ export interface ElectronApplication {* @param arg Optional argument to pass to* [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression).*/- evaluateHandle: JSHandle<ElectronType>['evaluateHandle'];+ evaluateHandle<R>(pageFunction: PageFunctionOn<ElectronType, void, R>, arg?: any): Promise<SmartHandle<R>>;/*** This event is issued when the application process has been terminated.*/@@ -17124,8 +17698,6 @@ export interface ElectronApplication {[Symbol.asyncDispose](): Promise<void>;}-export const _electron: Electron;-// This is required to not export everything by default. See https://github.com/Microsoft/TypeScript/issues/19545#issuecomment-340490459export {};@@ -21317,11 +21889,16 @@ export interface WebSocket {}/**- * Playwright has **experimental** support for Electron automation, exposed as `_electron`. An example of the Electron- * automation script would be:+ * Playwright has **experimental** support for Electron automation. You can access electron namespace via:+ *+ * ```js+ * const { _electron } = require('playwright');+ * ```+ *+ * An example of the Electron automation script would be:** ```js- * import { _electron as electron } from 'playwright';+ * const { _electron: electron } = require('playwright');** (async () => {* // Launch Electron app.@@ -21361,127 +21938,6 @@ export interface WebSocket {* - Ensure that `nodeCliInspect`* ([FuseV1Options.EnableNodeCliInspectArguments](https://www.electronjs.org/docs/latest/tutorial/fuses#nodecliinspect))* fuse is **not** set to `false`.- *- * **Migrating from v1.59**- *- * A number of launch options have been removed after v1.59. See below for alternatives.- * - `recordHar` - use- * [tracing.startHar(path[, options])](https://playwright.dev/docs/api/class-tracing#tracing-start-har).- *- * ```js- * const electronApp = await electron.launch({ args: ['main.js'] });- * await electronApp.context().tracing.startHar('network.har');- * // ... drive the app ...- * await electronApp.context().tracing.stopHar();- * await electronApp.close();- * ```- *- * - `recordVideo` - use- * [screencast.start([options])](https://playwright.dev/docs/api/class-screencast#screencast-start) on each- * window.- *- * ```js- * const electronApp = await electron.launch({ args: ['main.js'] });- * const window = await electronApp.firstWindow();- * await window.screencast.start({ path: 'video.webm' });- * // ... drive the window ...- * await window.screencast.stop();- * await electronApp.close();- * ```- *- * - `colorScheme` - use- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) on each window.- *- * ```js- * const window = await electronApp.firstWindow();- * await window.emulateMedia({ colorScheme: 'dark' });- * ```- *- * - `extraHTTPHeaders` - use- * [browserContext.setExtraHTTPHeaders(headers)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-extra-http-headers).- *- * ```js- * await electronApp.context().setExtraHTTPHeaders({ 'X-My-Header': 'value' });- * ```- *- * - `geolocation` - use- * [browserContext.setGeolocation(geolocation)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-geolocation).- *- * ```js- * await electronApp.context().setGeolocation({ latitude: 48.858455, longitude: 2.294474 });- * ```- *- * - `httpCredentials` - use- * [browserContext.setHTTPCredentials(httpCredentials)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-http-credentials).- *- * ```js- * await electronApp.context().setHTTPCredentials({ username: 'user', password: 'pass' });- * ```- *- * - `offline` - use- * [browserContext.setOffline(offline)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-offline).- *- * ```js- * await electronApp.context().setOffline(true);- * ```- *- * - `bypassCSP` - disable CSP at the `BrowserWindow` level via Electron's- * [web preferences](https://www.electronjs.org/docs/latest/api/structures/web-preferences). Note that- * `webSecurity: false` also disables CORS and the Same-Origin Policy.- *- * ```js- * const win = new BrowserWindow({- * webPreferences: {- * webSecurity: false,- * },- * });- * ```- *- * - `ignoreHTTPSErrors`- *- * There are several ways to relax HTTPS checks in Electron. Pick the one that matches the scope you need.- *- * Per-window, allow mixed content through- * [web preferences](https://www.electronjs.org/docs/latest/api/structures/web-preferences):- *- * ```js- * const win = new BrowserWindow({- * webPreferences: {- * allowRunningInsecureContent: true,- * },- * });- * ```- *- * Process-wide, ignore certificate errors via Chromium command-line switches (must run before the `ready` event):- *- * ```js- * const { app } = require('electron');- * app.commandLine.appendSwitch('ignore-certificate-errors');- * // Optional: also ignore localhost certificate errors when testing on an IP.- * app.commandLine.appendSwitch('allow-insecure-localhost', 'true');- * ```- *- * Per-request, accept the certificate manually via the- * [`certificate-error`](https://www.electronjs.org/docs/latest/api/app#event-certificate-error) event:- *- * ```js- * app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {- * event.preventDefault();- * callback(true);- * });- * ```- *- * - `timezoneId` - set an environment variable at the very top of the main file, before any other logic or Chromium- * windows are initialized.- *- * ```js- * // main.js- * process.env.TZ = 'Europe/London';- *- * const { app } = require('electron');- * // ... rest of your app logic- * ```- **/export interface Electron {/**@@ -21490,16 +21946,41 @@ export interface Electron {* @param options*/launch(options?: {+ /**+ * Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.+ */+ acceptDownloads?: boolean;+/*** Additional arguments to pass to the application when launching. You typically pass the main script name here.*/args?: Array<string>;+ /**+ * If 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.+ */+ artifactsDir?: string;++ /**+ * Toggles bypassing page's Content-Security-Policy. Defaults to `false`.+ */+ bypassCSP?: boolean;+/*** Enable Chromium sandboxing. Defaults to `false`.*/chromiumSandbox?: boolean;+ /**+ * Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)+ * media feature, supported values are `'light'` and `'dark'`. See+ * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.+ * Passing `null` resets emulation to system defaults. Defaults to `'light'`.+ */+ colorScheme?: null|"light"|"dark"|"no-preference";+/*** Current working directory to launch application from.*/@@ -21516,11 +21997,180 @@ export interface Electron {*/executablePath?: string;+ /**+ * An object containing additional HTTP headers to be sent with every request. Defaults to none.+ */+ extraHTTPHeaders?: { [key: string]: string; };++ geolocation?: {+ /**+ * Latitude between -90 and 90.+ */+ latitude: number;++ /**+ * Longitude between -180 and 180.+ */+ longitude: number;++ /**+ * Non-negative accuracy value. Defaults to `0`.+ */+ accuracy?: number;+ };++ /**+ * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no+ * origin is specified, the username and password are sent to any servers upon unauthorized responses.+ */+ httpCredentials?: {+ username: string;++ password: string;++ /**+ * Restrain sending http credentials on specific origin (scheme://host:port).+ */+ origin?: string;++ /**+ * This option only applies to the requests sent from corresponding+ * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) and does not affect requests sent from+ * the browser. `'always'` - `Authorization` header with basic authentication credentials will be sent with the each+ * API request. `'unauthorized` - the credentials are only sent when 401 (Unauthorized) response with+ * `WWW-Authenticate` header is received. Defaults to `'unauthorized'`.+ */+ send?: "unauthorized"|"always";+ };++ /**+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.+ */+ ignoreHTTPSErrors?: boolean;++ /**+ * Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,+ * `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default+ * locale. Learn more about emulation in our [emulation guide](https://playwright.dev/docs/emulation#locale--timezone).+ */+ locale?: string;++ /**+ * Whether to emulate network being offline. Defaults to `false`. Learn more about+ * [network emulation](https://playwright.dev/docs/emulation#offline).+ */+ offline?: boolean;++ /**+ * Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into `recordHar.path` file.+ * If not specified, the HAR is not recorded. Make sure to await+ * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for+ * the HAR to be saved.+ */+ recordHar?: {+ /**+ * Optional setting to control whether to omit request content from the HAR. Defaults to `false`. Deprecated, use+ * `content` policy instead.+ */+ omitContent?: boolean;++ /**+ * Optional setting to control resource content management. If `omit` is specified, content is not persisted. If+ * `attach` is specified, resources are persisted as separate files or entries in the ZIP archive. If `embed` is+ * specified, content is stored inline the HAR file as per HAR specification. Defaults to `attach` for `.zip` output+ * files and to `embed` for all other file extensions.+ */+ content?: "omit"|"embed"|"attach";++ /**+ * Path on the filesystem to write the HAR file to. If the file name ends with `.zip`, `content: 'attach'` is used by+ * default.+ */+ path: string;++ /**+ * When 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 to `full`.+ */+ mode?: "full"|"minimal";++ /**+ * A glob or regex pattern to filter requests that are stored in the HAR. When a+ * [`baseURL`](https://playwright.dev/docs/api/class-browser#browser-new-context-option-base-url) via the context+ * options was provided and the passed URL is a path, it gets merged via the+ * [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor. Defaults to none.+ */+ urlFilter?: string|RegExp;+ };++ /**+ * Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded.+ * Make sure to await+ * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for+ * videos to be saved.+ */+ recordVideo?: {+ /**+ * Path to the directory to put videos into. If not specified, the videos will be stored in `artifactsDir` (see+ * [browserType.launch([options])](https://playwright.dev/docs/api/class-browsertype#browser-type-launch) options).+ */+ dir?: string;++ /**+ * Optional dimensions of the recorded videos. If not specified the size will be equal to `viewport` scaled down to+ * fit into 800x800. If `viewport` is 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.+ */+ size?: {+ /**+ * Video frame width.+ */+ width: number;++ /**+ * Video frame height.+ */+ height: number;+ };++ /**+ * If specified, enables visual annotations on interacted elements during video recording.+ */+ showActions?: {+ /**+ * How long each annotation is displayed in milliseconds. Defaults to `500`.+ */+ duration?: number;++ /**+ * Position of the action title overlay. Defaults to `"top-right"`.+ */+ position?: "top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right";++ /**+ * Font size of the action title in pixels. Defaults to `24`.+ */+ fontSize?: number;+ };+ };+/*** Maximum time in milliseconds to wait for the application to start. Defaults to `30000` (30 seconds). Pass `0` to* disable timeout.*/timeout?: number;++ /**+ * Changes the timezone of the context. See+ * [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)+ * for a list of supported timezone IDs. Defaults to the system timezone.+ */+ timezoneId?: string;++ /**+ * If specified, traces are saved into this directory.+ */+ tracesDir?: string;}): Promise<ElectronApplication>;}diff --git a/packages/playwright-core/index.mjs b/packages/playwright-core/index.mjsindex 0878c2161f..3b3c75b0f7 100644--- a/packages/playwright-core/index.mjs+++ b/packages/playwright-core/index.mjs@@ -23,6 +23,6 @@ export const selectors = playwright.selectors;export const devices = playwright.devices;export const errors = playwright.errors;export const request = playwright.request;-export const _android = playwright._android;export const _electron = playwright._electron;+export const _android = playwright._android;export default playwright;diff --git a/packages/playwright-core/src/client/api.ts b/packages/playwright-core/src/client/api.tsindex 53f3888a9d..3a36d03285 100644--- a/packages/playwright-core/src/client/api.ts+++ b/packages/playwright-core/src/client/api.ts@@ -26,6 +26,7 @@ export { Debugger } from './debugger';export { Dialog } from './dialog';export type { Disposable } from './disposable';export { Download } from './download';+export { Electron, ElectronApplication } from './electron';export { FrameLocator, Locator } from './locator';export { ElementHandle } from './elementHandle';export { FileChooser } from './fileChooser';diff --git a/packages/playwright-core/src/client/connection.ts b/packages/playwright-core/src/client/connection.tsindex dbc80c21d0..f54c07948c 100644--- a/packages/playwright-core/src/client/connection.ts+++ b/packages/playwright-core/src/client/connection.ts@@ -27,6 +27,7 @@ import { createInstrumentation } from './clientInstrumentation';import { Debugger } from './debugger';import { Dialog } from './dialog';import { DisposableObject } from './disposable';+import { Electron, ElectronApplication } from './electron';import { ElementHandle } from './elementHandle';import { TargetClosedError, parseError } from './errors';import { APIRequestContext } from './fetch';@@ -103,6 +104,8 @@ export class Connection extends EventEmitter {Debugger: (parent, type, guid, init) => new Debugger(parent, type, guid, init),Dialog: (parent, type, guid, init) => new Dialog(parent, type, guid, init),Disposable: (parent, type, guid, init) => new DisposableObject(parent, type, guid, init),+ Electron: (parent, type, guid, init) => new Electron(parent, type, guid, init),+ ElectronApplication: (parent, type, guid, init) => new ElectronApplication(parent, type, guid, init),ElementHandle: (parent, type, guid, init) => new ElementHandle(parent, type, guid, init),Frame: (parent, type, guid, init) => new Frame(parent, type, guid, init),JSHandle: (parent, type, guid, init) => new JSHandle(parent, type, guid, init),diff --git a/packages/playwright-core/src/client/consoleMessage.ts b/packages/playwright-core/src/client/consoleMessage.tsindex 2cbf124dcb..4b4e213293 100644--- a/packages/playwright-core/src/client/consoleMessage.ts+++ b/packages/playwright-core/src/client/consoleMessage.ts@@ -26,9 +26,9 @@ export class ConsoleMessage implements api.ConsoleMessage {private _page: Page | null;private _worker: Worker | null;- private _event: channels.BrowserContextConsoleEvent | channels.WorkerConsoleEvent;+ private _event: channels.BrowserContextConsoleEvent | channels.WorkerConsoleEvent | channels.ElectronApplicationConsoleEvent;- constructor(platform: Platform, event: channels.BrowserContextConsoleEvent | channels.WorkerConsoleEvent, page: Page | null, worker: Worker | null) {+ constructor(platform: Platform, event: channels.BrowserContextConsoleEvent | channels.WorkerConsoleEvent | channels.ElectronApplicationConsoleEvent, page: Page | null, worker: Worker | null) {this._page = page;this._worker = worker;this._event = event;diff --git a/packages/playwright-core/src/client/electron.ts b/packages/playwright-core/src/client/electron.tsnew file mode 100644index 0000000000..2399aa61ff--- /dev/null+++ b/packages/playwright-core/src/client/electron.ts@@ -0,0 +1,169 @@+/**+ * Copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { BrowserContext, prepareBrowserContextParams } from './browserContext';+import { ChannelOwner } from './channelOwner';+import { envObjectToArray } from './clientHelper';+import { ConsoleMessage } from './consoleMessage';+import { TargetClosedError, isTargetClosedError } from './errors';+import { Events } from './events';+import { JSHandle, parseResult, serializeArgument } from './jsHandle';+import { Waiter } from './waiter';+import { TimeoutSettings } from './timeoutSettings';++import type { Page } from './page';+import type { BrowserContextOptions, Headers, WaitForEventOptions } from './types';+import type * as structs from '../../types/structs';+import type * as api from '../../types/types';+import type * as channels from '@protocol/channels';+import type * as childProcess from 'child_process';+import type { BrowserWindow } from 'electron';+import type { Playwright } from './playwright';++type ElectronOptions = Omit<channels.ElectronLaunchOptions, 'env'|'extraHTTPHeaders'|'recordHar'|'colorScheme'|'acceptDownloads'> & {+ env?: NodeJS.ProcessEnv,+ extraHTTPHeaders?: Headers,+ recordHar?: BrowserContextOptions['recordHar'],+ colorScheme?: 'dark' | 'light' | 'no-preference' | null,+ acceptDownloads?: boolean,+ timeout?: number,+};++type ElectronAppType = typeof import('electron');++export class Electron extends ChannelOwner<channels.ElectronChannel> implements api.Electron {+ _playwright!: Playwright;++ static from(electron: channels.ElectronChannel): Electron {+ return (electron as any)._object;+ }++ constructor(parent: ChannelOwner, type: string, guid: string, initializer: channels.ElectronInitializer) {+ super(parent, type, guid, initializer);+ }++ async launch(options: ElectronOptions = {}): Promise<ElectronApplication> {+ options = this._playwright.selectors._withSelectorOptions(options);+ const params: channels.ElectronLaunchParams = {+ ...await prepareBrowserContextParams(this._platform, options),+ env: envObjectToArray(options.env ? options.env : this._platform.env),+ tracesDir: options.tracesDir,+ artifactsDir: options.artifactsDir,+ timeout: new TimeoutSettings(this._platform).launchTimeout(options),+ };+ const app = ElectronApplication.from((await this._channel.launch(params)).electronApplication);+ this._playwright.selectors._contextsForSelectors.add(app._context);+ app.once(Events.ElectronApplication.Close, () => this._playwright.selectors._contextsForSelectors.delete(app._context));+ await app._context._initializeHarFromOptions(options.recordHar);+ app._context.tracing._tracesDir = options.tracesDir;+ return app;+ }+}++export class ElectronApplication extends ChannelOwner<channels.ElectronApplicationChannel> implements api.ElectronApplication {+ readonly _context: BrowserContext;+ private _windows = new Set<Page>();+ private _timeoutSettings: TimeoutSettings;++ static from(electronApplication: channels.ElectronApplicationChannel): ElectronApplication {+ return (electronApplication as any)._object;+ }++ constructor(parent: ChannelOwner, type: string, guid: string, initializer: channels.ElectronApplicationInitializer) {+ super(parent, type, guid, initializer);++ this._timeoutSettings = new TimeoutSettings(this._platform);+ this._context = BrowserContext.from(initializer.context);+ for (const page of this._context._pages)+ this._onPage(page);+ this._context.on(Events.BrowserContext.Page, page => this._onPage(page));+ this._channel.on('close', () => {+ this.emit(Events.ElectronApplication.Close);+ });+ this._channel.on('console', event => this.emit(Events.ElectronApplication.Console, new ConsoleMessage(this._platform, event, null, null)));+ this._setEventToSubscriptionMapping(new Map<string, channels.ElectronApplicationUpdateSubscriptionParams['event']>([+ [Events.ElectronApplication.Console, 'console'],+ ]));+ }++ process(): childProcess.ChildProcess {+ return this._connection.toImpl?.(this)?.process();+ }++ _onPage(page: Page) {+ this._windows.add(page);+ this.emit(Events.ElectronApplication.Window, page);+ page.once(Events.Page.Close, () => this._windows.delete(page));+ }++ windows(): Page[] {+ // TODO: add ElectronPage class inheriting from Page.+ return [...this._windows];+ }++ async firstWindow(options?: { timeout?: number }): Promise<Page> {+ if (this._windows.size)+ return this._windows.values().next().value!;+ return await this.waitForEvent('window', options);+ }++ context(): BrowserContext {+ return this._context;+ }++ async [Symbol.asyncDispose]() {+ await this.close();+ }++ async close() {+ try {+ await this._context.close();+ } catch (e) {+ if (isTargetClosedError(e))+ return;+ throw e;+ }+ }++ async waitForEvent(event: string, optionsOrPredicate: WaitForEventOptions = {}): Promise<any> {+ return await this._wrapApiCall(async () => {+ const timeout = this._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);+ const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;+ const waiter = Waiter.createForEvent(this, event);+ waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded while waiting for event "${event}"`);+ if (event !== Events.ElectronApplication.Close)+ waiter.rejectOnEvent(this, Events.ElectronApplication.Close, () => new TargetClosedError());+ const result = await waiter.waitForEvent(this, event, predicate as any);+ waiter.dispose();+ return result;+ });+ }++ async browserWindow(page: Page): Promise<JSHandle<BrowserWindow>> {+ const result = await this._channel.browserWindow({ page: page._channel });+ return JSHandle.from(result.handle);+ }++ async evaluate<R, Arg>(pageFunction: structs.PageFunctionOn<ElectronAppType, Arg, R>, arg: Arg): Promise<R> {+ const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg) });+ return parseResult(result.value);+ }++ async evaluateHandle<R, Arg>(pageFunction: structs.PageFunctionOn<ElectronAppType, Arg, R>, arg: Arg): Promise<structs.SmartHandle<R>> {+ const result = await this._channel.evaluateExpressionHandle({ expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg) });+ return JSHandle.from(result.handle) as any as structs.SmartHandle<R>;+ }+}diff --git a/packages/playwright-core/src/client/events.ts b/packages/playwright-core/src/client/events.tsindex 85dfc561fd..c69b3aa5a4 100644--- a/packages/playwright-core/src/client/events.ts+++ b/packages/playwright-core/src/client/events.ts@@ -100,4 +100,10 @@ export const Events = {Close: 'close',Console: 'console',},++ ElectronApplication: {+ Close: 'close',+ Console: 'console',+ Window: 'window',+ },};diff --git a/packages/playwright-core/src/client/playwright.ts b/packages/playwright-core/src/client/playwright.tsindex e777e79832..c5f2074aee 100644--- a/packages/playwright-core/src/client/playwright.ts+++ b/packages/playwright-core/src/client/playwright.ts@@ -18,6 +18,7 @@ import { Android } from './android';import { Browser } from './browser';import { BrowserType } from './browserType';import { ChannelOwner } from './channelOwner';+import { Electron } from './electron';import { TimeoutError } from './errors';import { APIRequest } from './fetch';import { Selectors } from './selectors';@@ -27,6 +28,7 @@ import type { LaunchOptions } from 'playwright-core';export class Playwright extends ChannelOwner<channels.PlaywrightChannel> {readonly _android: Android;+ readonly _electron: Electron;readonly chromium: BrowserType;readonly firefox: BrowserType;readonly webkit: BrowserType;@@ -51,6 +53,8 @@ export class Playwright extends ChannelOwner<channels.PlaywrightChannel> {this.webkit._playwright = this;this._android = Android.from(initializer.android);this._android._playwright = this;+ this._electron = Electron.from(initializer.electron);+ this._electron._playwright = this;this.devices = this._connection.localUtils()?.devices ?? {};this.selectors = new Selectors(this._connection._platform);this.errors = { TimeoutError };diff --git a/packages/playwright-core/src/electron/DEPS.list b/packages/playwright-core/src/electron/DEPS.listdeleted file mode 100644index 33bd5201b0..0000000000--- a/packages/playwright-core/src/electron/DEPS.list+++ /dev/null@@ -1,5 +0,0 @@-[*]-../package.ts-@isomorphic/**-@utils/**-node_modules/debugdiff --git a/packages/playwright-core/src/electron/electron.ts b/packages/playwright-core/src/electron/electron.tsdeleted file mode 100644index cc493b7ed1..0000000000--- a/packages/playwright-core/src/electron/electron.ts+++ /dev/null@@ -1,358 +0,0 @@-/**- * Copyright (c) Microsoft Corporation.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import os from 'os';-import readline from 'readline';-import { EventEmitter } from 'events';-import debug from 'debug';--import { launchProcess } from '@utils/processLauncher';-import { wrapInASCIIBox } from '@utils/ascii';-import { debugMode } from '@utils/debug';-import { ManualPromise } from '@isomorphic/manualPromise';-import { monotonicTime } from '@isomorphic/time';--import { libPath } from '../package';--import type { BrowserWindow } from 'electron';-import type { Browser, BrowserContext, JSHandle, Page } from '../../types/types';-import type * as api from '../../types/types';-import type { Playwright } from '../client/playwright';-import type { Worker } from '../client/worker';-import type childProcess from 'child_process';--const debugLogger = debug('pw:electron');--export const Events = {- ElectronApplication: {- Close: 'close',- Console: 'console',- Window: 'window',- },-};--type ElectronLaunchOptions = NonNullable<Parameters<api.Electron['launch']>[0]>;--type ElectronAppType = typeof import('electron');--class Progress {- private _deadline: number;- private _timeoutError: Error;-- constructor(timeout: number, timeoutMessage: string) {- this._deadline = timeout ? monotonicTime() + timeout : 0;- this._timeoutError = new Error(timeoutMessage);- }-- async race<T>(promise: Promise<T>): Promise<T> {- const timeoutPromise = new ManualPromise<T>();- const timeout = this.timeUntilDeadline();- const timer = timeout ? setTimeout(() => timeoutPromise.reject(this._timeoutError), timeout) : undefined;- try {- return await Promise.race([promise, timeoutPromise]);- } finally {- clearTimeout(timer);- }- }-- timeUntilDeadline() {- return this._deadline ? this._deadline - monotonicTime() : 0;- }-}--export class Electron implements api.Electron {- _playwright: Playwright;-- constructor(playwright: Playwright) {- this._playwright = playwright;- }-- async launch(options: ElectronLaunchOptions = {}): Promise<ElectronApplication> {- const timeout = options.timeout ?? (debugMode() === 'inspector' ? 0 : 3 * 60 * 1000);- const progress = new Progress(timeout, `electron.launch: Timeout ${timeout}ms exceeded`);- let app: ElectronApplication | undefined;-- // --remote-debugging-port=0 must be the last playwright argument; loader.ts relies on it.- let electronArguments = ['--inspect=0', '--remote-debugging-port=0', ...(options.args || [])];-- if (os.platform() === 'linux') {- if (!options.chromiumSandbox && !electronArguments.includes('--no-sandbox'))- electronArguments.unshift('--no-sandbox');- }-- let command: string;- if (options.executablePath) {- command = options.executablePath;- } else {- try {- // 'electron/index.js' resolves to the Electron App executable shim.- command = require('electron/index.js');- } catch (error: any) {- if ((error as NodeJS.ErrnoException)?.code === 'MODULE_NOT_FOUND') {- throw new Error('\n' + wrapInASCIIBox([- 'Electron executablePath not found!',- 'Please install it using `npm install -D electron` or set the executablePath to your Electron executable.',- ].join('\n'), 1));- }- throw error;- }- // Only inject our loader for non-packaged apps; packaged apps may have- // their own command-line handling. loader.js is emitted under- // lib/electron/ as a per-file build (see utils/build/build.js).- electronArguments.unshift('-r', libPath('electron', 'loader.js'));- }-- let shell = false;- if (process.platform === 'win32') {- // shell: true is required to launch .cmd files. We pass the entire- // command as a single string to dodge DEP0190 and Windows quoting bugs.- // https://github.com/nodejs/node/issues/52554- // https://github.com/microsoft/playwright/issues/38278- shell = true;- command = [command, ...electronArguments].map(arg => `"${arg.replace(/"/g, '\\"')}"`).join(' ');- electronArguments = [];- }-- // When debugging Playwright tests that drive Electron, NODE_OPTIONS- // would make the user's debugger latch onto Electron's Node first.- // Strip it so Playwright can attach.- const env = { ...(options.env ?? process.env) };- delete env.NODE_OPTIONS;-- const logCollector: string[] = [];- const { launchedProcess, kill } = await launchProcess({- command,- args: electronArguments,- env,- log: (message: string) => {- debugLogger(message);- logCollector.push(message);- },- shell,- stdio: 'pipe',- cwd: options.cwd,- tempDirectories: [],- attemptToGracefullyClose: async () => { await app?.close(); },- handleSIGINT: true,- handleSIGTERM: true,- handleSIGHUP: true,- onExit: () => app?._onClose(),- });-- // Start every line listener immediately — the lines may arrive before we- // are ready to await them.- const waitForXserverError = waitForLine(progress, launchedProcess, /Unable to open X display/).then(() => {- throw new Error([- 'Unable to open X display!',- '================================',- 'Most likely this is because there is no X server available.',- "Use 'xvfb-run' on Linux to launch your tests with an emulated display server.",- "For example: 'xvfb-run npm run test:e2e'",- '================================',- ...logCollector,- ].join('\n'));- });- const nodeMatchPromise = waitForLine(progress, launchedProcess, /^Debugger listening on (ws:\/\/.*)$/);- const chromeMatchPromise = waitForLine(progress, launchedProcess, /^DevTools listening on (ws:\/\/.*)$/);- const debuggerDisconnectPromise = waitForLine(progress, launchedProcess, /Waiting for the debugger to disconnect\.\.\./);-- try {- const chromium = this._playwright.chromium;- const nodeMatch = await nodeMatchPromise;- const worker = await chromium._connectToWorker(nodeMatch[1], { timeout: progress.timeUntilDeadline() });-- // Release the Electron process immediately if the user is debugging it.- debuggerDisconnectPromise.then(() => worker._disconnect()).catch(() => {});-- const chromeMatch = await Promise.race([chromeMatchPromise, waitForXserverError]);- const browser = await chromium.connectOverCDP(chromeMatch[1], { timeout: progress.timeUntilDeadline(), isLocal: true });-- app = new ElectronApplication(worker, browser, launchedProcess);- await progress.race(app._initialize());- return app;- } catch (error) {- await kill();- throw error;- }- }-}--export class ElectronApplication extends EventEmitter implements api.ElectronApplication {- private _worker: Worker;- private _browser: Browser;- private _process: childProcess.ChildProcess;- private _context: BrowserContext;- private _windows = new Map<Page, JSHandle<BrowserWindow> | undefined>();- private _appHandlePromise = new ManualPromise<JSHandle<ElectronAppType>>();- private _closedPromise: Promise<void> | undefined;-- constructor(worker: Worker, browser: Browser, process: childProcess.ChildProcess) {- super();-- this._worker = worker;- this._worker.on('console', message => this.emit(Events.ElectronApplication.Console, message));-- this._browser = browser;- this._context = browser.contexts()[0];- for (const page of this._context.pages())- this._onPage(page);- this._context.on('page', page => this._onPage(page));- // Closing the BrowserContext should close the entire app; route both through close().- this._context.close = () => this.close();-- this._process = process;- }-- _onClose() {- this.emit(Events.ElectronApplication.Close);- this._closedPromise ??= Promise.resolve();- }-- process(): childProcess.ChildProcess {- return this._process;- }-- _onPage(page: Page) {- this._windows.set(page, undefined);- this.emit(Events.ElectronApplication.Window, page);- page.once('close', () => this._windows.delete(page));- }-- windows(): Page[] {- return [...this._windows.keys()];- }-- async firstWindow(options?: { timeout?: number }): Promise<Page> {- if (this._windows.size)- return this._windows.keys().next().value!;- return await this.waitForEvent('window', options);- }-- context(): BrowserContext {- return this._context;- }-- async [Symbol.asyncDispose]() {- await this.close();- }-- async close() {- if (!this._closedPromise) {- this._closedPromise = new Promise<void>(f => this.once(Events.ElectronApplication.Close, f));- await this._browser.close();- const appHandle = await this._appHandlePromise;- await appHandle.evaluate(({ app }) => app.quit()).catch(() => {});- await this._worker._disconnect();- }- await this._closedPromise;- }-- async waitForEvent(event: string, optionsOrPredicate: Function | { timeout?: number, predicate?: Function } = {}): Promise<any> {- const promise = new ManualPromise<any>();-- const onEvent = async (eventArg: any) => {- try {- const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;- if (predicate && !(await predicate(eventArg)))- return;- promise.resolve(eventArg);- } catch (e) {- promise.reject(e);- }- };- this.addListener(event, onEvent);-- const onClose = () => promise.reject(new Error('Electron application has been closed'));- if (event !== Events.ElectronApplication.Close)- this.addListener(Events.ElectronApplication.Close, onClose);-- try {- const timeout = typeof optionsOrPredicate === 'function' ? 30000 : (optionsOrPredicate?.timeout ?? 30000);- const progress = new Progress(timeout, `Timeout ${timeout}ms exceeded while waiting for event "${event}"`);- return await progress.race(promise);- } finally {- this.removeListener(event, onEvent);- this.removeListener(Events.ElectronApplication.Close, onClose);- }- }-- async _initialize() {- await Promise.all([- this._worker.evaluateHandle('__playwright_electron').then(handle => {- this._appHandlePromise.resolve(handle as any);- // Best-effort: in-process clients can rename the preview to make stack traces nicer.- (handle as any)._connection?.toImpl?.(handle)?._setPreview('ElectronModule');- }),- // Defer Electron's `ready` until the browser side is wired up for auto-attach.- this._worker.evaluate('__playwright_run()'),- ]);- }-- async browserWindow(page: Page): Promise<JSHandle<BrowserWindow>> {- let browserWindow = this._windows.get(page);- if (!browserWindow) {- const cdpSession = await this._context.newCDPSession(page);- const { targetInfo } = await cdpSession.send('Target.getTargetInfo');- const appHandle = await this._appHandlePromise;- browserWindow = await appHandle.evaluateHandle(({ BrowserWindow, webContents }, targetId) => {- const wc = webContents.fromDevToolsTargetId(targetId);- return BrowserWindow.fromWebContents(wc!)!;- }, targetInfo.targetId);- this._windows.set(page, browserWindow);- }- return browserWindow;- }-- async evaluate<R, Arg>(pageFunction: any, arg: Arg): Promise<R> {- const appHandle = await this._appHandlePromise;- return appHandle.evaluate(pageFunction, arg);- }-- async evaluateHandle<Arg>(pageFunction: any, arg: Arg): Promise<any> {- const appHandle = await this._appHandlePromise;- return await appHandle.evaluateHandle(pageFunction, arg);- }-}--async function waitForLine(progress: Progress, process: childProcess.ChildProcess, regex: RegExp) {- const promise = new ManualPromise<RegExpMatchArray>();-- // eslint-disable-next-line no-restricted-properties- const rl = readline.createInterface({ input: process.stderr! });-- const failError = new Error('Process failed to launch!');- const onFail = () => promise.reject(failError);- const onLine = (line: string) => {- const match = line.match(regex);- if (match)- promise.resolve(match);- };-- rl.addListener('line', onLine);- rl.addListener('close', onFail);- process.addListener('exit', onFail);- // Safe to add a listener — launchProcess attached its own error handler already.- process.addListener('error', onFail);-- try {- return await progress.race(promise);- } finally {- rl.removeListener('line', onLine);- rl.removeListener('close', onFail);- process.removeListener('exit', onFail);- process.removeListener('error', onFail);- }-}diff --git a/packages/playwright-core/src/electron/loader.ts b/packages/playwright-core/src/electron/loader.tsdeleted file mode 100644index 2cc15ec3b5..0000000000--- a/packages/playwright-core/src/electron/loader.ts+++ /dev/null@@ -1,103 +0,0 @@-/**- * Copyright (c) Microsoft Corporation.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--// Runs inside the Electron main process via `electron -r loader.js`.-// Must be self-contained — Electron's main process does not have access-// to playwright-core's bundled deps. Keep the chromium switches list in sync-// with packages/playwright-core/src/server/chromium/chromiumSwitches.ts.--const electronModule = require('electron') as typeof import('electron');--const { app } = electronModule;--const chromiumSwitches = [- '--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-edgeupdater',- '--disable-extensions',- '--disable-features=AvoidUnnecessaryBeforeUnloadCheckSync,BoundaryEventDispatchTracksNodeRemoval,DestroyProfileOnBrowserClose,DialMediaRouteProvider,GlobalMediaControls,HttpsUpgrades,LensOverlay,MediaRouter,PaintHolding,ThirdPartyStoragePartitioning,Translate,AutoDeElevate,RenderDocument,OptimizationHints,msForceBrowserSignIn,msEdgeUpdateLaunchServicesPreferredVersion',- '--enable-features=CDPScreenshotNewSurface',- '--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',- '--password-store=basic',- '--use-mock-keychain',- '--no-service-autorun',- '--export-tagged-pdf',- '--disable-search-engine-choice-screen',- '--unsafely-disable-devtools-self-xss-warnings',- '--edge-skip-compat-layer-relaunch',- '--enable-automation',- '--disable-infobars',- '--disable-sync',-];--// The new `chromium._connectToWorker`-based client reads these globals via-// the Node debugger to bootstrap the Electron app.-(globalThis as any).__playwright_electron = electronModule;--// Always pass user arguments first.-// https://github.com/microsoft/playwright/issues/16614-// https://github.com/microsoft/playwright/issues/29198-// argv layout: [Electron, -r, loader.js[, --no-sandbox], --inspect=0, --remote-debugging-port=0, ...userArgs]-process.argv.splice(1, process.argv.indexOf('--remote-debugging-port=0'));--for (const arg of chromiumSwitches) {- const match = arg.match(/--([^=]*)=?(.*)/)!;- app.commandLine.appendSwitch(match[1], match[2]);-}--// Defer the `ready` event until the Playwright client has wired up auto-attach.-const originalWhenReady = app.whenReady();-const originalEmit = app.emit.bind(app);-let readyEventArgs: any[];-app.emit = (event: string | symbol, ...args: any[]): boolean => {- if (event === 'ready') {- readyEventArgs = args;- return app.listenerCount('ready') > 0;- }- return originalEmit(event, ...args);-};--let isReady = false;-let whenReadyCallback: (event: any) => any;-const whenReadyPromise = new Promise<void>(f => whenReadyCallback = f);-app.isReady = () => isReady;-app.whenReady = () => whenReadyPromise;--(globalThis as any).__playwright_run = async () => {- // Wait for app to be ready to avoid browser-initialization races.- const event = await originalWhenReady;- isReady = true;- whenReadyCallback(event);- originalEmit('ready', ...readyEventArgs);-};diff --git a/packages/playwright-core/src/inprocess.ts b/packages/playwright-core/src/inprocess.tsindex c65ae864f4..fba4fb5ad7 100644--- a/packages/playwright-core/src/inprocess.ts+++ b/packages/playwright-core/src/inprocess.ts@@ -17,7 +17,6 @@import { nodePlatform } from '@utils/nodePlatform';import { AndroidServerLauncherImpl } from './androidServerImpl';import { BrowserServerLauncherImpl } from './browserServerImpl';-import { Electron } from './electron/electron';import { DispatcherConnection, PlaywrightDispatcher, RootDispatcher, createPlaywright } from './server';import { Connection } from './client/connection';import { packageRoot } from './package';@@ -44,7 +43,6 @@ export function createInProcessPlaywright(): PlaywrightAPI {playwrightAPI.firefox._serverLauncher = new BrowserServerLauncherImpl('firefox');playwrightAPI.webkit._serverLauncher = new BrowserServerLauncherImpl('webkit');playwrightAPI._android._serverLauncher = new AndroidServerLauncherImpl();- (playwrightAPI as any)._electron = new Electron(playwrightAPI);// Switch to async dispatch after we got Playwright object.dispatcherConnection.onmessage = message => setImmediate(() => clientConnection.dispatch(message));diff --git a/packages/playwright-core/src/protocol/validator.ts b/packages/playwright-core/src/protocol/validator.tsindex 8c0a3fcb23..b73bea2193 100644--- a/packages/playwright-core/src/protocol/validator.ts+++ b/packages/playwright-core/src/protocol/validator.ts@@ -1101,6 +1101,7 @@ scheme.EventTargetWaitForEventInfoParams = tObject({});scheme.AndroidDeviceWaitForEventInfoParams = tType('EventTargetWaitForEventInfoParams');scheme.BrowserContextWaitForEventInfoParams = tType('EventTargetWaitForEventInfoParams');+scheme.ElectronApplicationWaitForEventInfoParams = tType('EventTargetWaitForEventInfoParams');scheme.WebSocketWaitForEventInfoParams = tType('EventTargetWaitForEventInfoParams');scheme.PageWaitForEventInfoParams = tType('EventTargetWaitForEventInfoParams');scheme.DebuggerWaitForEventInfoParams = tType('EventTargetWaitForEventInfoParams');@@ -1108,10 +1109,100 @@ scheme.WorkerWaitForEventInfoParams = tType('EventTargetWaitForEventInfoParams')scheme.EventTargetWaitForEventInfoResult = tOptional(tObject({}));scheme.AndroidDeviceWaitForEventInfoResult = tType('EventTargetWaitForEventInfoResult');scheme.BrowserContextWaitForEventInfoResult = tType('EventTargetWaitForEventInfoResult');+scheme.ElectronApplicationWaitForEventInfoResult = tType('EventTargetWaitForEventInfoResult');scheme.WebSocketWaitForEventInfoResult = tType('EventTargetWaitForEventInfoResult');scheme.PageWaitForEventInfoResult = tType('EventTargetWaitForEventInfoResult');scheme.DebuggerWaitForEventInfoResult = tType('EventTargetWaitForEventInfoResult');scheme.WorkerWaitForEventInfoResult = tType('EventTargetWaitForEventInfoResult');+scheme.ElectronInitializer = tOptional(tObject({}));+scheme.ElectronLaunchParams = tObject({+ executablePath: tOptional(tString),+ args: tOptional(tArray(tString)),+ chromiumSandbox: tOptional(tBoolean),+ cwd: tOptional(tString),+ env: tOptional(tArray(tType('NameValue'))),+ timeout: tFloat,+ acceptDownloads: tOptional(tEnum(['accept', 'deny', 'internal-browser-default'])),+ bypassCSP: tOptional(tBoolean),+ colorScheme: tOptional(tEnum(['dark', 'light', 'no-preference', 'no-override'])),+ extraHTTPHeaders: tOptional(tArray(tType('NameValue'))),+ geolocation: tOptional(tObject({+ longitude: tFloat,+ latitude: tFloat,+ accuracy: tOptional(tFloat),+ })),+ httpCredentials: tOptional(tObject({+ username: tString,+ password: tString,+ origin: tOptional(tString),+ })),+ ignoreHTTPSErrors: tOptional(tBoolean),+ locale: tOptional(tString),+ offline: tOptional(tBoolean),+ recordVideo: tOptional(tObject({+ dir: tOptional(tString),+ size: tOptional(tObject({+ width: tInt,+ height: tInt,+ })),+ showActions: tOptional(tObject({+ duration: tOptional(tFloat),+ position: tOptional(tEnum(['top-left', 'top', 'top-right', 'bottom-left', 'bottom', 'bottom-right'])),+ fontSize: tOptional(tInt),+ })),+ })),+ strictSelectors: tOptional(tBoolean),+ timezoneId: tOptional(tString),+ tracesDir: tOptional(tString),+ artifactsDir: tOptional(tString),+ selectorEngines: tOptional(tArray(tType('SelectorEngine'))),+ testIdAttributeName: tOptional(tString),+});+scheme.ElectronLaunchResult = tObject({+ electronApplication: tChannel(['ElectronApplication']),+});+scheme.ElectronApplicationInitializer = tObject({+ context: tChannel(['BrowserContext']),+});+scheme.ElectronApplicationCloseEvent = tOptional(tObject({}));+scheme.ElectronApplicationConsoleEvent = tObject({+ type: tString,+ text: tString,+ args: tArray(tChannel(['ElementHandle', 'JSHandle'])),+ location: tObject({+ url: tString,+ lineNumber: tInt,+ columnNumber: tInt,+ }),+ timestamp: tFloat,+});+scheme.ElectronApplicationBrowserWindowParams = tObject({+ page: tChannel(['Page']),+});+scheme.ElectronApplicationBrowserWindowResult = tObject({+ handle: tChannel(['ElementHandle', 'JSHandle']),+});+scheme.ElectronApplicationEvaluateExpressionParams = tObject({+ expression: tString,+ isFunction: tOptional(tBoolean),+ arg: tType('SerializedArgument'),+});+scheme.ElectronApplicationEvaluateExpressionResult = tObject({+ value: tType('SerializedValue'),+});+scheme.ElectronApplicationEvaluateExpressionHandleParams = tObject({+ expression: tString,+ isFunction: tOptional(tBoolean),+ arg: tType('SerializedArgument'),+});+scheme.ElectronApplicationEvaluateExpressionHandleResult = tObject({+ handle: tChannel(['ElementHandle', 'JSHandle']),+});+scheme.ElectronApplicationUpdateSubscriptionParams = tObject({+ event: tEnum(['console']),+ enabled: tBoolean,+});+scheme.ElectronApplicationUpdateSubscriptionResult = tOptional(tObject({}));scheme.FrameInitializer = tObject({url: tString,name: tString,@@ -2568,6 +2659,7 @@ scheme.PlaywrightInitializer = tObject({firefox: tChannel(['BrowserType']),webkit: tChannel(['BrowserType']),android: tChannel(['Android']),+ electron: tChannel(['Electron']),utils: tOptional(tChannel(['LocalUtils'])),preLaunchedBrowser: tOptional(tChannel(['Browser'])),preConnectedAndroidDevice: tOptional(tChannel(['AndroidDevice'])),diff --git a/packages/playwright-core/src/server/DEPS.list b/packages/playwright-core/src/server/DEPS.listindex 8af50d834f..f9cf05a0b3 100644--- a/packages/playwright-core/src/server/DEPS.list+++ b/packages/playwright-core/src/server/DEPS.list@@ -25,6 +25,7 @@ node_modules/yazl./android/./bidi/./chromium/+./electron/./firefox/./webkit/diff --git a/packages/playwright-core/src/server/browserContext.ts b/packages/playwright-core/src/server/browserContext.tsindex ac66c000d4..1b7c0856e3 100644--- a/packages/playwright-core/src/server/browserContext.ts+++ b/packages/playwright-core/src/server/browserContext.ts@@ -726,8 +726,13 @@ export function validateBrowserContextOptions(options: types.BrowserContextOptiothrow new Error(`"deviceScaleFactor" option is not supported with null "viewport"`);if (options.noDefaultViewport && !!options.isMobile)throw new Error(`"isMobile" option is not supported with null "viewport"`);- if (options.acceptDownloads === undefined)+ if (options.acceptDownloads === undefined && browserOptions.name !== 'electron')options.acceptDownloads = 'accept';+ // Electron requires explicit acceptDownloads: true since we wait for+ // https://github.com/electron/electron/pull/41718 to be widely shipped.+ // In 6-12 months, we can remove this check.+ else if (options.acceptDownloads === undefined && browserOptions.name === 'electron')+ options.acceptDownloads = 'internal-browser-default';if (!options.viewport && !options.noDefaultViewport)options.viewport = { width: 1280, height: 720 };if (options.proxy)diff --git a/packages/playwright-core/src/server/dispatchers/electronDispatcher.ts b/packages/playwright-core/src/server/dispatchers/electronDispatcher.tsnew file mode 100644index 0000000000..4dcf68d0d1--- /dev/null+++ b/packages/playwright-core/src/server/dispatchers/electronDispatcher.ts@@ -0,0 +1,95 @@+/**+ * Copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { BrowserContextDispatcher } from './browserContextDispatcher';+import { Dispatcher } from './dispatcher';+import { JSHandleDispatcher, parseArgument, serializeResult } from './jsHandleDispatcher';+import { ElectronApplication } from '../electron/electron';++import type { RootDispatcher } from './dispatcher';+import type { PageDispatcher } from './pageDispatcher';+import type { ConsoleMessage } from '../console';+import type { Electron } from '../electron/electron';+import type * as channels from '@protocol/channels';+import type { Progress } from '@protocol/progress';+++export class ElectronDispatcher extends Dispatcher<Electron, channels.ElectronChannel, RootDispatcher> implements channels.ElectronChannel {+ _type_Electron = true;+ _denyLaunch: boolean;++ constructor(scope: RootDispatcher, electron: Electron, denyLaunch: boolean) {+ super(scope, electron, 'Electron', {});+ this._denyLaunch = denyLaunch;+ }++ async launch(params: channels.ElectronLaunchParams, progress: Progress): Promise<channels.ElectronLaunchResult> {+ if (this._denyLaunch)+ throw new Error(`Launching more browsers is not allowed.`);+ const electronApplication = await this._object.launch(progress, params);+ return { electronApplication: new ElectronApplicationDispatcher(this, electronApplication) };+ }+}++export class ElectronApplicationDispatcher extends Dispatcher<ElectronApplication, channels.ElectronApplicationChannel, ElectronDispatcher> implements channels.ElectronApplicationChannel {+ _type_EventTarget = true;+ _type_ElectronApplication = true;+ private readonly _subscriptions = new Set<channels.ElectronApplicationUpdateSubscriptionParams['event']>();++ constructor(scope: ElectronDispatcher, electronApplication: ElectronApplication) {+ super(scope, electronApplication, 'ElectronApplication', {+ context: BrowserContextDispatcher.from(scope, electronApplication.context())+ });+ this.addObjectListener(ElectronApplication.Events.Close, () => {+ this._dispatchEvent('close');+ this._dispose();+ });+ this.addObjectListener(ElectronApplication.Events.Console, (message: ConsoleMessage) => {+ if (!this._subscriptions.has('console'))+ return;+ this._dispatchEvent('console', {+ type: message.type(),+ text: message.text(),+ args: message.args().map(a => JSHandleDispatcher.fromJSHandle(this, a)),+ location: message.location(),+ timestamp: message.timestamp(),+ });+ });+ }++ async browserWindow(params: channels.ElectronApplicationBrowserWindowParams, progress: Progress): Promise<channels.ElectronApplicationBrowserWindowResult> {+ const handle = await this._object.browserWindow(progress, (params.page as PageDispatcher).page());+ return { handle: JSHandleDispatcher.fromJSHandle(this, handle) };+ }++ async evaluateExpression(params: channels.ElectronApplicationEvaluateExpressionParams, progress: Progress): Promise<channels.ElectronApplicationEvaluateExpressionResult> {+ const handle = await progress.race(this._object._nodeElectronHandlePromise);+ return { value: serializeResult(await handle.evaluateExpression(progress, params.expression, { isFunction: params.isFunction }, parseArgument(params.arg))) };+ }++ async evaluateExpressionHandle(params: channels.ElectronApplicationEvaluateExpressionHandleParams, progress: Progress): Promise<channels.ElectronApplicationEvaluateExpressionHandleResult> {+ const handle = await progress.race(this._object._nodeElectronHandlePromise);+ const result = await handle.evaluateExpressionHandle(progress, params.expression, { isFunction: params.isFunction }, parseArgument(params.arg));+ return { handle: JSHandleDispatcher.fromJSHandle(this, result) };+ }++ async updateSubscription(params: channels.ElectronApplicationUpdateSubscriptionParams, progress: Progress): Promise<void> {+ if (params.enabled)+ this._subscriptions.add(params.event);+ else+ this._subscriptions.delete(params.event);+ }+}diff --git a/packages/playwright-core/src/server/dispatchers/jsHandleDispatcher.ts b/packages/playwright-core/src/server/dispatchers/jsHandleDispatcher.tsindex b1d47c0f0b..8b494360a9 100644--- a/packages/playwright-core/src/server/dispatchers/jsHandleDispatcher.ts+++ b/packages/playwright-core/src/server/dispatchers/jsHandleDispatcher.ts@@ -19,12 +19,13 @@ import { ElementHandleDispatcher } from './elementHandlerDispatcher';import { parseSerializedValue, serializeValue } from '../../protocol/serializers';import type * as js from '../javascript';+import type { ElectronApplicationDispatcher } from './electronDispatcher';import type { FrameDispatcher } from './frameDispatcher';import type { PageDispatcher, WorkerDispatcher } from './pageDispatcher';import type * as channels from '@protocol/channels';import type { Progress } from '@protocol/progress';-export type JSHandleDispatcherParentScope = PageDispatcher | FrameDispatcher | WorkerDispatcher;+export type JSHandleDispatcherParentScope = PageDispatcher | FrameDispatcher | WorkerDispatcher | ElectronApplicationDispatcher;export class JSHandleDispatcher<ParentScope extends JSHandleDispatcherParentScope = JSHandleDispatcherParentScope> extends Dispatcher<js.JSHandle, channels.JSHandleChannel, ParentScope> implements channels.JSHandleChannel {_type_JSHandle = true;diff --git a/packages/playwright-core/src/server/dispatchers/playwrightDispatcher.ts b/packages/playwright-core/src/server/dispatchers/playwrightDispatcher.tsindex f11677855f..09a3b1dc8d 100644--- a/packages/playwright-core/src/server/dispatchers/playwrightDispatcher.ts+++ b/packages/playwright-core/src/server/dispatchers/playwrightDispatcher.ts@@ -22,6 +22,7 @@ import { AndroidDeviceDispatcher } from './androidDispatcher';import { BrowserDispatcher } from './browserDispatcher';import { BrowserTypeDispatcher } from './browserTypeDispatcher';import { Dispatcher } from './dispatcher';+import { ElectronDispatcher } from './electronDispatcher';import { LocalUtilsDispatcher } from './localUtilsDispatcher';import { APIRequestContextDispatcher } from './networkDispatchers';import { SdkObject } from '../instrumentation';@@ -59,6 +60,7 @@ export class PlaywrightDispatcher extends Dispatcher<Playwright, channels.Playwrfirefox,webkit,android,+ electron: new ElectronDispatcher(scope, playwright.electron, denyLaunch),utils: playwright.options.isServer ? undefined : new LocalUtilsDispatcher(scope, playwright),socksSupport: options.socksProxy ? new SocksSupportDispatcher(scope, playwright, options.socksProxy) : undefined,};diff --git a/packages/playwright-core/src/server/electron/DEPS.list b/packages/playwright-core/src/server/electron/DEPS.listnew file mode 100644index 0000000000..d918ec7567--- /dev/null+++ b/packages/playwright-core/src/server/electron/DEPS.list@@ -0,0 +1,6 @@+[*]+../+../../package.ts+@utils/**+@isomorphic/**+../chromium/\ No newline at end of filediff --git a/packages/playwright-core/src/server/electron/electron.ts b/packages/playwright-core/src/server/electron/electron.tsnew file mode 100644index 0000000000..4064465579--- /dev/null+++ b/packages/playwright-core/src/server/electron/electron.ts@@ -0,0 +1,329 @@+/**+ * Copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import fs from 'fs';+import os from 'os';+import path from 'path';+import * as readline from 'readline';++import { wrapInASCIIBox } from '@utils/ascii';+import { RecentLogsCollector } from '@utils/debugLogger';+import { eventsHelper } from '@utils/eventsHelper';+import { envArrayToObject, launchProcess } from '@utils/processLauncher';+import { ManualPromise } from '@isomorphic/manualPromise';+import { libPath } from '../../package';+import { validateBrowserContextOptions } from '../browserContext';+import { CRBrowser } from '../chromium/crBrowser';+import { CRConnection } from '../chromium/crConnection';+import { createHandle, CRExecutionContext } from '../chromium/crExecutionContext';+import { stackTraceToLocation } from '../chromium/crProtocolHelper';+import { ConsoleMessage } from '../console';+import { helper } from '../helper';+import { SdkObject } from '../instrumentation';+import * as js from '../javascript';+import { WebSocketTransport } from '../transport';+import { nullProgress } from '../progress';++import type { BrowserOptions, BrowserProcess } from '../browser';+import type { BrowserContext } from '../browserContext';+import type { CRBrowserContext } from '../chromium/crBrowser';+import type { CRSession } from '../chromium/crConnection';+import type { CRPage } from '../chromium/crPage';+import type { Protocol } from '../chromium/protocol';+import type { Page } from '../page';+import type { Playwright } from '../playwright';+import type { Progress } from '../progress';+import type * as types from '../types';+import type * as channels from '@protocol/channels';+import type * as childProcess from 'child_process';+import type { BrowserWindow } from 'electron';++const ARTIFACTS_FOLDER = path.join(os.tmpdir(), 'playwright-artifacts-');++export class ElectronApplication extends SdkObject {+ static Events = {+ Close: 'close',+ Console: 'console',+ };++ private _browserContext: CRBrowserContext;+ private _nodeConnection: CRConnection;+ private _nodeSession: CRSession;+ private _nodeExecutionContext: js.ExecutionContext | undefined;+ _nodeElectronHandlePromise: ManualPromise<js.JSHandle<typeof import('electron')>> = new ManualPromise();+ private _process: childProcess.ChildProcess;++ constructor(parent: SdkObject, browser: CRBrowser, nodeConnection: CRConnection, process: childProcess.ChildProcess) {+ super(parent, 'electron-app');+ this._process = process;+ this._browserContext = browser._defaultContext as CRBrowserContext;+ this._nodeConnection = nodeConnection;+ this._nodeSession = nodeConnection.rootSession;+ this._nodeSession.on('Runtime.executionContextCreated', async (event: Protocol.Runtime.executionContextCreatedPayload) => {+ if (!event.context.auxData || !event.context.auxData.isDefault)+ return;+ const crExecutionContext = new CRExecutionContext(this._nodeSession, event.context);+ this._nodeExecutionContext = new js.ExecutionContext(this, crExecutionContext, 'electron');+ const { result: remoteObject } = await crExecutionContext._client.send('Runtime.evaluate', {+ expression: `require('electron')`,+ contextId: event.context.id,+ // Needed after Electron 28 to get access to require: https://github.com/microsoft/playwright/issues/28048+ includeCommandLineAPI: true,+ });+ this._nodeElectronHandlePromise.resolve(new js.JSHandle(this._nodeExecutionContext!, 'object', 'ElectronModule', remoteObject.objectId!));+ });+ this._nodeSession.on('Runtime.consoleAPICalled', event => this._onConsoleAPI(event));+ const appClosePromise = new Promise(f => this.once(ElectronApplication.Events.Close, f));+ this._browserContext.setCustomCloseHandler(async () => {+ const electronHandle = await this._nodeElectronHandlePromise;+ await electronHandle.evaluate(({ app }) => app.quit()).catch(() => {});+ this._nodeConnection.close();+ await appClosePromise;+ });+ }++ async _onConsoleAPI(event: Protocol.Runtime.consoleAPICalledPayload) {+ if (event.executionContextId === 0) {+ // DevTools protocol stores the last 1000 console messages. These+ // messages are always reported even for removed execution contexts. In+ // this case, they are marked with executionContextId = 0 and are+ // reported upon enabling Runtime agent.+ //+ // Ignore these messages since:+ // - there's no execution context we can use to operate with message+ // arguments+ // - these messages are reported before Playwright clients can subscribe+ // to the 'console'+ // page event.+ //+ // @see https://github.com/GoogleChrome/puppeteer/issues/3865+ return;+ }+ if (!this._nodeExecutionContext)+ return;+ const args = event.args.map(arg => createHandle(this._nodeExecutionContext!, arg));+ const message = new ConsoleMessage(null, null, event.type, undefined, args, stackTraceToLocation(event.stackTrace), event.timestamp);+ this.emit(ElectronApplication.Events.Console, message);+ }++ async initialize() {+ await this._nodeSession.send('Runtime.enable', {});+ // Delay loading the app until browser is started and the browser targets are configured to auto-attach.+ await this._nodeSession.send('Runtime.evaluate', { expression: '__playwright_run()' });+ }++ process(): childProcess.ChildProcess {+ return this._process;+ }++ context(): BrowserContext {+ return this._browserContext;+ }++ async close(progress: Progress) {+ // This will call BrowserContext.setCustomCloseHandler.+ await this._browserContext.close(progress, { reason: 'Application exited' });+ }++ async browserWindow(progress: Progress, page: Page): Promise<js.JSHandle<BrowserWindow>> {+ // Assume CRPage as Electron is always Chromium.+ const targetId = (page.delegate as CRPage)._targetId;+ const electronHandle = await progress.race(this._nodeElectronHandlePromise);+ return await progress.race(electronHandle.evaluateHandle(({ BrowserWindow, webContents }, targetId) => {+ const wc = webContents.fromDevToolsTargetId(targetId);+ return BrowserWindow.fromWebContents(wc!)!;+ }, targetId));+ }+}++export class Electron extends SdkObject {+ constructor(playwright: Playwright) {+ super(playwright, 'electron');+ this.logName = 'browser';+ }++ async launch(progress: Progress, options: Omit<channels.ElectronLaunchParams, 'timeout'>): Promise<ElectronApplication> {+ let app: ElectronApplication | undefined = undefined;+ // --remote-debugging-port=0 must be the last playwright's argument, loader.ts relies on it.+ let electronArguments = ['--inspect=0', '--remote-debugging-port=0', ...(options.args || [])];++ if (os.platform() === 'linux') {+ if (!options.chromiumSandbox && electronArguments.indexOf('--no-sandbox') === -1)+ electronArguments.unshift('--no-sandbox');+ }++ let artifactsDir: string;+ const tempDirectories: string[] = [];+ if (options.artifactsDir) {+ artifactsDir = options.artifactsDir;+ } else {+ artifactsDir = await progress.race(fs.promises.mkdtemp(ARTIFACTS_FOLDER));+ tempDirectories.push(artifactsDir);+ }+ const browserLogsCollector = new RecentLogsCollector();+ const env = options.env ? envArrayToObject(options.env) : process.env;++ let command: string;+ if (options.executablePath) {+ command = options.executablePath;+ } else {+ try {+ // By default we fallback to the Electron App executable path.+ // 'electron/index.js' resolves to the actual Electron App.+ command = require('electron/index.js');+ } catch (error: any) {+ if ((error as NodeJS.ErrnoException)?.code === 'MODULE_NOT_FOUND') {+ throw new Error('\n' + wrapInASCIIBox([+ 'Electron executablePath not found!',+ 'Please install it using `npm install -D electron` or set the executablePath to your Electron executable.',+ ].join('\n'), 1));+ }+ throw error;+ }+ // Only use our own loader for non-packaged apps.+ // Packaged apps might have their own command line handling.+ electronArguments.unshift('-r', libPath('server', 'electron', 'loader.js'));+ }+ let shell = false;+ if (process.platform === 'win32') {+ // On Windows in order to run .cmd files, shell: true is required.+ // https://github.com/nodejs/node/issues/52554+ shell = true;+ // On Windows, we need to quote the executable path and arguments due to shell: true.+ // We allso pass the arguments as a single string due to DEP0190,+ // see https://github.com/microsoft/playwright/issues/38278.+ command = [command, ...electronArguments].map(arg => `"${escapeDoubleQuotes(arg)}"`).join(' ');+ electronArguments = [];+ }++ // When debugging Playwright test that runs Electron, NODE_OPTIONS+ // will make the debugger attach to Electron's Node. But Playwright+ // also needs to attach to drive the automation. Disable external debugging.+ delete env.NODE_OPTIONS;+ const { launchedProcess, gracefullyClose, kill } = await progress.race(launchProcess({+ command,+ args: electronArguments,+ env,+ log: (message: string) => {+ progress.log(message);+ browserLogsCollector.log(message);+ },+ shell,+ stdio: 'pipe',+ cwd: options.cwd,+ tempDirectories,+ attemptToGracefullyClose: () => app!.close(nullProgress),+ handleSIGINT: true,+ handleSIGTERM: true,+ handleSIGHUP: true,+ onExit: () => app?.emit(ElectronApplication.Events.Close),+ }));++ // All waitForLines must be started immediately.+ // Otherwise the lines might come before we are ready.+ const waitForXserverError = waitForLine(progress, launchedProcess, /Unable to open X display/).then(() => {+ throw new Error([+ 'Unable to open X display!',+ `================================`,+ 'Most likely this is because there is no X server available.',+ "Use 'xvfb-run' on Linux to launch your tests with an emulated display server.",+ "For example: 'xvfb-run npm run test:e2e'",+ `================================`,+ progress.metadata.log+ ].join('\n'));+ });+ const nodeMatchPromise = waitForLine(progress, launchedProcess, /^Debugger listening on (ws:\/\/.*)$/);+ const chromeMatchPromise = waitForLine(progress, launchedProcess, /^DevTools listening on (ws:\/\/.*)$/);+ const debuggerDisconnectPromise = waitForLine(progress, launchedProcess, /Waiting for the debugger to disconnect\.\.\./);++ try {+ const nodeMatch = await nodeMatchPromise;+ const nodeTransport = await WebSocketTransport.connect(progress, nodeMatch[1]);+ const nodeConnection = new CRConnection(this, nodeTransport, helper.debugProtocolLogger(), browserLogsCollector);+ // Immediately release exiting process under debug.+ debuggerDisconnectPromise.then(() => {+ nodeTransport.close();+ }).catch(() => {});++ const chromeMatch = await progress.race(Promise.race([+ chromeMatchPromise,+ waitForXserverError,+ ]));+ const chromeTransport = await WebSocketTransport.connect(progress, chromeMatch[1]);+ const browserProcess: BrowserProcess = {+ onclose: undefined,+ process: launchedProcess,+ close: gracefullyClose,+ kill+ };+ const contextOptions: types.BrowserContextOptions = {+ ...options,+ noDefaultViewport: true,+ };+ const browserOptions: BrowserOptions = {+ name: 'electron',+ browserType: 'chromium',+ headful: true,+ persistent: contextOptions,+ browserProcess,+ protocolLogger: helper.debugProtocolLogger(),+ browserLogsCollector,+ artifactsDir,+ downloadsPath: artifactsDir,+ tracesDir: options.tracesDir || artifactsDir,+ originalLaunchOptions: {},+ };+ validateBrowserContextOptions(contextOptions, browserOptions);+ const browser = await progress.race(CRBrowser.connect(this.attribution.playwright, chromeTransport, browserOptions));+ app = new ElectronApplication(this, browser, nodeConnection, launchedProcess);+ await progress.race(app.initialize());+ return app;+ } catch (error) {+ await progress.race(kill());+ throw error;+ }+ }+}++async function waitForLine(progress: Progress, process: childProcess.ChildProcess, regex: RegExp) {+ const promise = new ManualPromise<RegExpMatchArray>();+ // eslint-disable-next-line no-restricted-properties+ const rl = readline.createInterface({ input: process.stderr! });+ const failError = new Error('Process failed to launch!');+ const listeners = [+ eventsHelper.addEventListener(rl, 'line', onLine),+ eventsHelper.addEventListener(rl, 'close', () => promise.reject(failError)),+ eventsHelper.addEventListener(process, 'exit', () => promise.reject(failError)),+ // It is Ok to remove error handler because we did not create process and there is another listener.+ eventsHelper.addEventListener(process, 'error', () => promise.reject(failError)),+ ];++ function onLine(line: string) {+ const match = line.match(regex);+ if (match)+ promise.resolve(match);+ }++ try {+ return await progress.race(promise);+ } finally {+ eventsHelper.removeEventListeners(listeners);+ }+}++function escapeDoubleQuotes(str: string): string {+ return str.replace(/"/g, '\\"');+}diff --git a/packages/playwright-core/src/server/electron/loader.ts b/packages/playwright-core/src/server/electron/loader.tsnew file mode 100644index 0000000000..80c6f76fb3--- /dev/null+++ b/packages/playwright-core/src/server/electron/loader.ts@@ -0,0 +1,54 @@+/**+ * Copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { app } from 'electron';+import { chromiumSwitches } from '../chromium/chromiumSwitches';++// Always pass user arguments first, see https://github.com/microsoft/playwright/issues/16614 and+// https://github.com/microsoft/playwright/issues/29198.+// [Electron, -r, loader.js[, --no-sandbox>], --inspect=0, --remote-debugging-port=0, ...args]+process.argv.splice(1, process.argv.indexOf('--remote-debugging-port=0'));++for (const arg of chromiumSwitches()) {+ const match = arg.match(/--([^=]*)=?(.*)/)!;+ app.commandLine.appendSwitch(match[1], match[2]);+}++// Defer ready event.+const originalWhenReady = app.whenReady();+const originalEmit = app.emit.bind(app);+let readyEventArgs: any[];+app.emit = (event: string | symbol, ...args: any[]): boolean => {+ if (event === 'ready') {+ readyEventArgs = args;+ return app.listenerCount('ready') > 0;+ }+ return originalEmit(event, ...args);+};++let isReady = false;+let whenReadyCallback: (event: any) => any;+const whenReadyPromise = new Promise<void>(f => whenReadyCallback = f);+app.isReady = () => isReady;+app.whenReady = () => whenReadyPromise;++(globalThis as any).__playwright_run = async () => {+ // Wait for app to be ready to avoid browser initialization races.+ const event = await originalWhenReady;+ isReady = true;+ whenReadyCallback(event);+ originalEmit('ready', ...readyEventArgs);+};diff --git a/packages/playwright-core/src/server/playwright.ts b/packages/playwright-core/src/server/playwright.tsindex 26d13551c4..3430f7829f 100644--- a/packages/playwright-core/src/server/playwright.ts+++ b/packages/playwright-core/src/server/playwright.ts@@ -20,6 +20,7 @@ import { BidiChromium } from './bidi/bidiChromium';import { BidiFirefox } from './bidi/bidiFirefox';import { Chromium } from './chromium/chromium';import { DebugController } from './debugController';+import { Electron } from './electron/electron';import { Firefox } from './firefox/firefox';import { SdkObject, createRootSdkObject } from './instrumentation';import { WebKit } from './webkit/webkit';@@ -38,6 +39,7 @@ type PlaywrightOptions = {export class Playwright extends SdkObject {readonly chromium: BrowserType;readonly android: Android;+ readonly electron: Electron;readonly firefox: BrowserType;readonly webkit: BrowserType;readonly options: PlaywrightOptions;@@ -58,6 +60,7 @@ export class Playwright extends SdkObject {this.chromium = new Chromium(this, new BidiChromium(this));this.firefox = new Firefox(this, new BidiFirefox(this));this.webkit = new WebKit(this);+ this.electron = new Electron(this);this.android = new Android(this, new AdbBackend());this.debugController = new DebugController(this);}diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.tsindex cb4cfb3767..f3488dd71a 100644--- a/packages/playwright-core/types/types.d.ts+++ b/packages/playwright-core/types/types.d.ts@@ -16702,6 +16702,450 @@ class TimeoutError extends Error {export const devices: Devices;+//@ts-ignore this will be any if electron is not installed+type ElectronType = typeof import('electron');++/**+ * Electron application representation. You can use+ * [electron.launch([options])](https://playwright.dev/docs/api/class-electron#electron-launch) to obtain the+ * application instance. This instance you can control main electron process as well as work with Electron windows:+ *+ * ```js+ * 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();+ * })();+ * ```+ *+ */+export interface ElectronApplication {+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a [Promise], then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * would wait for the promise to resolve and return its value.+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a non-[Serializable] value, then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by+ * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ */+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a [Promise], then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * would wait for the promise to resolve and return its value.+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a non-[Serializable] value, then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by+ * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ */+ evaluate<R, Arg>(pageFunction: PageFunctionOn<ElectronType, Arg, R>, arg: Arg): Promise<R>;+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a [Promise], then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * would wait for the promise to resolve and return its value.+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a non-[Serializable] value, then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by+ * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ */+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a [Promise], then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * would wait for the promise to resolve and return its value.+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a non-[Serializable] value, then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by+ * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ */+ evaluate<R>(pageFunction: PageFunctionOn<ElectronType, void, R>, arg?: any): Promise<R>;++ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression)+ * as a [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * The only difference between+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * and+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * is that+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * If the function passed to the+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns a [Promise], then+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * would wait for the promise to resolve and return its value.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression).+ */+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression)+ * as a [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * The only difference between+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * and+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * is that+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * If the function passed to the+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns a [Promise], then+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * would wait for the promise to resolve and return its value.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression).+ */+ evaluateHandle<R, Arg>(pageFunction: PageFunctionOn<ElectronType, Arg, R>, arg: Arg): Promise<SmartHandle<R>>;+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression)+ * as a [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * The only difference between+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * and+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * is that+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * If the function passed to the+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns a [Promise], then+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * would wait for the promise to resolve and return its value.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression).+ */+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression)+ * as a [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * The only difference between+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * and+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * is that+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * If the function passed to the+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns a [Promise], then+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * would wait for the promise to resolve and return its value.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression).+ */+ evaluateHandle<R>(pageFunction: PageFunctionOn<ElectronType, void, R>, arg?: any): Promise<SmartHandle<R>>;+ /**+ * This event is issued when the application process has been terminated.+ */+ on(event: 'close', listener: () => any): this;++ /**+ * Emitted when JavaScript within the Electron main process calls one of console API methods, e.g. `console.log` or+ * `console.dir`.+ *+ * The arguments passed into `console.log` are available on the+ * [ConsoleMessage](https://playwright.dev/docs/api/class-consolemessage) event handler argument.+ *+ * **Usage**+ *+ * ```js+ * electronApp.on('console', async msg => {+ * const values = [];+ * for (const arg of msg.args())+ * values.push(await arg.jsonValue());+ * console.log(...values);+ * });+ * await electronApp.evaluate(() => console.log('hello', 5, { foo: 'bar' }));+ * ```+ *+ */+ on(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;++ /**+ * This event is issued for every window that is created **and loaded** in Electron. It contains a+ * [Page](https://playwright.dev/docs/api/class-page) that can be used for Playwright automation.+ */+ on(event: 'window', listener: (page: Page) => any): this;++ /**+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ */+ once(event: 'close', listener: () => any): this;++ /**+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ */+ once(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;++ /**+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ */+ once(event: 'window', listener: (page: Page) => any): this;++ /**+ * This event is issued when the application process has been terminated.+ */+ addListener(event: 'close', listener: () => any): this;++ /**+ * Emitted when JavaScript within the Electron main process calls one of console API methods, e.g. `console.log` or+ * `console.dir`.+ *+ * The arguments passed into `console.log` are available on the+ * [ConsoleMessage](https://playwright.dev/docs/api/class-consolemessage) event handler argument.+ *+ * **Usage**+ *+ * ```js+ * electronApp.on('console', async msg => {+ * const values = [];+ * for (const arg of msg.args())+ * values.push(await arg.jsonValue());+ * console.log(...values);+ * });+ * await electronApp.evaluate(() => console.log('hello', 5, { foo: 'bar' }));+ * ```+ *+ */+ addListener(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;++ /**+ * This event is issued for every window that is created **and loaded** in Electron. It contains a+ * [Page](https://playwright.dev/docs/api/class-page) that can be used for Playwright automation.+ */+ addListener(event: 'window', listener: (page: Page) => any): this;++ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ removeListener(event: 'close', listener: () => any): this;++ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ removeListener(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;++ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ removeListener(event: 'window', listener: (page: Page) => any): this;++ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ off(event: 'close', listener: () => any): this;++ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ off(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;++ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ off(event: 'window', listener: (page: Page) => any): this;++ /**+ * This event is issued when the application process has been terminated.+ */+ prependListener(event: 'close', listener: () => any): this;++ /**+ * Emitted when JavaScript within the Electron main process calls one of console API methods, e.g. `console.log` or+ * `console.dir`.+ *+ * The arguments passed into `console.log` are available on the+ * [ConsoleMessage](https://playwright.dev/docs/api/class-consolemessage) event handler argument.+ *+ * **Usage**+ *+ * ```js+ * electronApp.on('console', async msg => {+ * const values = [];+ * for (const arg of msg.args())+ * values.push(await arg.jsonValue());+ * console.log(...values);+ * });+ * await electronApp.evaluate(() => console.log('hello', 5, { foo: 'bar' }));+ * ```+ *+ */+ prependListener(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;++ /**+ * This event is issued for every window that is created **and loaded** in Electron. It contains a+ * [Page](https://playwright.dev/docs/api/class-page) that can be used for Playwright automation.+ */+ prependListener(event: 'window', listener: (page: Page) => any): this;++ /**+ * Returns the BrowserWindow object that corresponds to the given Playwright page.+ * @param page Page to retrieve the window for.+ */+ browserWindow(page: Page): Promise<JSHandle>;++ /**+ * Closes Electron application.+ */+ close(): Promise<void>;++ /**+ * This method returns browser context that can be used for setting up context-wide routing, etc.+ */+ context(): BrowserContext;++ /**+ * Convenience method that waits for the first application window to be opened.+ *+ * **Usage**+ *+ * ```js+ * const electronApp = await electron.launch({+ * args: ['main.js']+ * });+ * const window = await electronApp.firstWindow();+ * // ...+ * ```+ *+ * @param options+ */+ firstWindow(options?: {+ /**+ * Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The+ * default value can be changed by using the+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout).+ */+ timeout?: number;+ }): Promise<Page>;++ /**+ * Returns the main process for this Electron Application.+ */+ process(): ChildProcess;++ /**+ * This event is issued when the application process has been terminated.+ */+ waitForEvent(event: 'close', optionsOrPredicate?: { predicate?: () => boolean | Promise<boolean>, timeout?: number } | (() => boolean | Promise<boolean>)): Promise<void>;++ /**+ * Emitted when JavaScript within the Electron main process calls one of console API methods, e.g. `console.log` or+ * `console.dir`.+ *+ * The arguments passed into `console.log` are available on the+ * [ConsoleMessage](https://playwright.dev/docs/api/class-consolemessage) event handler argument.+ *+ * **Usage**+ *+ * ```js+ * electronApp.on('console', async msg => {+ * const values = [];+ * for (const arg of msg.args())+ * values.push(await arg.jsonValue());+ * console.log(...values);+ * });+ * await electronApp.evaluate(() => console.log('hello', 5, { foo: 'bar' }));+ * ```+ *+ */+ waitForEvent(event: 'console', optionsOrPredicate?: { predicate?: (consoleMessage: ConsoleMessage) => boolean | Promise<boolean>, timeout?: number } | ((consoleMessage: ConsoleMessage) => boolean | Promise<boolean>)): Promise<ConsoleMessage>;++ /**+ * This event is issued for every window that is created **and loaded** in Electron. It contains a+ * [Page](https://playwright.dev/docs/api/class-page) that can be used for Playwright automation.+ */+ waitForEvent(event: 'window', optionsOrPredicate?: { predicate?: (page: Page) => boolean | Promise<boolean>, timeout?: number } | ((page: Page) => boolean | Promise<boolean>)): Promise<Page>;+++ /**+ * Convenience method that returns all the opened windows.+ */+ windows(): Array<Page>;++ [Symbol.asyncDispose](): Promise<void>;+}+export type AndroidElementInfo = {clazz: string;desc: string;@@ -16807,6 +17251,7 @@ export type AndroidKey ='Copy' |'Paste';+export const _electron: Electron;export const _android: Android;//@ts-ignore this will be any if electron is not installed@@ -16818,7 +17263,7 @@ type ElectronType = typeof import('electron');* application instance. This instance you can control main electron process as well as work with Electron windows:** ```js- * import { _electron as electron } from 'playwright';+ * const { _electron: electron } = require('playwright');** (async () => {* // Launch Electron app.@@ -16854,22 +17299,151 @@ export interface ElectronApplication {* [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).** If the function passed to the- * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a [Promise], then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * would wait for the promise to resolve and return its value.+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a non-[Serializable] value, then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by+ * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ */+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a [Promise], then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * would wait for the promise to resolve and return its value.+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a non-[Serializable] value, then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by+ * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ */+ evaluate<R, Arg>(pageFunction: PageFunctionOn<ElectronType, Arg, R>, arg: Arg): Promise<R>;+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a [Promise], then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * would wait for the promise to resolve and return its value.+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a non-[Serializable] value, then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by+ * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ */+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a [Promise], then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * would wait for the promise to resolve and return its value.+ *+ * If the function passed to the+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns a non-[Serializable] value, then+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by+ * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ */+ evaluate<R>(pageFunction: PageFunctionOn<ElectronType, void, R>, arg?: any): Promise<R>;++ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression)+ * as a [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * The only difference between+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * and+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * is that+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * If the function passed to the+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns a [Promise], then+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * would wait for the promise to resolve and return its value.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression).+ */+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression)+ * as a [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * The only difference between+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * and+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * is that+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * If the function passed to the+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns a [Promise], then+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * would wait for the promise to resolve and return its value.+ * @param pageFunction Function to be evaluated in the main Electron process.+ * @param arg Optional argument to pass to+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression).+ */+ evaluateHandle<R, Arg>(pageFunction: PageFunctionOn<ElectronType, Arg, R>, arg: Arg): Promise<SmartHandle<R>>;+ /**+ * Returns the return value of+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression)+ * as a [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * The only difference between+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * and+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * is that+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)+ * returns [JSHandle](https://playwright.dev/docs/api/class-jshandle).+ *+ * If the function passed to the+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)* returns a [Promise], then- * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)* would wait for the promise to resolve and return its value.- *- * If the function passed to the- * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)- * returns a non-[Serializable] value, then- * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)- * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by- * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.* @param pageFunction Function to be evaluated in the main Electron process.* @param arg Optional argument to pass to- * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-option-expression).+ * [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression).*/- evaluate: JSHandle<ElectronType>['evaluate'];/*** Returns the return value of* [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression)@@ -16892,7 +17466,7 @@ export interface ElectronApplication {* @param arg Optional argument to pass to* [`pageFunction`](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle-option-expression).*/- evaluateHandle: JSHandle<ElectronType>['evaluateHandle'];+ evaluateHandle<R>(pageFunction: PageFunctionOn<ElectronType, void, R>, arg?: any): Promise<SmartHandle<R>>;/*** This event is issued when the application process has been terminated.*/@@ -17124,8 +17698,6 @@ export interface ElectronApplication {[Symbol.asyncDispose](): Promise<void>;}-export const _electron: Electron;-// This is required to not export everything by default. See https://github.com/Microsoft/TypeScript/issues/19545#issuecomment-340490459export {};@@ -21317,11 +21889,16 @@ export interface WebSocket {}/**- * Playwright has **experimental** support for Electron automation, exposed as `_electron`. An example of the Electron- * automation script would be:+ * Playwright has **experimental** support for Electron automation. You can access electron namespace via:+ *+ * ```js+ * const { _electron } = require('playwright');+ * ```+ *+ * An example of the Electron automation script would be:** ```js- * import { _electron as electron } from 'playwright';+ * const { _electron: electron } = require('playwright');** (async () => {* // Launch Electron app.@@ -21361,127 +21938,6 @@ export interface WebSocket {* - Ensure that `nodeCliInspect`* ([FuseV1Options.EnableNodeCliInspectArguments](https://www.electronjs.org/docs/latest/tutorial/fuses#nodecliinspect))* fuse is **not** set to `false`.- *- * **Migrating from v1.59**- *- * A number of launch options have been removed after v1.59. See below for alternatives.- * - `recordHar` - use- * [tracing.startHar(path[, options])](https://playwright.dev/docs/api/class-tracing#tracing-start-har).- *- * ```js- * const electronApp = await electron.launch({ args: ['main.js'] });- * await electronApp.context().tracing.startHar('network.har');- * // ... drive the app ...- * await electronApp.context().tracing.stopHar();- * await electronApp.close();- * ```- *- * - `recordVideo` - use- * [screencast.start([options])](https://playwright.dev/docs/api/class-screencast#screencast-start) on each- * window.- *- * ```js- * const electronApp = await electron.launch({ args: ['main.js'] });- * const window = await electronApp.firstWindow();- * await window.screencast.start({ path: 'video.webm' });- * // ... drive the window ...- * await window.screencast.stop();- * await electronApp.close();- * ```- *- * - `colorScheme` - use- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) on each window.- *- * ```js- * const window = await electronApp.firstWindow();- * await window.emulateMedia({ colorScheme: 'dark' });- * ```- *- * - `extraHTTPHeaders` - use- * [browserContext.setExtraHTTPHeaders(headers)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-extra-http-headers).- *- * ```js- * await electronApp.context().setExtraHTTPHeaders({ 'X-My-Header': 'value' });- * ```- *- * - `geolocation` - use- * [browserContext.setGeolocation(geolocation)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-geolocation).- *- * ```js- * await electronApp.context().setGeolocation({ latitude: 48.858455, longitude: 2.294474 });- * ```- *- * - `httpCredentials` - use- * [browserContext.setHTTPCredentials(httpCredentials)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-http-credentials).- *- * ```js- * await electronApp.context().setHTTPCredentials({ username: 'user', password: 'pass' });- * ```- *- * - `offline` - use- * [browserContext.setOffline(offline)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-offline).- *- * ```js- * await electronApp.context().setOffline(true);- * ```- *- * - `bypassCSP` - disable CSP at the `BrowserWindow` level via Electron's- * [web preferences](https://www.electronjs.org/docs/latest/api/structures/web-preferences). Note that- * `webSecurity: false` also disables CORS and the Same-Origin Policy.- *- * ```js- * const win = new BrowserWindow({- * webPreferences: {- * webSecurity: false,- * },- * });- * ```- *- * - `ignoreHTTPSErrors`- *- * There are several ways to relax HTTPS checks in Electron. Pick the one that matches the scope you need.- *- * Per-window, allow mixed content through- * [web preferences](https://www.electronjs.org/docs/latest/api/structures/web-preferences):- *- * ```js- * const win = new BrowserWindow({- * webPreferences: {- * allowRunningInsecureContent: true,- * },- * });- * ```- *- * Process-wide, ignore certificate errors via Chromium command-line switches (must run before the `ready` event):- *- * ```js- * const { app } = require('electron');- * app.commandLine.appendSwitch('ignore-certificate-errors');- * // Optional: also ignore localhost certificate errors when testing on an IP.- * app.commandLine.appendSwitch('allow-insecure-localhost', 'true');- * ```- *- * Per-request, accept the certificate manually via the- * [`certificate-error`](https://www.electronjs.org/docs/latest/api/app#event-certificate-error) event:- *- * ```js- * app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {- * event.preventDefault();- * callback(true);- * });- * ```- *- * - `timezoneId` - set an environment variable at the very top of the main file, before any other logic or Chromium- * windows are initialized.- *- * ```js- * // main.js- * process.env.TZ = 'Europe/London';- *- * const { app } = require('electron');- * // ... rest of your app logic- * ```- **/export interface Electron {/**@@ -21490,16 +21946,41 @@ export interface Electron {* @param options*/launch(options?: {+ /**+ * Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.+ */+ acceptDownloads?: boolean;+/*** Additional arguments to pass to the application when launching. You typically pass the main script name here.*/args?: Array<string>;+ /**+ * If 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.+ */+ artifactsDir?: string;++ /**+ * Toggles bypassing page's Content-Security-Policy. Defaults to `false`.+ */+ bypassCSP?: boolean;+/*** Enable Chromium sandboxing. Defaults to `false`.*/chromiumSandbox?: boolean;+ /**+ * Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)+ * media feature, supported values are `'light'` and `'dark'`. See+ * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.+ * Passing `null` resets emulation to system defaults. Defaults to `'light'`.+ */+ colorScheme?: null|"light"|"dark"|"no-preference";+/*** Current working directory to launch application from.*/@@ -21516,11 +21997,180 @@ export interface Electron {*/executablePath?: string;+ /**+ * An object containing additional HTTP headers to be sent with every request. Defaults to none.+ */+ extraHTTPHeaders?: { [key: string]: string; };++ geolocation?: {+ /**+ * Latitude between -90 and 90.+ */+ latitude: number;++ /**+ * Longitude between -180 and 180.+ */+ longitude: number;++ /**+ * Non-negative accuracy value. Defaults to `0`.+ */+ accuracy?: number;+ };++ /**+ * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no+ * origin is specified, the username and password are sent to any servers upon unauthorized responses.+ */+ httpCredentials?: {+ username: string;++ password: string;++ /**+ * Restrain sending http credentials on specific origin (scheme://host:port).+ */+ origin?: string;++ /**+ * This option only applies to the requests sent from corresponding+ * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) and does not affect requests sent from+ * the browser. `'always'` - `Authorization` header with basic authentication credentials will be sent with the each+ * API request. `'unauthorized` - the credentials are only sent when 401 (Unauthorized) response with+ * `WWW-Authenticate` header is received. Defaults to `'unauthorized'`.+ */+ send?: "unauthorized"|"always";+ };++ /**+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.+ */+ ignoreHTTPSErrors?: boolean;++ /**+ * Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,+ * `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default+ * locale. Learn more about emulation in our [emulation guide](https://playwright.dev/docs/emulation#locale--timezone).+ */+ locale?: string;++ /**+ * Whether to emulate network being offline. Defaults to `false`. Learn more about+ * [network emulation](https://playwright.dev/docs/emulation#offline).+ */+ offline?: boolean;++ /**+ * Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into `recordHar.path` file.+ * If not specified, the HAR is not recorded. Make sure to await+ * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for+ * the HAR to be saved.+ */+ recordHar?: {+ /**+ * Optional setting to control whether to omit request content from the HAR. Defaults to `false`. Deprecated, use+ * `content` policy instead.+ */+ omitContent?: boolean;++ /**+ * Optional setting to control resource content management. If `omit` is specified, content is not persisted. If+ * `attach` is specified, resources are persisted as separate files or entries in the ZIP archive. If `embed` is+ * specified, content is stored inline the HAR file as per HAR specification. Defaults to `attach` for `.zip` output+ * files and to `embed` for all other file extensions.+ */+ content?: "omit"|"embed"|"attach";++ /**+ * Path on the filesystem to write the HAR file to. If the file name ends with `.zip`, `content: 'attach'` is used by+ * default.+ */+ path: string;++ /**+ * When 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 to `full`.+ */+ mode?: "full"|"minimal";++ /**+ * A glob or regex pattern to filter requests that are stored in the HAR. When a+ * [`baseURL`](https://playwright.dev/docs/api/class-browser#browser-new-context-option-base-url) via the context+ * options was provided and the passed URL is a path, it gets merged via the+ * [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor. Defaults to none.+ */+ urlFilter?: string|RegExp;+ };++ /**+ * Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded.+ * Make sure to await+ * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for+ * videos to be saved.+ */+ recordVideo?: {+ /**+ * Path to the directory to put videos into. If not specified, the videos will be stored in `artifactsDir` (see+ * [browserType.launch([options])](https://playwright.dev/docs/api/class-browsertype#browser-type-launch) options).+ */+ dir?: string;++ /**+ * Optional dimensions of the recorded videos. If not specified the size will be equal to `viewport` scaled down to+ * fit into 800x800. If `viewport` is 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.+ */+ size?: {+ /**+ * Video frame width.+ */+ width: number;++ /**+ * Video frame height.+ */+ height: number;+ };++ /**+ * If specified, enables visual annotations on interacted elements during video recording.+ */+ showActions?: {+ /**+ * How long each annotation is displayed in milliseconds. Defaults to `500`.+ */+ duration?: number;++ /**+ * Position of the action title overlay. Defaults to `"top-right"`.+ */+ position?: "top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right";++ /**+ * Font size of the action title in pixels. Defaults to `24`.+ */+ fontSize?: number;+ };+ };+/*** Maximum time in milliseconds to wait for the application to start. Defaults to `30000` (30 seconds). Pass `0` to* disable timeout.*/timeout?: number;++ /**+ * Changes the timezone of the context. See+ * [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)+ * for a list of supported timezone IDs. Defaults to the system timezone.+ */+ timezoneId?: string;++ /**+ * If specified, traces are saved into this directory.+ */+ tracesDir?: string;}): Promise<ElectronApplication>;}diff --git a/packages/playwright-electron/.npmignore b/packages/playwright-electron/.npmignoredeleted file mode 100644index 2ea87ab608..0000000000--- a/packages/playwright-electron/.npmignore+++ /dev/null@@ -1,8 +0,0 @@-**/*--!README.md-!LICENSE-!lib/**-!index.d.ts-!types.d.ts-!index.jsdiff --git a/packages/playwright-electron/README.md b/packages/playwright-electron/README.mddeleted file mode 100644index bfdd76e689..0000000000--- a/packages/playwright-electron/README.md+++ /dev/null@@ -1,170 +0,0 @@-# 🎭 Playwright for Electron--[](https://www.npmjs.com/package/@playwright/electron) [](https://aka.ms/playwright/discord)--## [Documentation](https://playwright.dev/docs/api/class-electron) | [API reference](https://playwright.dev/docs/api/class-electron)--Drive [Electron](https://www.electronjs.org/) apps with the full Playwright API — evaluate in the main process, control each `BrowserWindow` as a Playwright [Page](https://playwright.dev/docs/api/class-page), use locators and assertions.--## Install--```bash-npm i -D @playwright/electron-```--## Usage--```js-import { electron } from '@playwright/electron';--const electronApp = await electron.launch({ args: ['main.js'] });-const window = await electronApp.firstWindow();-// ... drive `window` like any Playwright Page ...-await electronApp.close();-```--Read more at https://playwright.dev/docs/api/class-electron.--## Migrating from v1.59--Prior to v1.60, the Electron API shipped as `playwright._electron` from the-`playwright` package. It is now exposed as `electron` from this dedicated-package.--A number of `electron.launch(...)` options have changed in the process. The sections below describe how to achieve-the same behavior with public Playwright APIs, or with built-in Electron APIs.--### Use Playwright APIs after launch--#### `recordHar`--Use [`browserContext.tracing.startHar`](https://playwright.dev/docs/api/class-tracing#tracing-start-har) /-[`stopHar`](https://playwright.dev/docs/api/class-tracing#tracing-stop-har).--```js-const electronApp = await electron.launch({ args: ['main.js'] });-await electronApp.context().tracing.startHar('network.har');-// ... drive the app ...-await electronApp.context().tracing.stopHar();-await electronApp.close();-```--#### `recordVideo`--Use [`page.screencast.start`](https://playwright.dev/docs/api/class-page#page-screencast) /-[`stop`](https://playwright.dev/docs/api/class-page#page-screencast) on each window.--```js-const electronApp = await electron.launch({ args: ['main.js'] });-const window = await electronApp.firstWindow();-await window.screencast.start({ path: 'video.webm' });-// ... drive the window ...-await window.screencast.stop();-await electronApp.close();-```--#### `colorScheme`--Use [`page.emulateMedia`](https://playwright.dev/docs/api/class-page#page-emulate-media)-on each window.--```js-const window = await electronApp.firstWindow();-await window.emulateMedia({ colorScheme: 'dark' });-```--#### `extraHTTPHeaders`--Use [`browserContext.setExtraHTTPHeaders`](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-extra-http-headers).--```js-await electronApp.context().setExtraHTTPHeaders({ 'X-My-Header': 'value' });-```--#### `geolocation`--Use [`browserContext.setGeolocation`](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-geolocation).--```js-await electronApp.context().setGeolocation({ latitude: 48.858455, longitude: 2.294474 });-```--#### `httpCredentials`--Use [`browserContext.setHTTPCredentials`](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-http-credentials).--```js-await electronApp.context().setHTTPCredentials({ username: 'user', password: 'pass' });-```--#### `offline`--Use [`browserContext.setOffline`](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-offline).--```js-await electronApp.context().setOffline(true);-```--### Use built-in Electron APIs--#### `bypassCSP`--Disable CSP at the `BrowserWindow` level via Electron's-[web preferences](https://www.electronjs.org/docs/latest/api/structures/web-preferences).-Note that `webSecurity: false` also disables CORS and the Same-Origin Policy.--```js-const win = new BrowserWindow({- webPreferences: {- webSecurity: false,- },-});-```--#### `ignoreHTTPSErrors`--There are several ways to relax HTTPS checks in Electron. Pick the one that-matches the scope you need.--Per-window, allow mixed content through [web preferences](https://www.electronjs.org/docs/latest/api/structures/web-preferences):--```js-const win = new BrowserWindow({- webPreferences: {- allowRunningInsecureContent: true,- },-});-```--Process-wide, ignore certificate errors via Chromium command-line switches-(must run before the `ready` event):--```js-const { app } = require('electron');-app.commandLine.appendSwitch('ignore-certificate-errors');-// Optional: also ignore localhost certificate errors when testing on an IP.-app.commandLine.appendSwitch('allow-insecure-localhost', 'true');-```--Per-request, accept the certificate manually via the-[`certificate-error`](https://www.electronjs.org/docs/latest/api/app#event-certificate-error)-event:--```js-app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {- event.preventDefault();- callback(true);-});-```--#### `timezoneId`--Set an environment variable at the very top of the main file, before any other logic or Chromium windows are initialized:--```js-// main.js-process.env.TZ = 'Europe/London';--const { app } = require('electron');-// ... rest of your app logic-```diff --git a/packages/playwright-electron/class-electronfixtures.md b/packages/playwright-electron/class-electronfixtures.mddeleted file mode 100644index c5a1eea6bb..0000000000--- a/packages/playwright-electron/class-electronfixtures.md+++ /dev/null@@ -1,202 +0,0 @@-# class: ElectronFixtures-* since: v1.60-* langs: js--The `@playwright/electron` package exposes a `test` object with a set of fixtures tailored for Electron automation. Fixtures are used to establish the environment for each test, giving the test everything it needs and nothing else.--Below is an example config and a test file.--```js title="playwright.config.ts"-import { defineConfig } from '@playwright/electron';--export default defineConfig({- use: {- appOptions: {- args: ['main.js'],- env: { NODE_ENV: 'test' },- },- },-});-```--```js title="example.spec.ts"-import { test, expect } from '@playwright/electron';--test('basic test', async ({ app, page }) => {- // Evaluate in the main Electron process.- const appPath = await app.evaluate(async ({ app }) => app.getAppPath());- console.log(appPath);-- // Interact with the first window via the `page` fixture.- await expect(page).toHaveTitle(/My App/);- await page.click('text=Click me');- await expect(page.getByRole('heading')).toHaveText('Hello');-});-```--Given the test above, Playwright Test will launch the Electron application, wait for its first window, and expose it as the `page` fixture. Underneath, the [`property: ElectronFixtures.app`] fixture launches the application via [`method: Electron.launch`] using [`property: ElectronFixtures.appOptions`]. The application is closed after the test finishes.--## property: ElectronFixtures.app-* since: v1.60-- type: <[ElectronApplication]>--[ElectronApplication] instance, created for each test by launching Electron with [`property: ElectronFixtures.appOptions`]. The application is closed after the test finishes.--**Usage**--```js-import { test, expect } from '@playwright/electron';--test.use({ appOptions: { args: ['main.js'] } });--test('scripts the main process', async ({ app }) => {- const appPath = await app.evaluate(({ app }) => app.getAppPath());- expect(appPath).toBeTruthy();-});-```--## property: ElectronFixtures.appOptions-* since: v1.60-- type: <[Object]>--Options passed to [`method: Electron.launch`] when creating the [`property: ElectronFixtures.app`]. Override via `use` in the config file or `test.use()` to point at your Electron entry point and configure the launch.--**Usage**--```js title="playwright.config.ts"-import { defineConfig } from '@playwright/electron';--export default defineConfig({- use: {- appOptions: {- args: ['main.js'],- env: { NODE_ENV: 'test' },- },- },-});-```--## property: ElectronFixtures.context-* since: v1.60-- type: <[BrowserContext]>--[BrowserContext] of the launched Electron app. All windows of the Electron application belong to this context.--**Usage**--```js-import { test, expect } from '@playwright/electron';--test('routes network', async ({ context, page }) => {- await context.route('**/api/**', route => route.fulfill({ status: 200, body: '{}' }));- await page.goto('https://example.com/api/data');-});-```--## property: ElectronFixtures.page-* since: v1.60-- type: <[Page]>--First window of the launched Electron app, as returned by [`method: ElectronApplication.firstWindow`]. This is the most common fixture used in an Electron test.--**Usage**--```js-import { test, expect } from '@playwright/electron';--test('interacts with the first window', async ({ page }) => {- await page.setContent('<h1>Hello</h1>');- await expect(page.locator('h1')).toHaveText('Hello');-});-```--## property: ElectronFixtures.playwright-* since: v1.60-- type: <[Object]>--The Playwright module re-exported as a worker-scoped fixture. Use it when you need programmatic access to the Playwright API without importing it directly.--**Usage**--```js-import { test, expect } from '@playwright/electron';--test('uses playwright module', async ({ playwright }) => {- const request = await playwright.request.newContext();- // ...-});-```--## property: ElectronFixtures.screenshot-* since: v1.60-- type: <[Object]|[ScreenshotMode]<"off"|"on"|"only-on-failure"|"on-first-failure">>- - `mode` <[ScreenshotMode]<"off"|"on"|"only-on-failure"|"on-first-failure">> Automatic screenshot mode.- - `fullPage` ?<[boolean]> When true, takes a screenshot of the full scrollable page, instead of the currently visible viewport. Defaults to `false`.- - `omitBackground` ?<[boolean]> Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images. Defaults to `false`.--Whether to automatically capture a screenshot after each test. Defaults to `'off'`.-* `'off'`: Do not capture screenshots.-* `'on'`: Capture screenshot after each test.-* `'only-on-failure'`: Capture screenshot after each test failure.-* `'on-first-failure'`: Capture screenshot after each test's first failure.--**Usage**--```js title="playwright.config.ts"-import { defineConfig } from '@playwright/electron';--export default defineConfig({- use: {- screenshot: 'only-on-failure',- },-});-```--## property: ElectronFixtures.testIdAttribute-* since: v1.60--Custom attribute to be used in [`method: Page.getByTestId`]. `data-testid` is used by default.--**Usage**--```js title="playwright.config.ts"-import { defineConfig } from '@playwright/electron';--export default defineConfig({- use: {- testIdAttribute: 'pw-test-id',- },-});-```--## property: ElectronFixtures.trace-* since: v1.60-- type: <[Object]|[TraceMode]<"off"|"on"|"retain-on-failure"|"on-first-retry"|"retain-on-first-failure"|"retain-on-failure-and-retries">>- - `mode` <[TraceMode]<"off"|"on"|"retain-on-failure"|"on-first-retry"|"on-all-retries"|"retain-on-first-failure"|"retain-on-failure-and-retries">> Trace recording mode.- - `attachments` ?<[boolean]> Whether to include test attachments. Defaults to true. Optional.- - `screenshots` ?<[boolean]> Whether to capture screenshots during tracing. Screenshots are used to build a timeline preview. Defaults to true. Optional.- - `snapshots` ?<[boolean]> Whether to capture DOM snapshot on every action. Defaults to true. Optional.- - `sources` ?<[boolean]> Whether to include source files for trace actions. Defaults to true. Optional.--Whether to record trace for each test. Defaults to `'off'`.-* `'off'`: Do not record trace.-* `'on'`: Record trace for each test.-* `'on-first-retry'`: Record trace only when retrying a test for the first time.-* `'on-all-retries'`: Record trace only when retrying a test.-* `'retain-on-failure'`: Record trace for each test. When test run passes, remove the recorded trace.-* `'retain-on-first-failure'`: Record trace for the first run of each test, but not for retries. When test run passes, remove the recorded trace.-* `'retain-on-failure-and-retries'`: Record trace for each test run. Retains all traces when an attempt fails.--For more control, pass an object that specifies `mode` and trace features to enable.--**Usage**--```js title="playwright.config.ts"-import { defineConfig } from '@playwright/electron';--export default defineConfig({- use: {- trace: 'on-first-retry'- },-});-```diff --git a/packages/playwright-electron/index.d.ts b/packages/playwright-electron/index.d.tsdeleted file mode 100644index d2b7923866..0000000000--- a/packages/playwright-electron/index.d.ts+++ /dev/null@@ -1,65 +0,0 @@-/**- * Copyright (c) Microsoft Corporation.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import type {- PlaywrightTestArgs as BasePlaywrightTestArgs,- PlaywrightTestOptions as BasePlaywrightTestOptions,- PlaywrightWorkerArgs as BasePlaywrightWorkerArgs,- PlaywrightWorkerOptions as BasePlaywrightWorkerOptions,- PlaywrightTestConfig as BasePlaywrightTestConfig,- TestType as BaseTestType,- BrowserContext,- Page,- Project,- Config,-} from 'playwright/test';-import type { Electron, ElectronApplication } from './types';--export * from './types';-export { expect, devices, mergeExpects, mergeTests } from 'playwright/test';-export { _electron as electron } from 'playwright-core';--export type ElectronAppOptions = Parameters<Electron['launch']>[0];-export type PlaywrightTestOptions = Pick<BasePlaywrightTestOptions, 'testIdAttribute'> & {- appOptions: ElectronAppOptions;-};-export type PlaywrightTestArgs = Pick<BasePlaywrightTestArgs, 'request'> & {- app: ElectronApplication;- context: BrowserContext;- page: Page;-};-export type PlaywrightWorkerArgs = Pick<BasePlaywrightWorkerArgs, 'playwright'>;-export type PlaywrightWorkerOptions = Pick<BasePlaywrightWorkerOptions, 'screenshot' | 'trace'>;--export type TestType<T, W> = BaseTestType<- PlaywrightTestOptions & PlaywrightTestArgs & T,- PlaywrightWorkerArgs & PlaywrightWorkerOptions & W->;-export const test: TestType<{}, {}>;--type ExcludeProps<A, B> = {- [K in Exclude<keyof A, keyof B>]: A[K];-};-type CustomProperties<T> = ExcludeProps<T, PlaywrightTestOptions & PlaywrightWorkerOptions & PlaywrightTestArgs & PlaywrightWorkerArgs>;-export type PlaywrightTestProject<TestArgs = {}, WorkerArgs = {}> = Project<PlaywrightTestOptions & CustomProperties<TestArgs>, PlaywrightWorkerOptions & CustomProperties<WorkerArgs>>;-export type PlaywrightTestConfig<TestArgs = {}, WorkerArgs = {}> = Config<PlaywrightTestOptions & CustomProperties<TestArgs>, PlaywrightWorkerOptions & CustomProperties<WorkerArgs>>;--export function defineConfig(config: PlaywrightTestConfig): PlaywrightTestConfig;-export function defineConfig<T>(config: PlaywrightTestConfig<T>): PlaywrightTestConfig<T>;-export function defineConfig<T, W>(config: PlaywrightTestConfig<T, W>): PlaywrightTestConfig<T, W>;-export function defineConfig(config: PlaywrightTestConfig, ...configs: PlaywrightTestConfig[]): PlaywrightTestConfig;-export function defineConfig<T>(config: PlaywrightTestConfig<T>, ...configs: PlaywrightTestConfig<T>[]): PlaywrightTestConfig<T>;-export function defineConfig<T, W>(config: PlaywrightTestConfig<T, W>, ...configs: PlaywrightTestConfig<T, W>[]): PlaywrightTestConfig<T, W>;diff --git a/packages/playwright-electron/index.js b/packages/playwright-electron/index.jsdeleted file mode 100644index 227eee0fde..0000000000--- a/packages/playwright-electron/index.js+++ /dev/null@@ -1,17 +0,0 @@-/**- * Copyright (c) Microsoft Corporation.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--module.exports = require('./lib/index');diff --git a/packages/playwright-electron/package.json b/packages/playwright-electron/package.jsondeleted file mode 100644index 676105e4a1..0000000000--- a/packages/playwright-electron/package.json+++ /dev/null@@ -1,27 +0,0 @@-{- "name": "@playwright/electron",- "version": "0.0.0",- "private": true,- "description": "Playwright for Electron",- "repository": {- "type": "git",- "url": "git+https://github.com/microsoft/playwright.git"- },- "homepage": "https://playwright.dev",- "engines": {- "node": ">=18"- },- "author": {- "name": "Microsoft Corporation"- },- "license": "Apache-2.0",- "exports": {- ".": {- "types": "./index.d.ts",- "default": "./index.js"- }- },- "dependencies": {- "playwright": "*"- }-}diff --git a/packages/playwright-electron/src/DEPS.list b/packages/playwright-electron/src/DEPS.listdeleted file mode 100644index e5344b5cbb..0000000000--- a/packages/playwright-electron/src/DEPS.list+++ /dev/null@@ -1,2 +0,0 @@-[*]-node_modules/playwrightdiff --git a/packages/playwright-electron/src/index.ts b/packages/playwright-electron/src/index.tsdeleted file mode 100644index d8c9f5b881..0000000000--- a/packages/playwright-electron/src/index.ts+++ /dev/null@@ -1,46 +0,0 @@-/**- * Copyright (c) Microsoft Corporation.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--// @ts-expect-error-import { _utilityTest, _electron as electron } from 'playwright/test';-import { selectors } from 'playwright/test';--export { expect, devices, defineConfig, mergeExpects, mergeTests } from 'playwright/test';-export { electron, selectors };--import type { TestType } from '../index.d.ts';--const baseTest = _utilityTest as TestType<{}, {}>;--export const test = baseTest.extend({- // @ts-expect-error- appOptions: [{}, { option: true }],-- app: async ({ appOptions, testIdAttribute }, use) => {- selectors.setTestIdAttribute(testIdAttribute);- const app = await electron.launch(appOptions);- await use(app);- await app.close();- },-- page: async ({ app }, use) => {- await use(await app.firstWindow());- },-- context: async ({ app }, use) => {- await use(app.context());- },-});diff --git a/packages/playwright-electron/types.d.ts b/packages/playwright-electron/types.d.tsdeleted file mode 100644index e2add353db..0000000000--- a/packages/playwright-electron/types.d.ts+++ /dev/null@@ -1,17 +0,0 @@-/**- * Copyright (c) Microsoft Corporation.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--export * from 'playwright-core';diff --git a/packages/protocol/spec/electron.yml b/packages/protocol/spec/electron.ymlnew file mode 100644index 0000000000..72f3a818c5--- /dev/null+++ b/packages/protocol/spec/electron.yml@@ -0,0 +1,140 @@+# Copyright (c) Microsoft Corporation.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+Electron:+ type: interface++ commands:++ launch:+ title: Launch electron+ parameters:+ executablePath: string?+ args:+ type: array?+ items: string+ chromiumSandbox: boolean?+ cwd: string?+ env:+ type: array?+ items: NameValue+ timeout: float+ acceptDownloads:+ type: enum?+ literals:+ - accept+ - deny+ - internal-browser-default+ bypassCSP: boolean?+ colorScheme:+ type: enum?+ literals:+ - dark+ - light+ - no-preference+ - no-override+ extraHTTPHeaders:+ type: array?+ items: NameValue+ geolocation:+ type: object?+ properties:+ longitude: float+ latitude: float+ accuracy: float?+ httpCredentials:+ type: object?+ properties:+ username: string+ password: string+ origin: string?+ ignoreHTTPSErrors: boolean?+ locale: string?+ offline: boolean?+ recordVideo:+ type: object?+ properties:+ dir: string?+ size:+ type: object?+ properties:+ width: int+ height: int+ showActions:+ type: object?+ properties:+ $mixin: ShowActionsOptions+ strictSelectors: boolean?+ timezoneId: string?+ tracesDir: string?+ artifactsDir: string?+ selectorEngines:+ type: array?+ items: SelectorEngine+ testIdAttributeName: string?++ returns:+ electronApplication: ElectronApplication+++ElectronApplication:+ type: interface++ extends: EventTarget++ initializer:+ context: BrowserContext++ commands:++ browserWindow:+ internal: true+ parameters:+ page: Page+ returns:+ handle: JSHandle++ evaluateExpression:+ title: Evaluate+ parameters:+ expression: string+ isFunction: boolean?+ arg: SerializedArgument+ returns:+ value: SerializedValue++ evaluateExpressionHandle:+ title: Evaluate+ parameters:+ expression: string+ isFunction: boolean?+ arg: SerializedArgument+ returns:+ handle: JSHandle++ updateSubscription:+ internal: true+ parameters:+ event:+ type: enum+ literals:+ - console+ enabled: boolean++ events:+ close:+ console:+ parameters:+ $mixin: ConsoleMessage++diff --git a/packages/protocol/spec/playwright.yml b/packages/protocol/spec/playwright.ymlindex e585848d37..bec45a11f5 100644--- a/packages/protocol/spec/playwright.yml+++ b/packages/protocol/spec/playwright.yml@@ -32,6 +32,7 @@ Playwright:firefox: BrowserTypewebkit: BrowserTypeandroid: Android+ electron: Electronutils: LocalUtils?# Only present when connecting remotely via BrowserType.connect() method.preLaunchedBrowser: Browser?diff --git a/packages/protocol/src/channels.d.ts b/packages/protocol/src/channels.d.tsindex b1aede0f72..645d3f441a 100644--- a/packages/protocol/src/channels.d.ts+++ b/packages/protocol/src/channels.d.ts@@ -28,6 +28,7 @@ export interface Channel {export type InitializerTraits<T> =T extends AndroidDeviceChannel ? AndroidDeviceInitializer :T extends BrowserContextChannel ? BrowserContextInitializer :+ T extends ElectronApplicationChannel ? ElectronApplicationInitializer :T extends ElementHandleChannel ? ElementHandleInitializer :T extends WebSocketChannel ? WebSocketInitializer :T extends PageChannel ? PageInitializer :@@ -43,6 +44,7 @@ export type InitializerTraits<T> =T extends BrowserTypeChannel ? BrowserTypeInitializer :T extends DisposableChannel ? DisposableInitializer :T extends EventTargetChannel ? EventTargetInitializer :+ T extends ElectronChannel ? ElectronInitializer :T extends FrameChannel ? FrameInitializer :T extends JSHandleChannel ? JSHandleInitializer :T extends LocalUtilsChannel ? LocalUtilsInitializer :@@ -65,6 +67,7 @@ export type InitializerTraits<T> =export type EventsTraits<T> =T extends AndroidDeviceChannel ? AndroidDeviceEvents :T extends BrowserContextChannel ? BrowserContextEvents :+ T extends ElectronApplicationChannel ? ElectronApplicationEvents :T extends ElementHandleChannel ? ElementHandleEvents :T extends WebSocketChannel ? WebSocketEvents :T extends PageChannel ? PageEvents :@@ -80,6 +83,7 @@ export type EventsTraits<T> =T extends BrowserTypeChannel ? BrowserTypeEvents :T extends DisposableChannel ? DisposableEvents :T extends EventTargetChannel ? EventTargetEvents :+ T extends ElectronChannel ? ElectronEvents :T extends FrameChannel ? FrameEvents :T extends JSHandleChannel ? JSHandleEvents :T extends LocalUtilsChannel ? LocalUtilsEvents :@@ -102,6 +106,7 @@ export type EventsTraits<T> =export type EventTargetTraits<T> =T extends AndroidDeviceChannel ? AndroidDeviceEventTarget :T extends BrowserContextChannel ? BrowserContextEventTarget :+ T extends ElectronApplicationChannel ? ElectronApplicationEventTarget :T extends ElementHandleChannel ? ElementHandleEventTarget :T extends WebSocketChannel ? WebSocketEventTarget :T extends PageChannel ? PageEventTarget :@@ -117,6 +122,7 @@ export type EventTargetTraits<T> =T extends BrowserTypeChannel ? BrowserTypeEventTarget :T extends DisposableChannel ? DisposableEventTarget :T extends EventTargetChannel ? EventTargetEventTarget :+ T extends ElectronChannel ? ElectronEventTarget :T extends FrameChannel ? FrameEventTarget :T extends JSHandleChannel ? JSHandleEventTarget :T extends LocalUtilsChannel ? LocalUtilsEventTarget :@@ -2084,6 +2090,178 @@ export type EventTargetWaitForEventInfoResult = void;export interface EventTargetEvents {}+// ----------- Electron -----------+export type ElectronInitializer = {};+export interface ElectronEventTarget {+}+export interface ElectronChannel extends ElectronEventTarget, Channel {+ _type_Electron: boolean;+ launch(params: ElectronLaunchParams, progress?: Progress): Promise<ElectronLaunchResult>;+}+export type ElectronLaunchParams = {+ executablePath?: string,+ args?: string[],+ chromiumSandbox?: boolean,+ cwd?: string,+ env?: NameValue[],+ timeout: number,+ acceptDownloads?: 'accept' | 'deny' | 'internal-browser-default',+ bypassCSP?: boolean,+ colorScheme?: 'dark' | 'light' | 'no-preference' | 'no-override',+ extraHTTPHeaders?: NameValue[],+ geolocation?: {+ longitude: number,+ latitude: number,+ accuracy?: number,+ },+ httpCredentials?: {+ username: string,+ password: string,+ origin?: string,+ },+ ignoreHTTPSErrors?: boolean,+ locale?: string,+ offline?: boolean,+ recordVideo?: {+ dir?: string,+ size?: {+ width: number,+ height: number,+ },+ showActions?: {+ duration?: number,+ position?: 'top-left' | 'top' | 'top-right' | 'bottom-left' | 'bottom' | 'bottom-right',+ fontSize?: number,+ },+ },+ strictSelectors?: boolean,+ timezoneId?: string,+ tracesDir?: string,+ artifactsDir?: string,+ selectorEngines?: SelectorEngine[],+ testIdAttributeName?: string,+};+export type ElectronLaunchOptions = {+ executablePath?: string,+ args?: string[],+ chromiumSandbox?: boolean,+ cwd?: string,+ env?: NameValue[],+ acceptDownloads?: 'accept' | 'deny' | 'internal-browser-default',+ bypassCSP?: boolean,+ colorScheme?: 'dark' | 'light' | 'no-preference' | 'no-override',+ extraHTTPHeaders?: NameValue[],+ geolocation?: {+ longitude: number,+ latitude: number,+ accuracy?: number,+ },+ httpCredentials?: {+ username: string,+ password: string,+ origin?: string,+ },+ ignoreHTTPSErrors?: boolean,+ locale?: string,+ offline?: boolean,+ recordVideo?: {+ dir?: string,+ size?: {+ width: number,+ height: number,+ },+ showActions?: {+ duration?: number,+ position?: 'top-left' | 'top' | 'top-right' | 'bottom-left' | 'bottom' | 'bottom-right',+ fontSize?: number,+ },+ },+ strictSelectors?: boolean,+ timezoneId?: string,+ tracesDir?: string,+ artifactsDir?: string,+ selectorEngines?: SelectorEngine[],+ testIdAttributeName?: string,+};+export type ElectronLaunchResult = {+ electronApplication: ElectronApplicationChannel,+};++export interface ElectronEvents {+}++// ----------- ElectronApplication -----------+export type ElectronApplicationInitializer = {+ context: BrowserContextChannel,+};+export interface ElectronApplicationEventTarget {+ on(event: 'close', callback: (params: ElectronApplicationCloseEvent) => void): this;+ on(event: 'console', callback: (params: ElectronApplicationConsoleEvent) => void): this;+}+export interface ElectronApplicationChannel extends ElectronApplicationEventTarget, EventTargetChannel {+ _type_ElectronApplication: boolean;+ browserWindow(params: ElectronApplicationBrowserWindowParams, progress?: Progress): Promise<ElectronApplicationBrowserWindowResult>;+ evaluateExpression(params: ElectronApplicationEvaluateExpressionParams, progress?: Progress): Promise<ElectronApplicationEvaluateExpressionResult>;+ evaluateExpressionHandle(params: ElectronApplicationEvaluateExpressionHandleParams, progress?: Progress): Promise<ElectronApplicationEvaluateExpressionHandleResult>;+ updateSubscription(params: ElectronApplicationUpdateSubscriptionParams, progress?: Progress): Promise<ElectronApplicationUpdateSubscriptionResult>;+}+export type ElectronApplicationCloseEvent = {};+export type ElectronApplicationConsoleEvent = {+ type: string,+ text: string,+ args: JSHandleChannel[],+ location: {+ url: string,+ lineNumber: number,+ columnNumber: number,+ },+ timestamp: number,+};+export type ElectronApplicationBrowserWindowParams = {+ page: PageChannel,+};+export type ElectronApplicationBrowserWindowOptions = {++};+export type ElectronApplicationBrowserWindowResult = {+ handle: JSHandleChannel,+};+export type ElectronApplicationEvaluateExpressionParams = {+ expression: string,+ isFunction?: boolean,+ arg: SerializedArgument,+};+export type ElectronApplicationEvaluateExpressionOptions = {+ isFunction?: boolean,+};+export type ElectronApplicationEvaluateExpressionResult = {+ value: SerializedValue,+};+export type ElectronApplicationEvaluateExpressionHandleParams = {+ expression: string,+ isFunction?: boolean,+ arg: SerializedArgument,+};+export type ElectronApplicationEvaluateExpressionHandleOptions = {+ isFunction?: boolean,+};+export type ElectronApplicationEvaluateExpressionHandleResult = {+ handle: JSHandleChannel,+};+export type ElectronApplicationUpdateSubscriptionParams = {+ event: 'console',+ enabled: boolean,+};+export type ElectronApplicationUpdateSubscriptionOptions = {++};+export type ElectronApplicationUpdateSubscriptionResult = void;++export interface ElectronApplicationEvents {+ 'close': ElectronApplicationCloseEvent;+ 'console': ElectronApplicationConsoleEvent;+}+// ----------- Frame -----------export type FrameInitializer = {url: string,@@ -4522,6 +4700,7 @@ export type PlaywrightInitializer = {firefox: BrowserTypeChannel,webkit: BrowserTypeChannel,android: AndroidChannel,+ electron: ElectronChannel,utils?: LocalUtilsChannel,preLaunchedBrowser?: BrowserChannel,preConnectedAndroidDevice?: AndroidDeviceChannel,diff --git a/tests/electron/electron-app.spec.ts b/tests/electron/electron-app.spec.tsindex 77dc7e0b9a..adbca5e7fe 100644--- a/tests/electron/electron-app.spec.ts+++ b/tests/electron/electron-app.spec.ts@@ -376,7 +376,7 @@ test('should report downloads', async ({ launchElectronApp, electronMajorVersionres.end(`Hello world`);});- const app = await launchElectronApp('electron-window-app.js');+ const app = await launchElectronApp('electron-window-app.js', [], { acceptDownloads: true });const window = await app.firstWindow();await window.setContent(`<a href="${server.PREFIX}/download">download</a>`);const [download] = await Promise.all([diff --git a/tests/electron/electron-screenshot.spec.ts b/tests/electron/electron-screenshot.spec.tsdeleted file mode 100644index 3c7c055aa7..0000000000--- a/tests/electron/electron-screenshot.spec.ts+++ /dev/null@@ -1,32 +0,0 @@-/**- * Copyright (c) Microsoft Corporation.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import fs from 'fs';-import { electronTest as test, expect } from './electronTest';--test.use({ screenshot: 'on' });--test.afterEach(async ({}, testInfo) => {- const screenshots = testInfo.attachments.filter(a => a.name === 'screenshot');- expect(screenshots).toHaveLength(1);- expect(fs.existsSync(screenshots[0].path!)).toBe(true);-});--test('should capture screenshot', async ({ launchElectronApp, newWindow }) => {- const app = await launchElectronApp('electron-app.js');- const page = await newWindow(app);- await page.setContent('<h1>Electron</h1>');-});diff --git a/tests/electron/electron-tracing.spec.ts b/tests/electron/electron-tracing.spec.tsindex c62d342eac..ad3d87bf9d 100644--- a/tests/electron/electron-tracing.spec.ts+++ b/tests/electron/electron-tracing.spec.ts@@ -15,6 +15,8 @@*/import { electronTest as test, expect } from './electronTest';+import fs from 'fs';+import path from 'path';test.skip(({ trace }) => trace === 'on');@@ -50,3 +52,17 @@ test('should support custom protocol', async ({ launchElectronApp, newWindow, shawait expect(frame.locator('button')).toHaveCSS('color', 'rgb(255, 0, 0)');await expect(frame.locator('button')).toHaveCSS('font-weight', '700');});++test('should respect tracesDir and name', async ({ launchElectronApp, server }, testInfo) => {+ const tracesDir = testInfo.outputPath('traces');+ const electronApp = await launchElectronApp('electron-window-app.js', [], { tracesDir });++ await electronApp.context().tracing.start({ name: 'name1', snapshots: true });+ const page = await electronApp.firstWindow();+ await page.goto(server.PREFIX + '/one-style.html');+ await electronApp.context().tracing.stopChunk({ path: testInfo.outputPath('trace1.zip') });+ expect(fs.existsSync(path.join(tracesDir, 'name1.trace'))).toBe(true);+ expect(fs.existsSync(path.join(tracesDir, 'name1.network'))).toBe(true);++ await electronApp.close();+});diff --git a/tests/electron/electronTest.ts b/tests/electron/electronTest.tsindex 7e0467c94a..d4793dec5f 100644--- a/tests/electron/electronTest.ts+++ b/tests/electron/electronTest.ts@@ -18,15 +18,15 @@ import { baseTest } from '../config/baseTest';import path from 'path';import fs from 'fs';import os from 'os';-import type { ElectronApplication, Electron, Page } from '@playwright/electron';-import { electron } from '@playwright/electron';+import type { ElectronApplication, Electron, Page } from 'playwright';+import { _electron as electron } from 'playwright';import type { PageTestFixtures, PageWorkerFixtures } from '../page/pageTestApi';import type { TraceViewerFixtures } from '../config/traceViewerFixtures';import { traceViewerFixtures } from '../config/traceViewerFixtures';import { utils } from '../../packages/playwright-core/lib/coreBundle';import { inheritAndCleanEnv } from '../config/utils';-export { expect, selectors } from '@playwright/electron';+export { expect, selectors } from '@playwright/test';const { removeFolders } = utils;diff --git a/tests/installation/globalSetup.ts b/tests/installation/globalSetup.tsindex 3035afd00f..9e295ee328 100644--- a/tests/installation/globalSetup.ts+++ b/tests/installation/globalSetup.ts@@ -57,7 +57,6 @@ async function globalSetup() {build('playwright-browser-webkit', '@playwright/browser-webkit'),build('playwright-ct-react', '@playwright/experimental-ct-react'),build('playwright-ct-core', '@playwright/experimental-ct-core'),- build('playwright-electron', '@playwright/electron'),]);const buildPlaywrightTestPlugin = async () => {diff --git a/tests/library/channels.spec.ts b/tests/library/channels.spec.tsindex a1cc03076b..7bff98362d 100644--- a/tests/library/channels.spec.ts+++ b/tests/library/channels.spec.ts@@ -48,6 +48,7 @@ it('should scope context handles', async ({ browserType, server, expectScopeStat{ _guid: 'browser-type', objects: [{ _guid: 'browser', objects: [] }] },+ { _guid: 'electron', objects: [] },{ _guid: 'localUtils', objects: [] },{ _guid: 'Playwright', objects: [] },]@@ -80,6 +81,7 @@ it('should scope context handles', async ({ browserType, server, expectScopeStat] },] },] },+ { _guid: 'electron', objects: [] },{ _guid: 'localUtils', objects: [] },{ _guid: 'Playwright', objects: [] },]@@ -103,6 +105,7 @@ it('should scope CDPSession handles', async ({ browserType, browserName, expectS{ _guid: 'browser-type', objects: [{ _guid: 'browser', objects: [] }] },+ { _guid: 'electron', objects: [] },{ _guid: 'localUtils', objects: [] },{ _guid: 'Playwright', objects: [] },]@@ -121,6 +124,7 @@ it('should scope CDPSession handles', async ({ browserType, browserName, expectS{ _guid: 'cdp-session', objects: [] },] },] },+ { _guid: 'electron', objects: [] },{ _guid: 'localUtils', objects: [] },{ _guid: 'Playwright', objects: [] },]@@ -140,6 +144,7 @@ it('should scope browser handles', async ({ browserType, expectScopeState }) =>{ _guid: 'browser-type', objects: [] },{ _guid: 'browser-type', objects: [] },{ _guid: 'browser-type', objects: [] },+ { _guid: 'electron', objects: [] },{ _guid: 'localUtils', objects: [] },{ _guid: 'Playwright', objects: [] },]@@ -166,6 +171,7 @@ it('should scope browser handles', async ({ browserType, expectScopeState }) =>},]},+ { _guid: 'electron', objects: [] },{ _guid: 'localUtils', objects: [] },{ _guid: 'Playwright', objects: [] },]@@ -208,6 +214,7 @@ it('should not generate dispatchers for subresources w/o listeners', async ({ pa]}],},+ { _guid: 'electron', objects: [] },{ _guid: 'localUtils', objects: [] },{ _guid: 'Playwright', objects: [] },]@@ -316,6 +323,10 @@ it('exposeFunction should not leak', async ({ page, expectScopeState, server })},],},+ {+ '_guid': 'electron',+ 'objects': [],+ },{'_guid': 'localUtils','objects': [],diff --git a/tests/page/page-leaks.spec.ts b/tests/page/page-leaks.spec.tsindex 7b09f33e3f..d38488932f 100644--- a/tests/page/page-leaks.spec.ts+++ b/tests/page/page-leaks.spec.ts@@ -24,7 +24,7 @@ function leakedJSHandles(): string {const map = new MultiMap();for (const [h, e] of (globalThis as any).leakedJSHandles) {const name = `[${h.worldNameForTest()}] ${h.preview()}`;- if (name === '[main] UtilityScript' || name === '[utility] UtilityScript' || name === '[electron] UtilityScript' || name === '[worker] UtilityScript' || name === '[main] InjectedScript' || name === '[utility] InjectedScript' || name === '[electron] ElectronModule' || name === '[worker] ElectronModule')+ if (name === '[main] UtilityScript' || name === '[utility] UtilityScript' || name === '[electron] UtilityScript' || name === '[main] InjectedScript' || name === '[utility] InjectedScript' || name === '[electron] ElectronModule')continue;map.set(e.stack, name);}diff --git a/utils/build/build.js b/utils/build/build.jsindex 347d617638..d565e9dd3e 100644--- a/utils/build/build.js+++ b/utils/build/build.js@@ -539,7 +539,7 @@ for (const pkg of workspace.packages()) {// playwright-client is built as a bundle.if (['@playwright/client'].includes(pkg.name))continue;- if (pkg.name === 'playwright-core' || pkg.name === 'playwright' || pkg.name === '@playwright/electron')+ if (pkg.name === 'playwright-core' || pkg.name === 'playwright')continue;steps.push(new EsbuildStep({@@ -549,22 +549,6 @@ for (const pkg of workspace.packages()) {}));}-// playwright-electron/lib/index.js — thin test-runner integration shim that-// re-exports `playwright._electron`. Resolved at runtime against the parent-// `playwright` install.-{- const electronPkg = filePath('packages/playwright-electron');- steps.push(new EsbuildStep({- bundle: true,- entryPoints: [path.join(electronPkg, 'src/index.ts')],- outfile: path.join(electronPkg, 'lib/index.js'),- external: [- 'playwright',- 'playwright/*',- ],- }));-}-// Build playwright-core exported entry points.steps.push(new EsbuildStep({entryPoints: [@@ -577,10 +561,6 @@ steps.push(new EsbuildStep({filePath('packages/playwright-core/src/entry/mcp.ts'),filePath('packages/playwright-core/src/entry/oopBrowserDownload.ts'),- // Electron loader — preloaded inside the Electron main process via `-r`.- // Self-contained (no @utils/@isomorphic imports) — emitted as a thin shim.- filePath('packages/playwright-core/src/electron/loader.ts'),-// CLI client tools, should be a separate bundle.filePath('packages/playwright-core/src/tools/cli-client/*.ts'),filePath('packages/playwright-core/src/package.ts'),@@ -818,6 +798,16 @@ steps.push(new EsbuildStep({plugins: [dynamicImportToRequirePlugin],}, [filePath('packages/playwright/src')]));+// Build the Electron preload loader as a standalone CJS file. It runs inside+// the Electron process (via `electron -r loader.js`) and must not depend on+// coreBundle. `electron` is resolved at runtime by the Electron process.+steps.push(new EsbuildStep({+ bundle: true,+ entryPoints: [filePath('packages/playwright-core/src/server/electron/loader.ts')],+ outfile: filePath('packages/playwright-core/lib/server/electron/loader.js'),+ external: ['electron'],+}, [playwrightCoreSrc]));+function copyXdgOpen() {const outdir = filePath('packages/playwright-core/lib');if (!fs.existsSync(outdir))diff --git a/utils/doclint/cli.js b/utils/doclint/cli.jsindex 141ecf3eb2..b6d346817d 100755--- a/utils/doclint/cli.js+++ b/utils/doclint/cli.js@@ -272,6 +272,7 @@ async function run() {// Check for missing docs{const apiDocumentation = parseApi(path.join(PROJECT_DIR, 'docs', 'src', 'api'))+ .mergeWith(parseApi(path.join(PROJECT_DIR, 'docs', 'src', 'electron-api'), path.join(PROJECT_DIR, 'docs', 'src', 'api', 'params.md'))).mergeWith(parseApi(path.join(PROJECT_DIR, 'docs', 'src', 'mobile-api'), path.join(PROJECT_DIR, 'docs', 'src', 'api', 'params.md')));apiDocumentation.filterForLanguage('js');const srcClient = path.join(PROJECT_DIR, 'packages', 'playwright-core', 'src', 'client');diff --git a/utils/generate_types/overrides.d.ts b/utils/generate_types/overrides.d.tsindex f7f10b66a3..03ca88049c 100644--- a/utils/generate_types/overrides.d.ts+++ b/utils/generate_types/overrides.d.ts@@ -277,6 +277,17 @@ class TimeoutError extends Error {}export const devices: Devices;+//@ts-ignore this will be any if electron is not installed+type ElectronType = typeof import('electron');++export interface ElectronApplication {+ evaluate<R, Arg>(pageFunction: PageFunctionOn<ElectronType, Arg, R>, arg: Arg): Promise<R>;+ evaluate<R>(pageFunction: PageFunctionOn<ElectronType, void, R>, arg?: any): Promise<R>;++ evaluateHandle<R, Arg>(pageFunction: PageFunctionOn<ElectronType, Arg, R>, arg: Arg): Promise<SmartHandle<R>>;+ evaluateHandle<R>(pageFunction: PageFunctionOn<ElectronType, void, R>, arg?: any): Promise<SmartHandle<R>>;+}+export type AndroidElementInfo = {clazz: string;desc: string;@@ -382,17 +393,19 @@ export type AndroidKey ='Copy' |'Paste';+export const _electron: Electron;export const _android: Android;//@ts-ignore this will be any if electron is not installedtype ElectronType = typeof import('electron');export interface ElectronApplication {- evaluate: JSHandle<ElectronType>['evaluate'];- evaluateHandle: JSHandle<ElectronType>['evaluateHandle'];-}+ evaluate<R, Arg>(pageFunction: PageFunctionOn<ElectronType, Arg, R>, arg: Arg): Promise<R>;+ evaluate<R>(pageFunction: PageFunctionOn<ElectronType, void, R>, arg?: any): Promise<R>;-export const _electron: Electron;+ evaluateHandle<R, Arg>(pageFunction: PageFunctionOn<ElectronType, Arg, R>, arg: Arg): Promise<SmartHandle<R>>;+ evaluateHandle<R>(pageFunction: PageFunctionOn<ElectronType, void, R>, arg?: any): Promise<SmartHandle<R>>;+}// This is required to not export everything by default. See https://github.com/Microsoft/TypeScript/issues/19545#issuecomment-340490459export {};