Skip to main content

浏览器

通过 browserType.launch() 创建浏览器。使用 浏览器 创建 页面 的示例:

A Browser is created via browserType.launch(). An example of using a Browser to create a Page:

const { firefox } = require('playwright');  // Or 'chromium' or 'webkit'.

(async () => {
const browser = await firefox.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await browser.close();
})();

方法

Methods

browserType

Added in: v1.23 browser.browserType

获取浏览器所属的浏览器类型(chromium、firefox 或 webkit)。

Get the browser type (chromium, firefox or webkit) that the browser belongs to.

用法

Usage

browser.browserType();

返回

Returns


close

Added in: v1.8 browser.close

如果使用 browserType.launch() 获取此浏览器,请关闭浏览器及其所有页面(如果有打开的页面)。

In case this browser is obtained using browserType.launch(), closes the browser and all of its pages (if any were opened).

如果连接到此浏览器,则清除属于此浏览器的所有创建的上下文并断开与浏览器服务器的连接。

In case this browser is connected to, clears all created contexts belonging to this browser and disconnects from the browser server.

注意

这类似于强制退出浏览器。因此,在调用 browser.close() 之前,你应该对先前使用 browser.newContext() 显式创建的任何 BrowserContext 调用 browserContext.close()

This is similar to force quitting the browser. Therefore, you should call browserContext.close() on any BrowserContext's you explicitly created earlier with browser.newContext() before calling browser.close().

浏览器 对象本身被认为已被释放,不能再使用。

The Browser object itself is considered to be disposed and cannot be used anymore.

用法

Usage

await browser.close();
await browser.close(options);

参数

Arguments

  • options Object (optional)

    • reason string (optional) Added in: v1.40#

报告的原因是由于浏览器关闭而中断的操作。

The reason to be reported to the operations interrupted by the browser closure.


contexts

Added in: v1.8 browser.contexts

返回所有打开的浏览器上下文的数组。在新创建的浏览器中,这将返回零浏览器上下文。

Returns an array of all open browser contexts. In a newly created browser, this will return zero browser contexts.

用法

Usage

const browser = await pw.webkit.launch();
console.log(browser.contexts().length); // prints `0`

const context = await browser.newContext();
console.log(browser.contexts().length); // prints `1`

返回

Returns


isConnected

Added in: v1.8 browser.isConnected

表示浏览器已连接。

Indicates that the browser is connected.

用法

Usage

browser.isConnected();

返回

Returns


newBrowserCDPSession

Added in: v1.11 browser.newBrowserCDPSession
注意

CDP 会话仅在基于 Chromium 的浏览器上受支持。

CDP Sessions are only supported on Chromium-based browsers.

返回新创建的浏览器会话。

Returns the newly created browser session.

用法

Usage

await browser.newBrowserCDPSession();

返回

Returns


newContext

Added in: v1.8 browser.newContext

创建一个新的浏览器上下文。它不会与其他浏览器上下文共享 cookie/缓存。

Creates a new browser context. It won't share cookies/cache with other browser contexts.

注意

如果直接使用此方法创建 BrowserContext,最佳实践是在代码完成 BrowserContext 后、调用 browser.close() 之前通过 browserContext.close() 显式关闭返回的上下文。这将确保 context 正常关闭,并且任何工件(例如 HAR 和视频)都被完全刷新并保存。

If directly using this method to create BrowserContexts, it is best practice to explicitly close the returned context via browserContext.close() when your code is done with the BrowserContext, and before calling browser.close(). This will ensure the context is closed gracefully and any artifacts—like HARs and videos—are fully flushed and saved.

用法

Usage

(async () => {
const browser = await playwright.firefox.launch(); // Or 'chromium' or 'webkit'.
// Create a new incognito browser context.
const context = await browser.newContext();
// Create a new page in a pristine context.
const page = await context.newPage();
await page.goto('https://example.com');

// Gracefully close up everything
await context.close();
await browser.close();
})();

参数

Arguments

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

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

当使用 page.goto()page.route()page.waitForURL()page.waitForRequest()page.waitForResponse() 时,它会使用 URL() 构造函数来构建相应的 URL,从而考虑基本 URL。默认情况下取消设置。示例:

When using page.goto(), page.route(), page.waitForURL(), page.waitForRequest(), or page.waitForResponse() it takes the base URL in consideration by using the URL() constructor for building the corresponding URL. Unset by default. Examples:

  • baseURL:http://localhost:3000 并导航至 /bar.html 结果为 http://localhost:3000/bar.html

    baseURL: http://localhost:3000 and navigating to /bar.html results in http://localhost:3000/bar.html

  • baseURL:http://localhost:3000/foo/ 并导航至 ./bar.html 结果为 http://localhost:3000/foo/bar.html

    baseURL: http://localhost:3000/foo/ and navigating to ./bar.html results in http://localhost:3000/foo/bar.html

  • baseURL:http://localhost:3000/foo(无尾部斜杠)并导航至 ./bar.html 将导致 http://localhost:3000/bar.html

    baseURL: http://localhost:3000/foo (without trailing slash) and navigating to ./bar.html results in http://localhost:3000/bar.html

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

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

  • colorScheme null|"light"|"dark"|"no-preference" (optional)#

模拟 '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'.

  • deviceScaleFactor number (optional)#

指定设备比例因子(可以视为 dpr)。默认为 1。了解有关 使用设备比例因子模拟设备 的更多信息。

Specify device scale factor (can be thought of as dpr). Defaults to 1. Learn more about emulating devices with device scale factor.

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

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

  • forcedColors null|"active"|"none" (optional)#

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

Emulates 'forced-colors' media feature, supported values are 'active', 'none'. See page.emulateMedia() for more details. Passing null resets emulation to system defaults. 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.

指定视口是否支持触摸事件。默认为 false。了解有关 移动模拟 的更多信息。

Specifies if viewport supports touch events. Defaults to false. Learn more about mobile emulation.

限制在特定来源 (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.

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

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

是否考虑 meta viewport 标签并启用触摸事件。isMobile 是设备的一部分,因此你实际上不需要手动设置它。默认为 false,Firefox 不支持。了解有关 移动模拟 的更多信息。

Whether the meta viewport tag is taken into account and touch events are enabled. isMobile is a part of device, so you don't actually need to set it manually. Defaults to false and is not supported in Firefox. Learn more about mobile emulation.

是否在上下文中启用 JavaScript。默认为 true。了解有关 禁用 JavaScript 的更多信息。

Whether or not to enable JavaScript in the context. Defaults to true. Learn more about disabling JavaScript.

指定用户区域设置,例如 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.

用于 Playwright 日志记录的日志器接收器。

Logger sink for Playwright logging.

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

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

授予此上下文中所有页面的权限列表。详细信息请参见 browserContext.grantPermissions()。默认为无。

A list of permissions to grant to all pages in this context. See browserContext.grantPermissions() for more details. Defaults to none.

用于所有请求的代理。支持 HTTP 和 SOCKS 代理,例如 http://myproxy.com:3128socks5://myproxy.com:3128。缩写形式 myproxy.com:3128 被视为 HTTP 代理。

Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example http://myproxy.com:3128 or socks5://myproxy.com:3128. Short form myproxy.com:3128 is considered an HTTP proxy.

用于绕过代理的可选逗号分隔域,例如 ".com, chromium.org, .domain.com"

Optional comma-separated domains to bypass proxy, for example ".com, chromium.org, .domain.com".

如果 HTTP 代理需要身份验证,则使用可选的用户名。

Optional username to use if HTTP proxy requires authentication.

如果 HTTP 代理需要身份验证,则使用可选密码。

Optional password to use if HTTP proxy requires authentication.

与此上下文一起使用的网络代理设置。默认为无。

Network proxy settings to use with this context. Defaults to none.

note

launch({ proxy: { server: 'http://per-context' } }). :::对于 Windows 上的 Chromium,需要使用全局代理启动浏览器才能使此选项发挥作用。如果所有上下文都覆盖代理,则全局代理将永远不会被使用,并且可以是任何字符串,例如

用于控制是否省略 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.

  • reducedMotion null|"reduce"|"no-preference" (optional)#

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

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

页面宽度(以像素为单位)。

page width in pixels.

页面高度(以像素为单位)。

page height in pixels.

通过 window.screen 模拟网页内可用的一致窗口屏幕尺寸。仅当设置了 viewport 时才使用。

Emulates consistent window screen size available inside web page via window.screen. Is only used when the viewport is set.

  • serviceWorkers "allow"|"block"(可选)#

    serviceWorkers "allow"|"block" (optional)#

    是否允许站点注册 Service Worker。默认为 'allow'

    Whether to allow sites to register Service workers. Defaults to 'allow'.

    • 'allow'服务工作进程 可以注册。

      'allow': Service Workers can be registered.

    • 'block':Playwright 将阻止所有服务工作进程的注册。

      'block': Playwright will block all registration of Service Workers.

需要域和路径。为了使 cookie 也适用于所有子域,请在域前添加一个点,如下所示:".example.com"

Domain and path are required. For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com"

域名和路径为必填项

Domain and path are required

Unix 时间以秒为单位。

Unix time in seconds.

  • sameSite "严格的"|"Lax"|"没有任何"

    sameSite "Strict"|"Lax"|"None"

    同一站点标志

    sameSite flag

为上下文设置的 Cookie

Cookies to set for context

localStorage 设置上下文

localStorage to set for context

了解有关 存储状态和授权 的更多信息。

Learn more about storage state and auth.

使用给定的存储状态填充上下文。该选项可用于使用通过 browserContext.storageState() 获取的登录信息来初始化上下文。

Populates context with given storage state. This option can be used to initialize context with logged-in information obtained via browserContext.storageState().

如果设置为 true,则为此上下文启用严格选择器模式。在严格选择器模式下,当多个元素与选择器匹配时,所有暗示单个目标 DOM 元素的选择器操作都会抛出异常。此选项不会影响任何定位器 API(定位器始终是严格的)。默认为 false。请参阅 定位器 了解有关严格模式的更多信息。

If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors that imply single target DOM element will throw when more than one element matches the selector. This option does not affect any Locator APIs (Locators are always strict). Defaults to false. See Locator to learn more about the strict mode.

更改上下文的时区。有关支持的时区 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.

在此上下文中使用的特定用户代理。

Specific user agent to use in this context.

Deprecated

Use recordVideo instead.

视频帧宽度。

Video frame width.

视频帧高度。

Video frame height.

Deprecated

Use recordVideo instead.

页面宽度(以像素为单位)。

page width in pixels.

页面高度(以像素为单位)。

page height in pixels.

模拟每个页面的一致视口。默认为 1280x720 视口。使用 null 禁用一致视口模拟。了解有关 视口模拟 的更多信息。

Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use null to disable the consistent viewport emulation. Learn more about viewport emulation.

note

null value opts out from the default presets, makes viewport depend on the host window size defined by the operating system. It makes the execution of the tests non-deterministic. :::这

返回

Returns


newPage

Added in: v1.8browser.newPage

在新的浏览器上下文中创建新页面。关闭此页面也将关闭上下文。

Creates a new page in a new browser context. Closing this page will close the context as well.

这是一个便捷的 API,仅适用于单页场景和短片段。生产代码和测试框架应显式创建 browser.newContext(),然后创建 browserContext.newPage(),以控制它们的确切生命周期。

This is a convenience API that should only be used for the single-page scenarios and short snippets. Production code and testing frameworks should explicitly create browser.newContext() followed by the browserContext.newPage() to control their exact life times.

用法

Usage

await browser.newPage();
await browser.newPage(options);

参数

Arguments

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

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

当使用 page.goto()page.route()page.waitForURL()page.waitForRequest()page.waitForResponse() 时,它会使用 URL() 构造函数来构建相应的 URL,从而考虑基本 URL。默认情况下取消设置。示例:

When using page.goto(), page.route(), page.waitForURL(), page.waitForRequest(), or page.waitForResponse() it takes the base URL in consideration by using the URL() constructor for building the corresponding URL. Unset by default. Examples:

  • baseURL:http://localhost:3000 并导航至 /bar.html 结果为 http://localhost:3000/bar.html

    baseURL: http://localhost:3000 and navigating to /bar.html results in http://localhost:3000/bar.html

  • baseURL:http://localhost:3000/foo/ 并导航至 ./bar.html 结果为 http://localhost:3000/foo/bar.html

    baseURL: http://localhost:3000/foo/ and navigating to ./bar.html results in http://localhost:3000/foo/bar.html

  • baseURL:http://localhost:3000/foo(无尾部斜杠)并导航至 ./bar.html 将导致 http://localhost:3000/bar.html

    baseURL: http://localhost:3000/foo (without trailing slash) and navigating to ./bar.html results in http://localhost:3000/bar.html

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

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

  • colorScheme null|"light"|"dark"|"no-preference" (optional)#

模拟 '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'.

  • deviceScaleFactor number (optional)#

指定设备比例因子(可以视为 dpr)。默认为 1。了解有关 使用设备比例因子模拟设备 的更多信息。

Specify device scale factor (can be thought of as dpr). Defaults to 1. Learn more about emulating devices with device scale factor.

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

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

  • forcedColors null|"active"|"none" (optional)#

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

Emulates 'forced-colors' media feature, supported values are 'active', 'none'. See page.emulateMedia() for more details. Passing null resets emulation to system defaults. 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.

指定视口是否支持触摸事件。默认为 false。了解有关 移动模拟 的更多信息。

Specifies if viewport supports touch events. Defaults to false. Learn more about mobile emulation.

限制在特定来源 (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.

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

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

是否考虑 meta viewport 标签并启用触摸事件。isMobile 是设备的一部分,因此你实际上不需要手动设置它。默认为 false,Firefox 不支持。了解有关 移动模拟 的更多信息。

Whether the meta viewport tag is taken into account and touch events are enabled. isMobile is a part of device, so you don't actually need to set it manually. Defaults to false and is not supported in Firefox. Learn more about mobile emulation.

是否在上下文中启用 JavaScript。默认为 true。了解有关 禁用 JavaScript 的更多信息。

Whether or not to enable JavaScript in the context. Defaults to true. Learn more about disabling JavaScript.

指定用户区域设置,例如 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.

用于 Playwright 日志记录的日志器接收器。

Logger sink for Playwright logging.

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

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

授予此上下文中所有页面的权限列表。详细信息请参见 browserContext.grantPermissions()。默认为无。

A list of permissions to grant to all pages in this context. See browserContext.grantPermissions() for more details. Defaults to none.

用于所有请求的代理。支持 HTTP 和 SOCKS 代理,例如 http://myproxy.com:3128socks5://myproxy.com:3128。缩写形式 myproxy.com:3128 被视为 HTTP 代理。

Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example http://myproxy.com:3128 or socks5://myproxy.com:3128. Short form myproxy.com:3128 is considered an HTTP proxy.

用于绕过代理的可选逗号分隔域,例如 ".com, chromium.org, .domain.com"

Optional comma-separated domains to bypass proxy, for example ".com, chromium.org, .domain.com".

如果 HTTP 代理需要身份验证,则使用可选的用户名。

Optional username to use if HTTP proxy requires authentication.

如果 HTTP 代理需要身份验证,则使用可选密码。

Optional password to use if HTTP proxy requires authentication.

与此上下文一起使用的网络代理设置。默认为无。

Network proxy settings to use with this context. Defaults to none.

note

launch({ proxy: { server: 'http://per-context' } }). :::对于 Windows 上的 Chromium,需要使用全局代理启动浏览器才能使此选项发挥作用。如果所有上下文都覆盖代理,则全局代理将永远不会被使用,并且可以是任何字符串,例如

用于控制是否省略 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.

  • reducedMotion null|"reduce"|"no-preference" (optional)#

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

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

页面宽度(以像素为单位)。

page width in pixels.

页面高度(以像素为单位)。

page height in pixels.

通过 window.screen 模拟网页内可用的一致窗口屏幕尺寸。仅当设置了 viewport 时才使用。

Emulates consistent window screen size available inside web page via window.screen. Is only used when the viewport is set.

  • serviceWorkers "allow"|"block"(可选)#

    serviceWorkers "allow"|"block" (optional)#

    是否允许站点注册 Service Worker。默认为 'allow'

    Whether to allow sites to register Service workers. Defaults to 'allow'.

    • 'allow'服务工作进程 可以注册。

      'allow': Service Workers can be registered.

    • 'block':Playwright 将阻止所有服务工作进程的注册。

      'block': Playwright will block all registration of Service Workers.

需要域和路径。为了使 cookie 也适用于所有子域,请在域前添加一个点,如下所示:".example.com"

Domain and path are required. For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com"

域名和路径为必填项

Domain and path are required

Unix 时间以秒为单位。

Unix time in seconds.

  • sameSite "严格的"|"Lax"|"没有任何"

    sameSite "Strict"|"Lax"|"None"

    同一站点标志

    sameSite flag

为上下文设置的 Cookie

Cookies to set for context

localStorage 设置上下文

localStorage to set for context

了解有关 存储状态和授权 的更多信息。

Learn more about storage state and auth.

使用给定的存储状态填充上下文。该选项可用于使用通过 browserContext.storageState() 获取的登录信息来初始化上下文。

Populates context with given storage state. This option can be used to initialize context with logged-in information obtained via browserContext.storageState().

如果设置为 true,则为此上下文启用严格选择器模式。在严格选择器模式下,当多个元素与选择器匹配时,所有暗示单个目标 DOM 元素的选择器操作都会抛出异常。此选项不会影响任何定位器 API(定位器始终是严格的)。默认为 false。请参阅 定位器 了解有关严格模式的更多信息。

If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors that imply single target DOM element will throw when more than one element matches the selector. This option does not affect any Locator APIs (Locators are always strict). Defaults to false. See Locator to learn more about the strict mode.

更改上下文的时区。有关支持的时区 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.

在此上下文中使用的特定用户代理。

Specific user agent to use in this context.

Deprecated

Use recordVideo instead.

视频帧宽度。

Video frame width.

视频帧高度。

Video frame height.

Deprecated

Use recordVideo instead.

页面宽度(以像素为单位)。

page width in pixels.

页面高度(以像素为单位)。

page height in pixels.

模拟每个页面的一致视口。默认为 1280x720 视口。使用 null 禁用一致视口模拟。了解有关 视口模拟 的更多信息。

Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use null to disable the consistent viewport emulation. Learn more about viewport emulation.

note

null value opts out from the default presets, makes viewport depend on the host window size defined by the operating system. It makes the execution of the tests non-deterministic. :::这

返回

Returns


startTracing

Added in: v1.11browser.startTracing
注意

该 API 控制 Chromium 追踪,它是一个底层 chromium 特定的调试工具。可以找到控制 Playwright 追踪 的 API 此处

This API controls Chromium Tracing which is a low-level chromium-specific debugging tool. API to control Playwright Tracing could be found here.

你可以使用 browser.startTracing()browser.stopTracing() 创建可在 Chrome DevTools 性能面板中打开的跟踪文件。

You can use browser.startTracing() and browser.stopTracing() to create a trace file that can be opened in Chrome DevTools performance panel.

用法

Usage

await browser.startTracing(page, { path: 'trace.json' });
await page.goto('https://www.google.com');
await browser.stopTracing();

参数

Arguments

可选(如果指定),跟踪包括给定页面的屏幕截图。

Optional, if specified, tracing includes screenshots of the given page.

指定要使用的自定义类别而不是默认类别。

specify custom categories to use instead of default.

写入跟踪文件的路径。

A path to write the trace file to.

捕获跟踪中的屏幕截图。

captures screenshots in the trace.


stopTracing

Added in: v1.11 browser.stopTracing
注意

该 API 控制 Chromium 追踪,它是一个底层 chromium 特定的调试工具。可以找到控制 Playwright 追踪 的 API 此处

This API controls Chromium Tracing which is a low-level chromium-specific debugging tool. API to control Playwright Tracing could be found here.

返回带有跟踪数据的缓冲区。

Returns the buffer with trace data.

用法

Usage

await browser.stopTracing();

返回

Returns


version

Added in: v1.8 browser.version

返回浏览器版本。

Returns the browser version.

用法

Usage

browser.version();

返回

Returns


事件

Events

on('disconnected')

Added in: v1.8 browser.on('disconnected')

当浏览器与浏览器应用断开连接时触发。发生这种情况可能是由于以下原因之一:

Emitted when Browser gets disconnected from the browser application. This might happen because of one of the following:

  • 浏览器应用已关闭或崩溃。

    Browser application is closed or crashed.

  • 调用了 browser.close() 方法。

    The browser.close() method was called.

用法

Usage

browser.on('disconnected', data => {});

事件数据

Event data