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() 方法创建独立的非持久化浏览器上下文。非持久化浏览器上下文不会将任何浏览数据写入磁盘。

🌐 Playwright allows creating isolated non-persistent browser contexts with browser.newContext() method. Non-persistent 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 before v1.9 browserContext.addCookies

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

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

用法

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

参数

  • cookies Array<Object>#
    • name string

    • value string

    • url string (optional)

      需要 urldomainpath 两者。可选。

    • domain string (optional)

      为了让 cookie 也适用于所有子域,请在域名前加一个点,例如:“.example.com”。url 或者同时 domainpath 是必填项。可选。

    • path string (optional)

      需要 urldomainpath 两者。可选。

    • expires number (optional)

      Unix 时间(以秒为单位)。可选。

    • httpOnly boolean (optional)

      可选的。

    • secure boolean (optional)

      可选的。

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

      可选的。

    • partitionKey string (optional)

      对于分区的第三方 Cookie(也称为 CHIPS),分区键。可选。

返回


addInitScript

Added before v1.9 browserContext.addInitScript

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

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

  • 每当在浏览器上下文中创建页面或导航页面时。
  • 每当浏览器上下文中的任意页面附加或导航子框架时,在这种情况下,脚本会在新附加的框架上下文中执行。

脚本在文档创建后但在其任何脚本运行之前进行评估。这对于修改 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.

用法

在页面加载之前重写 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'
});
note

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

参数

  • script function | string | Object#

    • path string (optional)

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

    • content string (optional)

      原始脚本内容。可选。

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

  • arg Serializable (optional)#

    可选参数,用于传递给 脚本(仅在传递函数时支持)。

返回


browser

Added before v1.9 browserContext.browser

获取拥有该上下文的浏览器实例。如果上下文是在正常浏览器之外创建的,例如 Android 或 Electron,则返回 null

🌐 Gets the browser instance that owns the context. Returns null if the context is created outside of normal browser, e.g. Android or Electron.

用法

browserContext.browser();

返回


clearCookies

Added before v1.9 browserContext.clearCookies

从上下文中移除 cookies。可接受可选过滤器。

🌐 Removes cookies from context. Accepts optional filter.

用法

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' });

参数

  • options Object (optional)
    • domain string | RegExp (optional) Added in: v1.43#

      仅删除具有给定域的 cookie。

    • name string | RegExp (optional) Added in: v1.43#

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

    • path string | RegExp (optional) Added in: v1.43#

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

返回


clearPermissions

Added before v1.9 browserContext.clearPermissions

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

🌐 Clears all permission overrides for the browser context.

用法

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

返回


close

Added before v1.9 browserContext.close

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

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

note

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

🌐 The default browser context cannot be closed.

用法

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

参数

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

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

返回


cookies

Added before v1.9 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.

用法

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

参数

返回


exposeBinding

Added before v1.9 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.

用法

将页面 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();
})();

参数

  • name string#

    窗口对象上的函数名称。

  • callback function#

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

  • options Object (optional)

    • handle boolean (optional)#

      已弃用

      此选项将在未来被移除。

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

返回


exposeFunction

Added before v1.9 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.

用法

在上下文中向所有页面添加 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();
})();

参数

  • name string#

    窗口对象上的函数名称。

  • callback function#

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

返回


grantPermissions

Added before v1.9 browserContext.grantPermissions

授予浏览器上下文指定的权限。仅在指定时向给定来源授予相应的权限。

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

用法

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

参数

  • permissions Array<string>#

    要授予的权限列表。

    danger

    不同浏览器支持的权限各不相同,甚至同一浏览器的不同版本之间也有所差异。任何权限在更新后都可能停止工作。

    以下是某些浏览器可能支持的一些权限:

    • 'accelerometer'
    • 'ambient-light-sensor'
    • 'background-sync'
    • 'camera'
    • 'clipboard-read'
    • 'clipboard-write'
    • 'geolocation'
    • 'gyroscope'
    • 'local-fonts'
    • 'local-network-access'
    • 'magnetometer'
    • 'microphone'
    • 'midi-sysex'(系统专用MIDI)
    • 'midi'
    • 'notifications'
    • 'payment-handler'
    • 'storage-access'
  • options Object (optional)

返回


newCDPSession

Added in: v1.11 browserContext.newCDPSession
note

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

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

返回新创建的会话。

🌐 Returns the newly created session.

用法

await browserContext.newCDPSession(page);

参数

  • page Page | Frame#

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

返回


newPage

Added before v1.9 browserContext.newPage

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

🌐 Creates a new page in the browser context.

用法

await browserContext.newPage();

返回


pages

Added before v1.9 browserContext.pages

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

🌐 Returns all open pages in the context.

用法

browserContext.pages();

返回


removeAllListeners

Added in: v1.47 browserContext.removeAllListeners

移除指定类型的所有监听器(如果未指定类型,则移除所有注册的监听器)。允许等待异步监听器完成,或忽略这些监听器随后产生的错误。

🌐 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.

用法

await browserContext.removeAllListeners();
await browserContext.removeAllListeners(type, options);

参数

  • type string (optional)#
  • options Object (optional)
    • behavior "wait" | "ignoreErrors" | "default" (optional)#

      指定是否等待已经运行的监听器以及如果它们抛出错误该怎么做: =

      • 'default' - 不要等待当前监听器的调用(如果有)完成,如果监听器抛出异常,可能会导致未处理的错误
      • 'wait' - 等待当前监听器调用(如果有)完成
      • 'ignoreErrors' - 不要等待当前监听器的调用(如果有的话)完成,移除后监听器抛出的所有错误都会被静默捕获

返回


route

Added before v1.9 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.

note

browserContext.route() 不会拦截被 Service Worker 拦截的请求。请参见 此处 的问题。我们建议在使用请求拦截时禁用 Service Worker,通过将 serviceWorkers 设置为 'block'。:::

用法

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

🌐 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();

可以检查请求以决定路由操作。例如,模拟所有包含某些 POST 数据的请求,而将所有其他请求保持原样:

🌐 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().

note

启用路由会禁用 HTTP 缓存。

🌐 Enabling routing disables http cache.

参数

  • url string | RegExp | function(URL):boolean#

    一个通配符模式、正则表达式模式或谓词,用于在路由期间接收要匹配的 URL。如果在上下文选项中设置了 baseURL,并且提供的 URL 是一个不以 * 开头的字符串,则会使用 new URL() 构造函数进行解析。

  • handler function(Route, Request):Promise<Object> | Object#

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

  • options Object (optional)

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

      一个路由应该使用的频率。默认情况下,它将每次都被使用。

返回


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 不会处理从 HAR 文件中被 Service Worker 拦截的请求。请参见 此处 的问题。我们建议在使用请求拦截时禁用 Service Worker,通过将 serviceWorkers 设置为 'block' 来实现。

🌐 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 serviceWorkers to 'block'.

用法

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

参数

  • har string#

    指向包含预录网络数据的 HAR 文件的路径。如果 path 是相对路径,则相对于当前工作目录进行解析。

  • options Object (optional)

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

      • 如果设置为“中止”,任何在 HAR 文件中未找到的请求都将被中止。
      • 如果设置为“fallback”,将会传递到处理链中的下一个路由处理程序。

      默认为中止。

    • update boolean (optional)#

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

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

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

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

      当设置为 minimal 时,仅记录从 HAR 路由所需的信息。这会省略在从 HAR 回放时不使用的大小、时间、页面、Cookies、安全性以及其他类型的 HAR 信息。默认值为 minimal

    • url string | RegExp (optional)#

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

返回


routeWebSocket

Added in: v1.48 browserContext.routeWebSocket

此方法允许修改浏览器上下文中任何页面建立的 websocket 连接。

🌐 This method allows to modify websocket connections that are made by any page in the browser context.

请注意,只有在调用此方法后创建的 WebSocket 才会被路由。建议在创建任何页面之前调用此方法。

🌐 Note that only WebSockets created after this method was called will be routed. It is recommended to call this method before creating any pages.

用法

下面是一个简单处理程序的示例,它可以阻止某些 WebSocket 消息。有关更多详细信息和示例,请参见 WebSocketRoute

🌐 Below is an example of a simple handler that blocks some websocket messages. See WebSocketRoute for more details and examples.

await context.routeWebSocket('/ws', async ws => {
ws.routeSend(message => {
if (message === 'to-be-blocked')
return;
ws.send(message);
});
await ws.connect();
});

参数

返回


serviceWorkers

Added in: v1.11 browserContext.serviceWorkers
note

服务工作者仅在基于 Chromium 的浏览器上受支持。

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

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

🌐 All existing service workers in the context.

用法

browserContext.serviceWorkers();

返回


setDefaultNavigationTimeout

Added before v1.9 browserContext.setDefaultNavigationTimeout

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

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

用法

browserContext.setDefaultNavigationTimeout(timeout);

参数

  • timeout number#

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


setDefaultTimeout

Added before v1.9 browserContext.setDefaultTimeout

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

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

用法

browserContext.setDefaultTimeout(timeout);

参数

  • timeout number#

    最大时间(毫秒)。传入 0 可禁用超时。


setExtraHTTPHeaders

Added before v1.9 browserContext.setExtraHTTPHeaders

额外的 HTTP 头会随着上下文中任何页面发起的每个请求一起发送。这些头部与页面特定的额外HTTP头合并,设置为[page.setExtraHTTPHeaders()](/api/class-page.mdx#page-set-extra-http-headers)。如果页面覆盖了某个特定头部,则会使用页面特定的头值代替浏览器上下文的头值。

🌐 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.

note

browserContext.setExtraHTTPHeaders() 并不能保证发送请求时请求头的顺序。

用法

await browserContext.setExtraHTTPHeaders(headers);

参数

  • headers Object<string, string>#

    一个包含要随每个请求发送的额外 HTTP 头的对象。所有头的值都必须是字符串。

返回


setGeolocation

Added before v1.9browserContext.setGeolocation

设置上下文的地理位置。传入 nullundefined 会模拟位置不可用。

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

用法

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

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

参数

  • geolocation null | Object#
    • latitude number

      纬度在 -90 到 90 之间。

    • longitude number

      经度在 -180 到 180 之间。

    • accuracy number (optional)

      非负精度值。默认值为 0

返回


setOffline

Added before v1.9 browserContext.setOffline

用法

await browserContext.setOffline(offline);

参数

  • offline boolean#

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

返回


storageState

Added before v1.9 browserContext.storageState

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

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

用法

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

参数

  • options Object (optional)
    • indexedDB boolean (optional) Added in: v1.51#

      设置为 true 以在存储状态快照中包含 IndexedDB。如果你的应用使用 IndexedDB 来存储身份验证令牌,例如 Firebase 身份验证,请启用此选项。

    • path string (optional)#

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

返回


unroute

Added before v1.9 browserContext.unroute

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

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

用法

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

参数

返回


unrouteAll

Added in: v1.41 browserContext.unrouteAll

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

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

用法

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

参数

  • options Object (optional)
    • behavior "wait" | "ignoreErrors" | "default" (optional)#

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

      • 'default' - 不要等待当前处理程序调用(如果有)完成,如果未路由的处理程序抛出异常,可能会导致未处理的错误
      • 'wait' - 等待当前处理程序的调用(如果有)完成
      • 'ignoreErrors' - 不要等待当前处理程序的调用(如果有)完成,在取消路由后,处理程序抛出的所有错误都会被静默捕获

返回


waitForEvent

Added before v1.9 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.

用法

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

参数

  • event string#

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

  • optionsOrPredicate function | Object (optional)#

    • predicate function

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

    • timeout number (optional)

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

    可以是接收事件的谓词,也可以是一个选项对象。可选。

  • options Object (optional)

    • predicate function (optional)#

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

返回


属性

🌐 Properties

clock

Added in: v1.45 browserContext.clock

Playwright 能够模拟时钟和时间的流逝。

🌐 Playwright has ability to mock clock and passage of time.

用法

browserContext.clock

类型


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.

用法

browserContext.request

类型


tracing

Added in: v1.12 browserContext.tracing

用法

browserContext.tracing

类型


事件

🌐 Events

on('close')

Added before v1.9 browserContext.on('close')

当浏览器上下文被关闭时触发。这可能是以下原因之一导致的:

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

  • 浏览器上下文已关闭。
  • 浏览器应用已关闭或崩溃。
  • 已调用 browser.close() 方法。

用法

browserContext.on('close', 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.

用法

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' }));

事件数据


on('dialog')

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

当出现 JavaScript 对话框时触发,例如 alertpromptconfirmbeforeunload。监听器必须要么 dialog.accept(),要么 dialog.dismiss() 对话框——否则页面会冻结等待对话框,像点击这样的操作将永远无法完成。

🌐 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.

用法

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

当没有 [page.on('dialog')]](/api/class-page.mdx#page-event-dialog) 或 [browserContext.on('dialog')](/api/class-browsercontext.mdx#browser-context-event-dialog) 监听者时,所有对话都会自动被关闭。

事件数据


on('page')

Added before v1.9 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" 完成并且其响应开始在弹出窗口中加载时,将触发此事件。如果你想要路由/监听此网络请求,请使用 browserContext.route()browserContext.on('request') 分别,而不是在 Page 上使用类似的方法。

🌐 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. If you would like to route/listen to this network request, use browserContext.route() and browserContext.on('request') respectively instead of similar methods on the Page.

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

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

用法

browserContext.on('page', 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().

用法

browserContext.on('request', 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').

note

从 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').

用法

browserContext.on('requestfailed', 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').

用法

browserContext.on('requestfinished', 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').

用法

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

事件数据


on('serviceworker')

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

服务工作者仅在基于 Chromium 的浏览器上受支持。

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

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

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

用法

browserContext.on('serviceworker', 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.

用法

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

事件数据


已弃用

🌐 Deprecated

on('backgroundpage')

Added in: v1.11 browserContext.on('backgroundpage')
已弃用

后台页面已从 Chromium 中移除,同时 Manifest V2 扩展也已移除。

🌐 Background pages have been removed from Chromium together with Manifest V2 extensions.

此事件不会触发。

🌐 This event is not emitted.

用法

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

事件数据


backgroundPages

Added in: v1.11 browserContext.backgroundPages
已弃用

后台页面已从 Chromium 中移除,同时 Manifest V2 扩展也已移除。

🌐 Background pages have been removed from Chromium together with Manifest V2 extensions.

返回一个空列表。

🌐 Returns an empty list.

用法

browserContext.backgroundPages();

返回


setHTTPCredentials

Added before v1.9 browserContext.setHTTPCredentials
已弃用

浏览器在成功认证后可能会缓存凭据。请改为创建一个新的浏览器上下文。

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

用法

await browserContext.setHTTPCredentials(httpCredentials);

参数

返回