Skip to main content

BrowserContext

BrowserContexts 提供了一种操作多个独立浏览器会话的方法。

¥BrowserContexts provide a way to operate multiple independent browser sessions.

如果一个页面打开另一个页面,例如 通过 window.open 调用,弹出窗口将属于父页面的浏览器上下文。

¥If a page opens another page, e.g. with a window.open call, the popup will belong to the parent page's browser context.

Playwright 允许使用 browser.newContext() 方法创建 "incognito" 浏览器上下文。"隐姓埋名" 浏览器上下文不会将任何浏览数据写入磁盘。

¥Playwright allows creating "incognito" browser contexts with browser.newContext() method. "Incognito" browser contexts don't write any browsing data to disk.

// Create a new incognito browser context
const context = await browser.newContext();
// Create a new page inside context.
const page = await context.newPage();
await page.goto('https://example.com');
// Dispose context once it's no longer needed.
await context.close();

方法

¥Methods

addCookies

Added in: v1.8 browserContext.addCookies

将 cookie 添加到此浏览器上下文中。此上下文中的所有页面都将安装这些 cookie。Cookie 可以通过 browserContext.cookies() 获取。

¥Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies can be obtained via browserContext.cookies().

用法

¥Usage

await browserContext.addCookies([cookieObject1, cookieObject2]);

参数

¥Arguments

需要 url 或域/路径。可选的。

¥either url or domain / path are required. Optional.

url 或域/路径是必需的 可选。

¥either url or domain / path are required Optional.

url 或域/路径是必需的 可选。

¥either url or domain / path are required Optional.

Unix 时间以秒为单位。可选的。

¥Unix time in seconds. Optional.

可选的。

¥Optional.

可选的。

¥Optional.

  • sameSite "严格的"|"Lax"|"没有任何"(可选)

    ¥sameSite "Strict"|"Lax"|"None" (optional)

    可选的。

    ¥Optional.

将 cookie 添加到浏览器上下文中。

¥Adds cookies to the browser context.

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

¥For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com".

返回

¥Returns


addInitScript

Added in: v1.8 browserContext.addInitScript

添加将在以下场景之一进行评估的脚本:

¥Adds a script which would be evaluated in one of the following scenarios:

  • 每当在浏览器上下文中创建页面或导航页面时。

    ¥Whenever a page is created in the browser context or is navigated.

  • 每当在浏览器上下文中的任何页面中附加或导航子框架时。在这种情况下,脚本将在新附加的框架的上下文中进行评估。

    ¥Whenever a child frame is attached or navigated in any page in the browser context. In this case, the script is evaluated in the context of the newly attached frame.

该脚本在创建文档之后但在运行其任何脚本之前进行评估。这对于修改 JavaScript 环境很有用,例如 种子 Math.random

¥The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random.

用法

¥Usage

在页面加载之前覆盖 Math.random 的示例:

¥An example of overriding Math.random before the page loads:

// preload.js
Math.random = () => 42;
// In your playwright script, assuming the preload.js file is in same directory.
await browserContext.addInitScript({
path: 'preload.js'
});
注意

通过 browserContext.addInitScript()page.addInitScript() 安装的多个脚本的评估顺序未定义。

¥The order of evaluation of multiple scripts installed via browserContext.addInitScript() and page.addInitScript() is not defined.

参数

¥Arguments

JavaScript 文件的路径。如果 path 是相对路径,则相对于当前工作目录进行解析。可选的。

¥Path to the JavaScript file. If path is a relative path, then it is resolved relative to the current working directory. Optional.

原始脚本内容。可选的。

¥Raw script content. Optional.

要在浏览器上下文中的所有页面中评估的脚本。

¥Script to be evaluated in all pages in the browser context.

传递给 script 的可选参数(仅在传递函数时受支持)。

¥Optional argument to pass to script (only supported when passing a function).

返回

¥Returns


backgroundPages

Added in: v1.11 browserContext.backgroundPages
注意

仅基于 Chromium 的浏览器支持后台页面。

¥Background pages are only supported on Chromium-based browsers.

上下文中所有现有的背景页面。

¥All existing background pages in the context.

用法

¥Usage

browserContext.backgroundPages();

返回

¥Returns


browser

Added in: v1.8 browserContext.browser

返回上下文的浏览器实例。如果它作为持久上下文启动,则返回 null。

¥Returns the browser instance of the context. If it was launched as a persistent context null gets returned.

用法

¥Usage

browserContext.browser();

返回

¥Returns


clearCookies

Added in: v1.8 browserContext.clearCookies

从上下文中删除 cookie。接受可选过滤器。

¥Removes cookies from context. Accepts optional filter.

用法

¥Usage

await context.clearCookies();
await context.clearCookies({ name: 'session-id' });
await context.clearCookies({ domain: 'my-origin.com' });
await context.clearCookies({ domain: /.*my-origin\.com/ });
await context.clearCookies({ path: '/api/v1' });
await context.clearCookies({ name: 'session-id', domain: 'my-origin.com' });

参数

¥Arguments

仅删除具有给定域的 cookie。

¥Only removes cookies with the given domain.

仅删除具有给定名称的 cookie。

¥Only removes cookies with the given name.

仅删除具有给定路径的 cookie。

¥Only removes cookies with the given path.

返回

¥Returns


clearPermissions

Added in: v1.8 browserContext.clearPermissions

清除浏览器上下文的所有权限覆盖。

¥Clears all permission overrides for the browser context.

用法

¥Usage

const context = await browser.newContext();
await context.grantPermissions(['clipboard-read']);
// do stuff ..
context.clearPermissions();

返回

¥Returns


close

Added in: v1.8 browserContext.close

关闭浏览器上下文。属于浏览器上下文的所有页面都将被关闭。

¥Closes the browser context. All the pages that belong to the browser context will be closed.

注意

默认浏览器上下文无法关闭。

¥The default browser context cannot be closed.

用法

¥Usage

await browserContext.close();
await browserContext.close(options);

参数

¥Arguments

  • options Object (optional)

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

被报告给因上下文关闭而中断的操作的原因。

¥The reason to be reported to the operations interrupted by the context closure.

返回

¥Returns


cookies

Added in: v1.8 browserContext.cookies

如果未指定 URL,此方法将返回所有 cookie。如果指定了 URL,则仅返回影响这些 URL 的 cookie。

¥If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned.

用法

¥Usage

await browserContext.cookies();
await browserContext.cookies(urls);

参数

¥Arguments

可选的 URL 列表。

¥Optional list of URLs.

返回

¥Returns

Unix 时间以秒为单位。

¥Unix time in seconds.

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

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


exposeBinding

Added in: v1.8 browserContext.exposeBinding

该方法在上下文中每个页面的每个帧的 window 对象上添加一个名为 name 的函数。调用时,该函数执行 callback 并返回 Promise,该 Promise 解析为 callback 的返回值。如果 callback 返回 Promise,则将等待它。

¥The method adds a function called name on the window object of every frame in every page in the context. When called, the function executes callback and returns a Promise which resolves to the return value of callback. If the callback returns a Promise, it will be awaited.

callback 函数的第一个参数包含有关调用者的信息:{ browserContext: BrowserContext, page: Page, frame: Frame }

¥The first argument of the callback function contains information about the caller: { browserContext: BrowserContext, page: Page, frame: Frame }.

有关仅页面版本,请参阅 page.exposeBinding()

¥See page.exposeBinding() for page-only version.

用法

¥Usage

将页面 URL 暴露给上下文中所有页面中的所有框架的示例:

¥An example of exposing page URL to all frames in all pages in the context:

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

(async () => {
const browser = await webkit.launch({ headless: false });
const context = await browser.newContext();
await context.exposeBinding('pageURL', ({ page }) => page.url());
const page = await context.newPage();
await page.setContent(`
<script>
async function onClick() {
document.querySelector('div').textContent = await window.pageURL();
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
`);
await page.getByRole('button').click();
})();

传递元素句柄的示例:

¥An example of passing an element handle:

await context.exposeBinding('clicked', async (source, element) => {
console.log(await element.textContent());
}, { handle: true });
await page.setContent(`
<script>
document.addEventListener('click', event => window.clicked(event.target));
</script>
<div>Click me</div>
<div>Or click me</div>
`);

参数

¥Arguments

窗口对象上的函数名称。

¥Name of the function on the window object.

将在 Playwright 上下文中调用的回调函数。

¥Callback function that will be called in the Playwright's context.

是否将参数作为句柄传递,而不是按值传递。传递句柄时,仅支持一个参数。按值传递时,支持多个参数。

¥Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is supported. When passing by value, multiple arguments are supported.

返回

¥Returns


exposeFunction

Added in: v1.8 browserContext.exposeFunction

该方法在上下文中每个页面的每个帧的 window 对象上添加一个名为 name 的函数。调用时,该函数执行 callback 并返回 Promise,该 Promise 解析为 callback 的返回值。

¥The method adds a function called name on the window object of every frame in every page in the context. When called, the function executes callback and returns a Promise which resolves to the return value of callback.

如果 callback 返回 Promise,则将等待它。

¥If the callback returns a Promise, it will be awaited.

有关仅页面版本,请参阅 page.exposeFunction()

¥See page.exposeFunction() for page-only version.

用法

¥Usage

向上下文中的所有页面添加 sha256 功能的示例:

¥An example of adding a sha256 function to all pages in the context:

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

(async () => {
const browser = await webkit.launch({ headless: false });
const context = await browser.newContext();
await context.exposeFunction('sha256', text =>
crypto.createHash('sha256').update(text).digest('hex'),
);
const page = await context.newPage();
await page.setContent(`
<script>
async function onClick() {
document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
`);
await page.getByRole('button').click();
})();

参数

¥Arguments

窗口对象上的函数名称。

¥Name of the function on the window object.

将在 Playwright 上下文中调用的回调函数。

¥Callback function that will be called in the Playwright's context.

返回

¥Returns


grantPermissions

Added in: v1.8 browserContext.grantPermissions

授予浏览器上下文指定的权限。如果指定,仅向给定源授予相应权限。

¥Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if specified.

用法

¥Usage

await browserContext.grantPermissions(permissions);
await browserContext.grantPermissions(permissions, options);

参数

¥Arguments

要授予的一个权限或一组权限。权限可以是以下值之一:

¥A permission or an array of permissions to grant. Permissions can be one of the following values:

  • 'geolocation'

  • 'midi'

  • 'midi-sysex'(系统独有的 MIDI)

    ¥'midi-sysex' (system-exclusive midi)

  • 'notifications'

  • 'camera'

  • 'microphone'

  • 'background-sync'

  • 'ambient-light-sensor'

  • 'accelerometer'

  • 'gyroscope'

  • 'magnetometer'

  • 'accessibility-events'

  • 'clipboard-read'

  • 'clipboard-write'

  • 'payment-handler'

授予权限的 origin,例如 “https://example.com”。

¥The origin to grant permissions to, e.g. "https://example.com".

返回

¥Returns


newCDPSession

Added in: v1.11 browserContext.newCDPSession
注意

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

¥CDP sessions are only supported on Chromium-based browsers.

返回新创建的会话。

¥Returns the newly created session.

用法

¥Usage

await browserContext.newCDPSession(page);

参数

¥Arguments

要为其创建新会话的目标。为了向后兼容,该参数被命名为 page,但它可以是 PageFrame 类型。

¥Target to create new session for. For backwards-compatibility, this parameter is named page, but it can be a Page or Frame type.

返回

¥Returns


newPage

Added in: v1.8 browserContext.newPage

在浏览器上下文中创建一个新页面。

¥Creates a new page in the browser context.

用法

¥Usage

await browserContext.newPage();

返回

¥Returns


pages

Added in: v1.8 browserContext.pages

返回上下文中所有打开的页面。

¥Returns all open pages in the context.

用法

¥Usage

browserContext.pages();

返回

¥Returns


route

Added in: v1.8 browserContext.route

路由提供了修改浏览器上下文中任何页面触发的网络请求的功能。一旦启用路由,每个与 url 模式匹配的请求都将停止,除非它继续、完成或中止。

¥Routing provides the capability to modify network requests that are made by any page in the browser context. Once route is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.

注意

browserContext.route() 不会拦截 Service Worker 拦截的请求。参见 this 期。我们建议在使用请求拦截时通过将 Browser.newContext.serviceWorkers 设置为 'block' 来禁用 Service Worker。

¥browserContext.route() will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by setting Browser.newContext.serviceWorkers to 'block'.

用法

¥Usage

中止所有图片请求的简单处理程序的示例:

¥An example of a naive handler that aborts all image requests:

const context = await browser.newContext();
await context.route('**/*.{png,jpg,jpeg}', route => route.abort());
const page = await context.newPage();
await page.goto('https://example.com');
await browser.close();

或使用正则表达式模式的相同片段:

¥or the same snippet using a regex pattern instead:

const context = await browser.newContext();
await context.route(/(\.png$)|(\.jpg$)/, route => route.abort());
const page = await context.newPage();
await page.goto('https://example.com');
await browser.close();

可以检查请求来决定路由操作。例如,模拟包含某些发布数据的所有请求,并保留所有其他请求不变:

¥It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:

await context.route('/api/**', async route => {
if (route.request().postData().includes('my-string'))
await route.fulfill({ body: 'mocked-data' });
else
await route.continue();
});

当请求与两个处理程序匹配时,页面路由(使用 page.route() 设置)优先于浏览器上下文路由。

¥Page routes (set up with page.route()) take precedence over browser context routes when request matches both handlers.

要删除路由及其处理程序,你可以使用 browserContext.unroute()

¥To remove a route with its handler you can use browserContext.unroute().

注意

启用路由会禁用 http 缓存。

¥Enabling routing disables http cache.

参数

¥Arguments

通配符模式、正则表达式模式或谓词接收 URL 以在路由时进行匹配。当通过上下文选项提供 baseURL 并且传递的 URL 是路径时,它将通过 new URL() 构造函数合并。

¥A glob pattern, regex pattern or predicate receiving URL to match while routing. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.

处理程序函数来路由请求。

¥handler function to route the request.

  • options Object (optional)

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

路由应该多久使用一次。默认情况下每次都会使用它。

¥How often a route should be used. By default it will be used every time.

返回

¥Returns


routeFromHAR

Added in: v1.23 browserContext.routeFromHAR

如果指定,上下文中触发的网络请求将从 HAR 文件提供服务。了解有关 从 HAR 重播 的更多信息。

¥If specified the network requests that are made in the context will be served from the HAR file. Read more about Replaying from HAR.

Playwright 不会处理 Service Worker 从 HAR 文件中拦截的请求。参见 this 期。我们建议在使用请求拦截时通过将 Browser.newContext.serviceWorkers 设置为 'block' 来禁用 Service Worker。

¥Playwright will not serve requests intercepted by Service Worker from the HAR file. See this issue. We recommend disabling Service Workers when using request interception by setting Browser.newContext.serviceWorkers to 'block'.

用法

¥Usage

await browserContext.routeFromHAR(har);
await browserContext.routeFromHAR(har, options);

参数

¥Arguments

带有预先记录的网络数据的 HAR 文件的路径。如果 path 是相对路径,则相对于当前工作目录进行解析。

¥Path to a HAR file with prerecorded network data. If path is a relative path, then it is resolved relative to the current working directory.

  • notFound "abort"|"fallback"(可选)#

    ¥notFound "abort"|"fallback" (optional)#

    • 如果设置为 'abort',在 HAR 文件中找不到的任何请求都将被中止。

      ¥If set to 'abort' any request not found in the HAR file will be aborted.

    • 如果设置为 'fallback',则会进入处理程序链中的下一个路由处理程序。

      ¥If set to 'fallback' falls through to the next route handler in the handler chain. 默认为中止。

    ¥Defaults to abort.

如果指定,则使用实际网络信息更新给定的 HAR,而不是从文件提供服务。当调用 browserContext.close() 时,文件被写入磁盘。

¥If specified, updates the given HAR with the actual network information instead of serving from file. The file is written to disk when browserContext.close() is called.

  • updateContent "embed"|"attach"(可选) Added in: v1.32#

    ¥updateContent "embed"|"attach" (optional) Added in: v1.32#

    用于控制资源内容管理的可选设置。如果指定了 attach,资源将作为单独的文件或条目保留在 ZIP 存档中。如果指定了 embed,内容将内联存储在 HAR 文件中。

    ¥Optional setting to control resource content management. 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.

  • updateMode "full"|"minimal"(可选) Added in: v1.32#

    ¥updateMode "full"|"minimal" (optional) Added in: v1.32#

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

    ¥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 minimal.

用于匹配请求 URL 的通配符模式、正则表达式或谓词。HAR 文件只会提供 URL 与模式匹配的请求。如果未指定,则所有请求均由 HAR 文件提供服务。

¥A glob pattern, regular expression or predicate to match the request URL. Only requests with URL matching the pattern will be served from the HAR file. If not specified, all requests are served from the HAR file.

返回

¥Returns


serviceWorkers

Added in: v1.11 browserContext.serviceWorkers
注意

Service Worker 仅在基于 Chromium 的浏览器上受支持。

¥Service workers are only supported on Chromium-based browsers.

上下文中所有现有的 Service Worker。

¥All existing service workers in the context.

用法

¥Usage

browserContext.serviceWorkers();

返回

¥Returns


setDefaultNavigationTimeout

Added in: v1.8 browserContext.setDefaultNavigationTimeout

此设置将更改以下方法和相关快捷方式的默认最大导航时间:

¥This setting will change the default maximum navigation time for the following methods and related shortcuts:

用法

¥Usage

browserContext.setDefaultNavigationTimeout(timeout);

参数

¥Arguments

最大导航时间(以毫秒为单位)

¥Maximum navigation time in milliseconds


setDefaultTimeout

Added in: v1.8 browserContext.setDefaultTimeout

此设置将更改所有接受 timeout 选项的方法的默认最大时间。

¥This setting will change the default maximum time for all the methods accepting timeout option.

用法

¥Usage

browserContext.setDefaultTimeout(timeout);

参数

¥Arguments

最长时间(以毫秒为单位)

¥Maximum time in milliseconds


setExtraHTTPHeaders

Added in: v1.8 browserContext.setExtraHTTPHeaders

额外的 HTTP 标头将随上下文中任何页面发起的每个请求一起发送。这些标头与使用 page.setExtraHTTPHeaders() 设置的特定于页面的额外 HTTP 标头合并。如果页面覆盖特定标头,则将使用特定于页面的标头值而不是浏览器上下文标头值。

¥The extra HTTP headers will be sent with every request initiated by any page in the context. These headers are merged with page-specific extra HTTP headers set with page.setExtraHTTPHeaders(). If page overrides a particular header, page-specific header value will be used instead of the browser context header value.

注意

browserContext.setExtraHTTPHeaders() 不保证传出请求中标头的顺序。

¥browserContext.setExtraHTTPHeaders() does not guarantee the order of headers in the outgoing requests.

用法

¥Usage

await browserContext.setExtraHTTPHeaders(headers);

参数

¥Arguments

包含随每个请求发送的附加 HTTP 标头的对象。所有标头值都必须是字符串。

¥An object containing additional HTTP headers to be sent with every request. All header values must be strings.

返回

¥Returns


setGeolocation

Added in: v1.8 browserContext.setGeolocation

设置上下文的地理位置。通过 nullundefined 模拟位置不可用。

¥Sets the context's geolocation. Passing null or undefined emulates position unavailable.

用法

¥Usage

await browserContext.setGeolocation({ latitude: 59.95, longitude: 30.31667 });
注意

考虑使用 browserContext.grantPermissions() 授予浏览器上下文页面读取其地理位置的权限。

¥Consider using browserContext.grantPermissions() to grant permissions for the browser context pages to read its geolocation.

参数

¥Arguments

纬度在 -90 到 90 之间。

¥Latitude between -90 and 90.

经度在 -180 到 180 之间。

¥Longitude between -180 and 180.

非负精度值。默认为 0

¥Non-negative accuracy value. Defaults to 0.

返回

¥Returns


setOffline

Added in: v1.8 browserContext.setOffline

用法

¥Usage

await browserContext.setOffline(offline);

参数

¥Arguments

是否为浏览器上下文模拟网络离线。

¥Whether to emulate network being offline for the browser context.

返回

¥Returns


storageState

Added in: v1.8 browserContext.storageState

返回此浏览器上下文的存储状态,包含当前的 cookie 和本地存储快照。

¥Returns storage state for this browser context, contains current cookies and local storage snapshot.

用法

¥Usage

await browserContext.storageState();
await browserContext.storageState(options);

参数

¥Arguments

保存存储状态的文件路径。如果 path 是相对路径,则相对于当前工作目录进行解析。如果未提供路径,仍会返回存储状态,但不会保存到磁盘。

¥The file path to save the storage state to. If path is a relative path, then it is resolved relative to current working directory. If no path is provided, storage state is still returned, but won't be saved to the disk.

返回

¥Returns

Unix 时间以秒为单位。

¥Unix time in seconds.


unroute

Added in: v1.8 browserContext.unroute

删除使用 browserContext.route() 创建的路由。当不指定 handler 时,删除 url 的所有路由。

¥Removes a route created with browserContext.route(). When handler is not specified, removes all routes for the url.

用法

¥Usage

await browserContext.unroute(url);
await browserContext.unroute(url, handler);

参数

¥Arguments

接收 URL 的通配符模式、正则表达式模式或谓词,用于向 browserContext.route() 注册路由。

¥A glob pattern, regex pattern or predicate receiving URL used to register a routing with browserContext.route().

用于向 browserContext.route() 注册路由的可选处理程序函数。

¥Optional handler function used to register a routing with browserContext.route().

返回

¥Returns


unrouteAll

Added in: v1.41 browserContext.unrouteAll

删除使用 browserContext.route()browserContext.routeFromHAR() 创建的所有路由。

¥Removes all routes created with browserContext.route() and browserContext.routeFromHAR().

用法

¥Usage

await browserContext.unrouteAll();
await browserContext.unrouteAll(options);

参数

¥Arguments

  • behavior "wait"|"ignoreErrors"|"default"(可选)#

    ¥behavior "wait"|"ignoreErrors"|"default" (optional)#

    指定是否等待已经运行的处理程序以及如果它们抛出错误该怎么办:

    ¥Specifies wether to wait for already running handlers and what to do if they throw errors:

    • 'default' - 不要等待当前处理程序调用(如果有)完成,如果未路由的处理程序抛出,可能会导致未处理的错误

      ¥'default' - do not wait for current handler calls (if any) to finish, if unrouted handler throws, it may result in unhandled error

    • 'wait' - 等待当前处理程序调用(如果有)完成

      ¥'wait' - wait for current handler calls (if any) to finish

    • 'ignoreErrors' - 不等待当前处理程序调用(如果有)完成,取消路由后处理程序抛出的所有错误都会被静默捕获

      ¥'ignoreErrors' - do not wait for current handler calls (if any) to finish, all errors thrown by the handlers after unrouting are silently caught

返回

¥Returns


waitForEvent

Added in: v1.8 browserContext.waitForEvent

等待事件触发并将其值传递给谓词函数。当谓词返回真值时返回。如果上下文在事件触发之前关闭,则会抛出错误。返回事件数据值。

¥Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy value. Will throw an error if the context closes before the event is fired. Returns the event data value.

用法

¥Usage

const pagePromise = context.waitForEvent('page');
await page.getByRole('button').click();
const page = await pagePromise;

参数

¥Arguments

事件名称,相同的将传递到 browserContext.on(event)

¥Event name, same one would pass into browserContext.on(event).

接收事件数据并在等待解决时解析为真值。

¥Receives the event data and resolves to truthy value when the waiting should resolve.

等待的最长时间(以毫秒为单位)。默认为 0 - 没有超时。可以通过配置中的 actionTimeout 选项或使用 browserContext.setDefaultTimeout() 方法更改默认值。

¥Maximum time to wait for in milliseconds. Defaults to 0 - no timeout. The default value can be changed via actionTimeout option in the config, or by using the browserContext.setDefaultTimeout() method.

接收事件的谓词或选项对象。可选的。

¥Either a predicate that receives an event or an options object. Optional.

接收事件数据并在等待解决时解析为真值。

¥Receives the event data and resolves to truthy value when the waiting should resolve.

返回

¥Returns


属性

¥Properties

request

Added in: v1.16 browserContext.request

与此上下文关联的 API 测试助手。使用此 API 触发的请求将使用上下文 cookie。

¥API testing helper associated with this context. Requests made with this API will use context cookies.

用法

¥Usage

browserContext.request

类型

¥Type


tracing

Added in: v1.12 browserContext.tracing

用法

¥Usage

browserContext.tracing

类型

¥Type


事件

¥Events

on('backgroundpage')

Added in: v1.11 browserContext.on('backgroundpage')
注意

仅适用于 Chromium 浏览器的持久上下文。

¥Only works with Chromium browser's persistent context.

在上下文中创建新的背景页面时触发。

¥Emitted when new background page is created in the context.

const backgroundPage = await context.waitForEvent('backgroundpage');

用法

¥Usage

browserContext.on('backgroundpage', data => {});

事件数据

¥Event data


on('close')

Added in: v1.8 browserContext.on('close')

当浏览器上下文关闭时触发。发生这种情况可能是由于以下原因之一:

¥Emitted when Browser context gets closed. This might happen because of one of the following:

  • 浏览器上下文已关闭。

    ¥Browser context is closed.

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

    ¥Browser application is closed or crashed.

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

    ¥The browser.close() method was called.

用法

¥Usage

browserContext.on('close', data => {});

事件数据

¥Event data


on('console')

Added in: v1.34 browserContext.on('console')

当页面内的 JavaScript 调用控制台 API 方法之一时触发,例如 console.logconsole.dir

¥Emitted when JavaScript within the page calls one of console API methods, e.g. console.log or console.dir.

传递到 console.log 和页面的参数可在 ConsoleMessage 事件处理程序参数上使用。

¥The arguments passed into console.log and the page are available on the ConsoleMessage event handler argument.

用法

¥Usage

context.on('console', async msg => {
const values = [];
for (const arg of msg.args())
values.push(await arg.jsonValue());
console.log(...values);
});
await page.evaluate(() => console.log('hello', 5, { foo: 'bar' }));

事件数据

¥Event data


on('dialog')

Added in: v1.34 browserContext.on('dialog')

当 JavaScript 对话框出现时触发,例如 alertpromptconfirmbeforeunload。监听者必须选择 dialog.accept()dialog.dismiss() 对话 - 否则页面将 freeze 等待对话框,并且单击等操作将永远不会完成。

¥Emitted when a JavaScript dialog appears, such as alert, prompt, confirm or beforeunload. Listener must either dialog.accept() or dialog.dismiss() the dialog - otherwise the page will freeze waiting for the dialog, and actions like click will never finish.

用法

¥Usage

context.on('dialog', dialog => {
dialog.accept();
});
注意

当没有 page.on('dialog')browserContext.on('dialog') 监听器存在时,所有对话框都会自动关闭。

¥When no page.on('dialog') or browserContext.on('dialog') listeners are present, all dialogs are automatically dismissed.

事件数据

¥Event data


on('page')

Added in: v1.8 browserContext.on('page')

当在 BrowserContext 中创建新页面时会触发该事件。该页面可能仍在加载。该事件还将针对弹出页面触发。另请参阅 page.on('popup') 以接收有关与特定页面相关的弹出窗口的事件。

¥The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event will also fire for popup pages. See also page.on('popup') to receive events about popups relevant to a specific page.

该页面最早可用的时刻是导航到初始 URL 时。例如,当使用 window.open('http://example.com') 打开弹出窗口时,当对“http://example.com”的网络请求完成并且其响应已开始在弹出窗口中加载时,将触发此事件。

¥The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a popup with window.open('http://example.com'), this event will fire when the network request to "http://example.com" is done and its response has started loading in the popup.

const newPagePromise = context.waitForEvent('page');
await page.getByText('open new page').click();
const newPage = await newPagePromise;
console.log(await newPage.evaluate('location.href'));
注意

使用 page.waitForLoadState() 等待页面进入特定状态(在大多数情况下你不需要它)。

¥Use page.waitForLoadState() to wait until the page gets to a particular state (you should not need it in most cases).

用法

¥Usage

browserContext.on('page', data => {});

事件数据

¥Event data


on('request')

Added in: v1.12 browserContext.on('request')

当从通过此上下文创建的任何页面触发请求时触发。request 对象是只读的。要仅监听来自特定页面的请求,请使用 page.on('request')

¥Emitted when a request is issued from any pages created through this context. The request object is read-only. To only listen for requests from a particular page, use page.on('request').

为了拦截和改变请求,请参阅 browserContext.route()page.route()

¥In order to intercept and mutate requests, see browserContext.route() or page.route().

用法

¥Usage

browserContext.on('request', data => {});

事件数据

¥Event data


on('requestfailed')

Added in: v1.12 browserContext.on('requestfailed')

当请求失败时触发,例如超时。要仅监听来自特定页面的失败请求,请使用 page.on('requestfailed')

¥Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page, use page.on('requestfailed').

注意

从 HTTP 角度来看,HTTP 错误响应(例如 404 或 503)仍然是成功响应,因此请求将通过 browserContext.on('requestfinished') 事件完成,而不是通过 browserContext.on('requestfailed') 事件完成。

¥HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with browserContext.on('requestfinished') event and not with browserContext.on('requestfailed').

用法

¥Usage

browserContext.on('requestfailed', data => {});

事件数据

¥Event data


on('requestfinished')

Added in: v1.12 browserContext.on('requestfinished')

下载响应正文后请求成功完成时触发。对于成功响应,事件顺序为 requestresponserequestfinished。要监听来自特定页面的成功请求,请使用 page.on('requestfinished')

¥Emitted when a request finishes successfully after downloading the response body. For a successful response, the sequence of events is request, response and requestfinished. To listen for successful requests from a particular page, use page.on('requestfinished').

用法

¥Usage

browserContext.on('requestfinished', data => {});

事件数据

¥Event data


on('response')

Added in: v1.12 browserContext.on('response')

当收到请求的 response 状态和标头时触发。对于成功响应,事件顺序为 requestresponserequestfinished。要监听来自特定页面的响应事件,请使用 page.on('response')

¥Emitted when response status and headers are received for a request. For a successful response, the sequence of events is request, response and requestfinished. To listen for response events from a particular page, use page.on('response').

用法

¥Usage

browserContext.on('response', data => {});

事件数据

¥Event data


on('serviceworker')

Added in: v1.11 browserContext.on('serviceworker')
注意

Service Worker 仅在基于 Chromium 的浏览器上受支持。

¥Service workers are only supported on Chromium-based browsers.

在上下文中创建新的 Service Worker 时触发。

¥Emitted when new service worker is created in the context.

用法

¥Usage

browserContext.on('serviceworker', data => {});

事件数据

¥Event data


on('weberror')

Added in: v1.38 browserContext.on('weberror')

当此上下文中的任何页面中的异常未处理时触发。要监听特定页面的错误,请改用 page.on('pageerror')

¥Emitted when exception is unhandled in any of the pages in this context. To listen for errors from a particular page, use page.on('pageerror') instead.

用法

¥Usage

browserContext.on('weberror', data => {});

事件数据

¥Event data


已弃用

¥Deprecated

setHTTPCredentials

Added in: v1.8 browserContext.setHTTPCredentials
已弃用

身份验证成功后,浏览器可能会缓存凭据。相反,创建一个新的浏览器上下文。

¥Browsers may cache credentials after successful authentication. Create a new browser context instead.

用法

¥Usage

await browserContext.setHTTPCredentials(httpCredentials);

参数

¥Arguments

返回

¥Returns