Skip to main content

Electron

Playwright 对 Electron 自动化提供实验支持。你可以通过以下方式访问 Electron 命名空间:

Playwright has experimental support for Electron automation. You can access electron namespace via:

const { _electron } = require('playwright');

Electron 自动化脚本的一个示例是:

An example of the Electron automation script would be:

const { _electron: electron } = require('playwright');

(async () => {
// Launch Electron app.
const electronApp = await electron.launch({ args: ['main.js'] });

// Evaluation expression in the Electron context.
const appPath = await electronApp.evaluate(async ({ app }) => {
// This runs in the main Electron process, parameter here is always
// the result of the require('electron') in the main app script.
return app.getAppPath();
});
console.log(appPath);

// Get the first window that the app opens, wait if necessary.
const window = await electronApp.firstWindow();
// Print the title.
console.log(await window.title());
// Capture a screenshot.
await window.screenshot({ path: 'intro.png' });
// Direct Electron console to Node terminal.
window.on('console', console.log);
// Click button.
await window.click('text=Click me');
// Exit app.
await electronApp.close();
})();

请注意,由于测试 Electron 时不需要 Playwright 安装 Web 浏览器,因此你可以在安装 Playwright 时通过设置以下环境变量来省略浏览器下载:

Note that since you don't need Playwright to install web browsers when testing Electron, you can omit browser download via setting the following environment variable when installing Playwright:

PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm i -D playwright

支持的 Electron 版本有:

Supported Electron versions are:

  • v12.2.0+

  • v13.4.0+

  • v14+

已知的问题:

Known issues:

如果你无法启动 Electron 并且它会在启动过程中超时,请尝试以下操作:

If you are not able to launch Electron and it will end up in timeouts during launch, try the following:


方法

Methods

launch

Added in: v1.9 electron.launch

启动 executablePath 指定的 electron 应用。

Launches electron application specified with the executablePath.

用法

Usage

await electron.launch();
await electron.launch(options);

参数

Arguments

  • options Object (optional)

    • acceptDownloads boolean (optional) Added in: v1.12#

是否自动下载所有附件。默认为 true,接受所有下载。

Whether to automatically download all the attachments. Defaults to true where all the downloads are accepted.

启动时传递给应用的其他参数。你通常在此处传递主脚本名称。

Additional arguments to pass to the application when launching. You typically pass the main script name here.

  • bypassCSP boolean (optional) Added in: v1.12#

切换绕过页面的内容安全策略。默认为 false

Toggles bypassing page's Content-Security-Policy. Defaults to false.

  • colorScheme null|"light"|"dark"|"no-preference" (optional) Added in: v1.12#

模拟 'prefers-colors-scheme' 媒体功能,支持的值为 'light''dark''no-preference'。详细信息请参见 page.emulateMedia()。传递 null 会将模拟重置为系统默认值。默认为 'light'

Emulates 'prefers-colors-scheme' media feature, supported values are 'light', 'dark', 'no-preference'. See page.emulateMedia() for more details. Passing null resets emulation to system defaults. Defaults to 'light'.

当前启动应用的工作目录。

Current working directory to launch application from.

指定 Electron 可见的环境变量。默认为 process.env

Specifies environment variables that will be visible to Electron. Defaults to process.env.

  • executablePath string (optional)#

启动给定的 Electron 应用。如果未指定,则启动此包中安装的默认 Electron 可执行文件,位于 node_modules/.bin/electron

Launches given Electron application. If not specified, launches the default Electron executable installed in this package, located at node_modules/.bin/electron.

包含随每个请求发送的附加 HTTP 标头的对象。默认为无。

An object containing additional HTTP headers to be sent with every request. Defaults to none.

纬度在 -90 到 90 之间。

Latitude between -90 and 90.

经度在 -180 到 180 之间。

Longitude between -180 and 180.

非负精度值。默认为 0

Non-negative accuracy value. Defaults to 0.

限制在特定来源 (scheme://host:port) 上发送 http 凭据。

Restrain sending http credentials on specific origin (scheme://host:port).

HTTP 认证 的凭证。如果未指定来源,则用户名和密码将在未经授权的响应时发送到任何服务器。

Credentials for HTTP authentication. If no origin is specified, the username and password are sent to any servers upon unauthorized responses.

  • ignoreHTTPSErrors boolean (optional) Added in: v1.12#

发送网络请求时是否忽略 HTTPS 错误。默认为 false

Whether to ignore HTTPS errors when sending network requests. Defaults to false.

  • locale string (optional) Added in: v1.12#

指定用户区域设置,例如 en-GBde-DE 等。区域设置会影响 navigator.language 值、Accept-Language 请求标头值以及数字和日期格式规则。默认为系统默认区域设置。在我们的 模拟指南 中了解有关模拟的更多信息。

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.

  • offline boolean (optional) Added in: v1.12#

是否模拟网络离线。默认为 false。了解有关 网络模拟 的更多信息。

Whether to emulate network being offline. Defaults to false. Learn more about network emulation.

  • recordHar Object (optional) Added in: v1.12#

用于控制是否省略 HAR 中的请求内容的可选设置。默认为 false。已弃用,请改用 content 策略。

Optional setting to control whether to omit request content from the HAR. Defaults to false. Deprecated, use content policy instead.

  • content "omit"|"embed"|"attach"(可选)

    content "omit"|"embed"|"attach" (optional)

    用于控制资源内容管理的可选设置。如果指定了 omit,则不会保留内容。如果指定了 attach,资源将作为单独的文件或条目保留在 ZIP 存档中。如果指定了 embed,则根据 HAR 规范将内容内联存储在 HAR 文件中。对于 .zip 输出文件,默认为 attach;对于所有其他文件扩展名,默认为 embed

    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.

将 HAR 文件写入到的文件系统上的路径。如果文件名以 .zip 结尾,则默认使用 content: 'attach'

Path on the filesystem to write the HAR file to. If the file name ends with .zip, content: 'attach' is used by default.

  • mode "full"|"minimal"(可选)

    mode "full"|"minimal" (optional)

    当设置为 minimal 时,仅记录从 HAR 路由所需的信息。这会忽略从 HAR 重放时不使用的大小、计时、页面、cookie、安全性和其他类型的 HAR 信息。默认为 full

    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.

用于过滤存储在 HAR 中的请求的 glob 或正则表达式模式。当通过上下文选项提供 baseURL 并且传递的 URL 是路径时,它将通过 new URL() 构造函数合并。默认为无。

A glob or regex pattern to filter requests that are stored in the HAR. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor. Defaults to none.

启用所有页面的 HAR 记录到 recordHar.path 文件中。如果未指定,则不会记录 HAR。确保等待 browserContext.close() 才能保存 HAR。

Enables HAR recording for all pages into recordHar.path file. If not specified, the HAR is not recorded. Make sure to await browserContext.close() for the HAR to be saved.

放置视频的目录路径。

Path to the directory to put videos into.

视频帧宽度。

Video frame width.

视频帧高度。

Video frame height.

录制视频的可选尺寸。如果未指定,大小将等于 viewport 缩小以适合 800x800。如果未明确配置 viewport,则视频大小默认为 800x450。如有必要,每页的实际图片将按比例缩小以适合指定的尺寸。

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.

启用 recordVideo.dir 目录中所有页面的视频录制。如果未指定,则不会录制视频。请务必等待 browserContext.close() 才能保存视频。

Enables video recording for all pages into recordVideo.dir directory. If not specified videos are not recorded. Make sure to await browserContext.close() for videos to be saved.

  • timeout number (optional) Added in: v1.15#

等待应用启动的最长时间(以毫秒为单位)。默认为 30000(30 秒)。通过 0 禁用超时。

Maximum time in milliseconds to wait for the application to start. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

  • timezoneId string (optional) Added in: v1.12#

更改上下文的时区。有关支持的时区 ID 的列表,请参阅 ICU 的 metaZones.txt。默认为系统时区。

Changes the timezone of the context. See ICU's metaZones.txt for a list of supported timezone IDs. Defaults to the system timezone.

  • tracesDir string (optional) Added in: v1.36#

如果指定,跟踪将保存到此目录中。

If specified, traces are saved into this directory.

返回

Returns