Browser
通过 browserType.launch() 创建浏览器。使用 Browser 创建 Page 的示例:
¥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获取浏览器所属的浏览器类型(chromium、firefox 或 webkit)。
¥Get the browser type (chromium, firefox or webkit) that the browser belongs to.
用法
¥Usage
browser.browserType();
返回
¥Returns
close
Added before v1.9如果使用 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().
Browser 对象本身被认为已被释放,不能再使用。
¥The Browser object itself is considered to be disposed and cannot be used anymore.
用法
¥Usage
await browser.close();
await browser.close(options);
参数
¥Arguments
报告的原因是由于浏览器关闭而中断的操作。
¥The reason to be reported to the operations interrupted by the browser closure.
返回
¥Returns
contexts
Added before v1.9返回所有打开的浏览器上下文的数组。在新创建的浏览器中,这将返回零浏览器上下文。
¥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 before v1.9表示浏览器已连接。
¥Indicates that the browser is connected.
用法
¥Usage
browser.isConnected();
返回
¥Returns
newBrowserCDPSession
Added in: v1.11CDP 会话仅在基于 Chromium 的浏览器上受支持。
¥CDP Sessions are only supported on Chromium-based browsers.
返回新创建的浏览器会话。
¥Returns the newly created browser session.
用法
¥Usage
await browser.newBrowserCDPSession();
返回
¥Returns
newContext
Added before v1.9创建一个新的浏览器上下文。它不会与其他浏览器上下文共享 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 inhttp://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 inhttp://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 inhttp://localhost:3000/bar.html
切换绕过页面的内容安全策略。默认为 false
。
¥Toggles bypassing page's Content-Security-Policy. Defaults to false
.
证书有效的确切来源。Origin 包括 https
协议、主机名和可选的端口。
¥Exact origin that the certificate is valid for. Origin includes https
protocol, a hostname and optionally a port.
certPath
string (optional)
PEM 格式的证书文件路径。
¥Path to the file with the certificate in PEM format.
cert
Buffer (optional)
PEM 格式的证书的直接值。
¥Direct value of the certificate in PEM format.
keyPath
string (optional)
PEM 格式的私钥文件路径。
¥Path to the file with the private key in PEM format.
key
Buffer (optional)
PEM 格式的私钥的直接值。
¥Direct value of the private key in PEM format.
pfxPath
string (optional)
PFX 或 PKCS12 编码的私钥和证书链的路径。
¥Path to the PFX or PKCS12 encoded private key and certificate chain.
pfx
Buffer (optional)
PFX 或 PKCS12 编码的私钥和证书链的直接值。
¥Direct value of the PFX or PKCS12 encoded private key and certificate chain.
passphrase
string (optional)
私钥的密码(PEM 或 PFX)。
¥Passphrase for the private key (PEM or PFX).
TLS 客户端身份验证允许服务器请求客户端证书并对其进行验证。
¥TLS Client Authentication allows the server to request a client certificate and verify it.
细节
¥Details
要使用的客户端证书数组。每个证书对象必须同时具有 certPath
和 keyPath
、单个 pfxPath
或它们对应的直接值等价物(cert
和 key
或 pfx
)。如果证书已加密,则可选地提供 passphrase
属性。origin
属性应与证书有效的请求来源完全匹配。
¥An array of client certificates to be used. Each certificate object must have either both certPath
and keyPath
, a single pfxPath
, or their corresponding direct value equivalents (cert
and key
, or pfx
). Optionally, passphrase
property should be provided if the certificate is encrypted. The origin
property should be provided with an exact match to the request origin that the certificate is valid for.
在 macOS 上使用 WebKit 时,访问 localhost
将不会获取客户端证书。你可以通过将 localhost
替换为 local.playwright
来使其工作。:::
¥When using WebKit on macOS, accessing localhost
will not pick up client certificates. You can make it work by replacing localhost
with local.playwright
.
模拟 prefers-colors-scheme 媒体功能,支持的值为 'light'
和 'dark'
。详细信息请参见 page.emulateMedia()。传递 null
会将模拟重置为系统默认值。默认为 'light'
。
¥Emulates prefers-colors-scheme media feature, supported values are 'light'
and 'dark'
. See page.emulateMedia() for more details. Passing null
resets emulation to system defaults. Defaults to 'light'
.
指定设备比例因子(可以视为 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.
模拟 '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.
longitude
number
经度在 -180 到 180 之间。
¥Longitude between -180 and 180.
accuracy
number (optional)
非负精度值。默认为 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).
-
send
"unauthorized" | "always"(可选)¥
send
"unauthorized" | "always" (optional)此选项仅适用于从相应 APIRequestContext 发送的请求,不影响从浏览器发送的请求。
'always'
- 带有基本身份验证凭据的Authorization
标头将随每个 API 请求一起发送。'unauthorized
- 仅当收到带有WWW-Authenticate
标头的 401(未授权)响应时才会发送凭据。默认为'unauthorized'
。¥This option only applies to the requests sent from corresponding 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 withWWW-Authenticate
header is received. Defaults to'unauthorized'
.
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-GB
、de-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:3128
或 socks5://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.
bypass
string (optional)
用于绕过代理的可选逗号分隔域,例如 ".com, chromium.org, .domain.com"
。
¥Optional comma-separated domains to bypass proxy, for example ".com, chromium.org, .domain.com"
.
username
string (optional)
如果 HTTP 代理需要身份验证,则使用可选的用户名。
¥Optional username to use if HTTP proxy requires authentication.
password
string (optional)
如果 HTTP 代理需要身份验证,则使用可选密码。
¥Optional password to use if HTTP proxy requires authentication.
与此上下文一起使用的网络代理设置。默认为无。
¥Network proxy settings to use with this context. Defaults to none.
用于控制是否省略 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. Ifattach
is specified, resources are persisted as separate files or entries in the ZIP archive. Ifembed
is specified, content is stored inline the HAR file as per HAR specification. Defaults toattach
for.zip
output files and toembed
for all other file extensions.path
string
将 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 tofull
.
用于过滤存储在 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.
height
number
视频帧高度。
¥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.
模拟 '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.
height
number
页面高度(以像素为单位)。
¥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"
path
string
域名和路径为必填项
¥Domain and path are required
expires
number
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
。请参阅 Locator 了解有关严格模式的更多信息。
¥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.
Use recordVideo instead.
width
number
视频帧宽度。
¥Video frame width.
height
number
视频帧高度。
¥Video frame height.
Use recordVideo instead.
页面宽度(以像素为单位)。
¥page width in pixels.
height
number
页面高度(以像素为单位)。
¥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.
null
值从默认预设中选择退出,使视口取决于操作系统定义的主机窗口大小。它使得测试的执行具有不确定性。:::
¥The 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 before v1.9在新的浏览器上下文中创建新页面。关闭此页面也将关闭上下文。
¥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 inhttp://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 inhttp://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 inhttp://localhost:3000/bar.html
切换绕过页面的内容安全策略。默认为 false
。
¥Toggles bypassing page's Content-Security-Policy. Defaults to false
.
证书有效的确切来源。Origin 包括 https
协议、主机名和可选的端口。
¥Exact origin that the certificate is valid for. Origin includes https
protocol, a hostname and optionally a port.
certPath
string (optional)
PEM 格式的证书文件路径。
¥Path to the file with the certificate in PEM format.
cert
Buffer (optional)
PEM 格式的证书的直接值。
¥Direct value of the certificate in PEM format.
keyPath
string (optional)
PEM 格式的私钥文件路径。
¥Path to the file with the private key in PEM format.
key
Buffer (optional)
PEM 格式的私钥的直接值。
¥Direct value of the private key in PEM format.
pfxPath
string (optional)
PFX 或 PKCS12 编码的私钥和证书链的路径。
¥Path to the PFX or PKCS12 encoded private key and certificate chain.
pfx
Buffer (optional)
PFX 或 PKCS12 编码的私钥和证书链的直接值。
¥Direct value of the PFX or PKCS12 encoded private key and certificate chain.
passphrase
string (optional)
私钥的密码(PEM 或 PFX)。
¥Passphrase for the private key (PEM or PFX).
TLS 客户端身份验证允许服务器请求客户端证书并对其进行验证。
¥TLS Client Authentication allows the server to request a client certificate and verify it.
细节
¥Details
要使用的客户端证书数组。每个证书对象必须同时具有 certPath
和 keyPath
、单个 pfxPath
或它们对应的直接值等价物(cert
和 key
或 pfx
)。如果证书已加密,则可选地提供 passphrase
属性。origin
属性应与证书有效的请求来源完全匹配。
¥An array of client certificates to be used. Each certificate object must have either both certPath
and keyPath
, a single pfxPath
, or their corresponding direct value equivalents (cert
and key
, or pfx
). Optionally, passphrase
property should be provided if the certificate is encrypted. The origin
property should be provided with an exact match to the request origin that the certificate is valid for.
在 macOS 上使用 WebKit 时,访问 localhost
将不会获取客户端证书。你可以通过将 localhost
替换为 local.playwright
来使其工作。:::
¥When using WebKit on macOS, accessing localhost
will not pick up client certificates. You can make it work by replacing localhost
with local.playwright
.
模拟 prefers-colors-scheme 媒体功能,支持的值为 'light'
和 'dark'
。详细信息请参见 page.emulateMedia()。传递 null
会将模拟重置为系统默认值。默认为 'light'
。
¥Emulates prefers-colors-scheme media feature, supported values are 'light'
and 'dark'
. See page.emulateMedia() for more details. Passing null
resets emulation to system defaults. Defaults to 'light'
.
指定设备比例因子(可以视为 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.
模拟 '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.
longitude
number
经度在 -180 到 180 之间。
¥Longitude between -180 and 180.
accuracy
number (optional)
非负精度值。默认为 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).
-
send
"unauthorized" | "always"(可选)¥
send
"unauthorized" | "always" (optional)此选项仅适用于从相应 APIRequestContext 发送的请求,不影响从浏览器发送的请求。
'always'
- 带有基本身份验证凭据的Authorization
标头将随每个 API 请求一起发送。'unauthorized
- 仅当收到带有WWW-Authenticate
标头的 401(未授权)响应时才会发送凭据。默认为'unauthorized'
。¥This option only applies to the requests sent from corresponding 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 withWWW-Authenticate
header is received. Defaults to'unauthorized'
.
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-GB
、de-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:3128
或 socks5://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.
bypass
string (optional)
用于绕过代理的可选逗号分隔域,例如 ".com, chromium.org, .domain.com"
。
¥Optional comma-separated domains to bypass proxy, for example ".com, chromium.org, .domain.com"
.
username
string (optional)
如果 HTTP 代理需要身份验证,则使用可选的用户名。
¥Optional username to use if HTTP proxy requires authentication.
password
string (optional)
如果 HTTP 代理需要身份验证,则使用可选密码。
¥Optional password to use if HTTP proxy requires authentication.
与此上下文一起使用的网络代理设置。默认为无。
¥Network proxy settings to use with this context. Defaults to none.
用于控制是否省略 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. Ifattach
is specified, resources are persisted as separate files or entries in the ZIP archive. Ifembed
is specified, content is stored inline the HAR file as per HAR specification. Defaults toattach
for.zip
output files and toembed
for all other file extensions.path
string
将 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 tofull
.
用于过滤存储在 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.
height
number
视频帧高度。
¥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.
模拟 '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.
height
number
页面高度(以像素为单位)。
¥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"
path
string
域名和路径为必填项
¥Domain and path are required
expires
number
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
。请参阅 Locator 了解有关严格模式的更多信息。
¥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.
Use recordVideo instead.
width
number
视频帧宽度。
¥Video frame width.
height
number
视频帧高度。
¥Video frame height.
Use recordVideo instead.
页面宽度(以像素为单位)。
¥page width in pixels.
height
number
页面高度(以像素为单位)。
¥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.
null
值从默认预设中选择退出,使视口取决于操作系统定义的主机窗口大小。它使得测试的执行具有不确定性。:::
¥The 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
removeAllListeners
Added in: v1.47删除给定类型的所有监听器(如果没有指定类型,则删除所有已注册的监听器)。允许等待异步监听器完成或忽略这些监听器的后续错误。
¥Removes all the listeners of the given type (or all registered listeners if no type given). Allows to wait for async listeners to complete or to ignore subsequent errors from these listeners.
用法
¥Usage
await browser.removeAllListeners();
await browser.removeAllListeners(type, options);
参数
¥Arguments
-
behavior
"wait" | "ignoreErrors" | "default"(可选)#¥
behavior
"wait" | "ignoreErrors" | "default" (optional)#指定是否等待已经运行的监听器以及如果它们抛出错误该怎么做: =
¥Specifies whether to wait for already running listeners and what to do if they throw errors:
-
'default'
- 不要等待当前监听器调用(如果有)完成,如果监听器抛出,可能会导致未处理的错误¥
'default'
- do not wait for current listener calls (if any) to finish, if the listener throws, it may result in unhandled error -
'wait'
- 等待当前监听器调用(如果有)完成¥
'wait'
- wait for current listener calls (if any) to finish -
'ignoreErrors'
- 不要等待当前监听器调用(如果有)完成,删除后监听器抛出的所有错误都会被默默捕获¥
'ignoreErrors'
- do not wait for current listener calls (if any) to finish, all errors thrown by the listeners after removal are silently caught
-
返回
¥Returns
startTracing
Added in: v1.11该 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.
返回
¥Returns
stopTracing
Added in: v1.11该 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 before v1.9返回浏览器版本。
¥Returns the browser version.
用法
¥Usage
browser.version();
返回
¥Returns
事件
¥Events
on('disconnected')
Added before v1.9当浏览器与浏览器应用断开连接时触发。发生这种情况可能是由于以下原因之一:
¥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