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

🌐 Playwright allows creating isolated non-persistent browser contexts with Browser.NewContextAsync() method. Non-persistent browser contexts don't write any browsing data to disk.

using var playwright = await Playwright.CreateAsync();
var browser = await playwright.Firefox.LaunchAsync(new() { Headless = false });
// Create a new incognito browser context
var context = await browser.NewContextAsync();
// Create a new page inside context.
var page = await context.NewPageAsync();
await page.GotoAsync("https://bing.com");
// Dispose context once it is no longer needed.
await context.CloseAsync();

方法

🌐 Methods

AddCookiesAsync

Added before v1.9 browserContext.AddCookiesAsync

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

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

用法

await context.AddCookiesAsync(new[] { cookie1, cookie2 });

参数

  • cookies IEnumerable<Cookie>#
    • Name string

    • Value string

    • Url string? (optional)

      需要 urldomainpath 两者。可选。

    • Domain string? (optional)

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

    • Path string? (optional)

      需要 urldomainpath 两者。可选。

    • Expires [float]? (optional)

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

    • HttpOnly bool? (optional)

      可选的。

    • Secure bool? (optional)

      可选的。

    • SameSite enum SameSiteAttribute { Strict, Lax, None }? (optional)

      可选的。

    • PartitionKey string? (optional)

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

返回


AddInitScriptAsync

Added before v1.9 browserContext.AddInitScriptAsync

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

🌐 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;
await Context.AddInitScriptAsync(scriptPath: "preload.js");
note

通过 BrowserContext.AddInitScriptAsync()Page.AddInitScriptAsync() 安装的多个脚本的执行顺序未定义。

参数

  • script string | string#

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

返回


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

返回


ClearCookiesAsync

Added before v1.9 browserContext.ClearCookiesAsync

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

🌐 Removes cookies from context. Accepts optional filter.

用法

await context.ClearCookiesAsync();
await context.ClearCookiesAsync(new() { Name = "session-id" });
await context.ClearCookiesAsync(new() { Domain = "my-origin.com" });
await context.ClearCookiesAsync(new() { Path = "/api/v1" });
await context.ClearCookiesAsync(new() { Name = "session-id", Domain = "my-origin.com" });

参数

  • options BrowserContextClearCookiesOptions? (optional)
    • Domain|DomainRegex string? | Regex? (optional) Added in: v1.43#

      仅删除具有给定域的 cookie。

    • Name|NameRegex string? | Regex? (optional) Added in: v1.43#

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

    • Path|PathRegex string? | Regex? (optional) Added in: v1.43#

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

返回


ClearPermissionsAsync

Added before v1.9 browserContext.ClearPermissionsAsync

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

🌐 Clears all permission overrides for the browser context.

用法

var context = await browser.NewContextAsync();
await context.GrantPermissionsAsync(new[] { "clipboard-read" });
// Alternatively, you can use the helper class ContextPermissions
// to specify the permissions...
// do stuff ...
await context.ClearPermissionsAsync();

返回


CloseAsync

Added before v1.9 browserContext.CloseAsync

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

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

参数

  • options BrowserContextCloseOptions? (optional)
    • Reason string? (optional) Added in: v1.40#

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

返回


CookiesAsync

Added before v1.9 browserContext.CookiesAsync

如果未指定 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.CookiesAsync(urls);

参数

返回


ExposeBindingAsync

Added before v1.9 browserContext.ExposeBindingAsync

该方法在上下文中每个页面的每一帧的 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.ExposeBindingAsync() 获取仅页面的版本。

🌐 See Page.ExposeBindingAsync() for page-only version.

用法

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

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

using Microsoft.Playwright;

using var playwright = await Playwright.CreateAsync();
var browser = await playwright.Webkit.LaunchAsync(new() { Headless = false });
var context = await browser.NewContextAsync();

await context.ExposeBindingAsync("pageURL", source => source.Page.Url);
var page = await context.NewPageAsync();
await page.SetContentAsync("<script>\n" +
" async function onClick() {\n" +
" document.querySelector('div').textContent = await window.pageURL();\n" +
" }\n" +
"</script>\n" +
"<button onclick=\"onClick()\">Click me</button>\n" +
"<div></div>");
await page.GetByRole(AriaRole.Button).ClickAsync();

参数

  • name string#

    窗口对象上的函数名称。

  • callback Action<BindingSource, T, [TResult]>#

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

  • options BrowserContextExposeBindingOptions? (optional)

    • Handle bool? (optional)#

      已弃用

      此选项将在未来被移除。

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

返回


ExposeFunctionAsync

Added before v1.9 browserContext.ExposeFunctionAsync

该方法在上下文中每个页面的每一帧的 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.ExposeFunctionAsync() 获取仅页面的版本。

🌐 See Page.ExposeFunctionAsync() for page-only version.

用法

在上下文中向所有页面添加 sha256 函数的示例:

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

using Microsoft.Playwright;
using System;
using System.Security.Cryptography;
using System.Threading.Tasks;

class BrowserContextExamples
{
public static async Task Main()
{
using var playwright = await Playwright.CreateAsync();
var browser = await playwright.Webkit.LaunchAsync(new() { Headless = false });
var context = await browser.NewContextAsync();

await context.ExposeFunctionAsync("sha256", (string input) =>
{
return Convert.ToBase64String(
SHA256.Create().ComputeHash(System.Text.Encoding.UTF8.GetBytes(input)));
});

var page = await context.NewPageAsync();
await page.SetContentAsync("<script>\n" +
" async function onClick() {\n" +
" document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');\n" +
" }\n" +
"</script>\n" +
"<button onclick=\"onClick()\">Click me</button>\n" +
"<div></div>");

await page.GetByRole(AriaRole.Button).ClickAsync();
Console.WriteLine(await page.TextContentAsync("div"));
}
}

参数

  • name string#

    窗口对象上的函数名称。

  • callback Action<T, [TResult]>#

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

返回


GrantPermissionsAsync

Added before v1.9 browserContext.GrantPermissionsAsync

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

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

用法

await BrowserContext.GrantPermissionsAsync(permissions, options);

参数

  • permissions IEnumerable<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 BrowserContextGrantPermissionsOptions? (optional)

返回


NewCDPSessionAsync

Added in: v1.11 browserContext.NewCDPSessionAsync
note

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

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

返回新创建的会话。

🌐 Returns the newly created session.

用法

await BrowserContext.NewCDPSessionAsync(page);

参数

  • page Page | Frame#

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

返回


NewPageAsync

Added before v1.9 browserContext.NewPageAsync

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

🌐 Creates a new page in the browser context.

用法

await BrowserContext.NewPageAsync();

返回


Pages

Added before v1.9 browserContext.Pages

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

🌐 Returns all open pages in the context.

用法

BrowserContext.Pages

返回


RouteAsync

Added before v1.9 browserContext.RouteAsync

路由功能提供了修改浏览器上下文中任何页面发出的网络请求的能力。一旦启用路由,每个匹配 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.RouteAsync() 不会拦截由 Service Worker 拦截的请求。请参见 此处 的问题。我们建议在使用请求拦截时禁用 Service Workers,可以通过将 ServiceWorkers 设置为 'block' 来实现。

用法

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

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

var context = await browser.NewContextAsync();
var page = await context.NewPageAsync();
await context.RouteAsync("**/*.{png,jpg,jpeg}", r => r.AbortAsync());
await page.GotoAsync("https://theverge.com");
await browser.CloseAsync();

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

🌐 or the same snippet using a regex pattern instead:

var context = await browser.NewContextAsync();
var page = await context.NewPageAsync();
await context.RouteAsync(new Regex("(\\.png$)|(\\.jpg$)"), r => r.AbortAsync());
await page.GotoAsync("https://theverge.com");
await browser.CloseAsync();

可以检查请求以决定路由操作。例如,模拟所有包含某些 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 page.RouteAsync("/api/**", async r =>
{
if (r.Request.PostData.Contains("my-string"))
await r.FulfillAsync(new() { Body = "mocked-data" });
else
await r.ContinueAsync();
});

页面路由(通过 Page.RouteAsync() 设置)在请求同时匹配两个处理程序时优先于浏览器上下文路由。

🌐 Page routes (set up with Page.RouteAsync()) take precedence over browser context routes when request matches both handlers.

要移除带有其处理程序的路由,你可以使用 BrowserContext.UnrouteAsync()

🌐 To remove a route with its handler you can use BrowserContext.UnrouteAsync().

note

启用路由会禁用 HTTP 缓存。

🌐 Enabling routing disables http cache.

参数

  • url string | Regex | Func<string, bool>#

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

  • handler Action<Route>#

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

  • options BrowserContextRouteOptions? (optional)

    • Times int? (optional) Added in: v1.15#

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

返回


RouteFromHARAsync

Added in: v1.23 browserContext.RouteFromHARAsync

如果指定,所做的网络请求将在上下文中从 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 文件中被服务工作者拦截的请求。请参见此处问题。我们建议在使用请求拦截时禁用服务工作者,通过将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.RouteFromHARAsync(har, options);

参数

  • har string#

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

  • options BrowserContextRouteFromHAROptions? (optional)

    • NotFound enum HarNotFound { Abort, Fallback }? (optional)#

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

      默认为中止。

    • Update bool? (optional)#

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

    • UpdateContent enum RouteFromHarUpdateContentPolicy { Embed, Attach }? (optional) Added in: v1.32#

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

    • UpdateMode enum HarMode { Full, Minimal }? (optional) Added in: v1.32#

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

    • Url|UrlRegex string? | Regex? (optional)#

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

返回


RouteWebSocketAsync

Added in: v1.48 browserContext.RouteWebSocketAsync

此方法允许修改浏览器上下文中任何页面建立的 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.RouteWebSocketAsync("/ws", async ws => {
ws.RouteSend(message => {
if (message == "to-be-blocked")
return;
ws.Send(message);
});
await ws.ConnectAsync();
});

参数

返回


RunAndWaitForConsoleMessageAsync

Added in: v1.34 browserContext.RunAndWaitForConsoleMessageAsync

执行操作并等待在上下文中的页面记录 ConsoleMessage。如果提供了谓词,它会将 ConsoleMessage 值传入 predicate 函数,并等待 predicate(message) 返回一个真值。如果页面在触发 BrowserContext.Console 事件之前被关闭,将抛出错误。

🌐 Performs action and waits for a ConsoleMessage to be logged by in the pages in the context. If predicate is provided, it passes ConsoleMessage value into the predicate function and waits for predicate(message) to return a truthy value. Will throw an error if the page is closed before the BrowserContext.Console event is fired.

用法

await BrowserContext.RunAndWaitForConsoleMessageAsync(action, options);

参数

  • action Func<Task>#

    触发事件的操作。

  • options BrowserContextRunAndWaitForConsoleMessageOptions? (optional)

返回


WaitForConsoleMessageAsync

Added in: v1.34 browserContext.WaitForConsoleMessageAsync

执行操作并等待在上下文中的页面记录 ConsoleMessage。如果提供了谓词,它会将 ConsoleMessage 值传入 predicate 函数,并等待 predicate(message) 返回一个真值。如果页面在触发 BrowserContext.Console 事件之前被关闭,将抛出错误。

🌐 Performs action and waits for a ConsoleMessage to be logged by in the pages in the context. If predicate is provided, it passes ConsoleMessage value into the predicate function and waits for predicate(message) to return a truthy value. Will throw an error if the page is closed before the BrowserContext.Console event is fired.

用法

await BrowserContext.WaitForConsoleMessageAsync(action, options);

参数

  • options BrowserContextRunAndWaitForConsoleMessageOptions? (optional)

返回


RunAndWaitForPageAsync

Added in: v1.9 browserContext.RunAndWaitForPageAsync

执行操作并等待在上下文中创建新的 Page。如果提供了谓词,将把 Page 值传入 predicate 函数,并等待 predicate(event) 返回一个真值。如果在创建新 Page 之前上下文关闭,将会抛出错误。

🌐 Performs action and waits for a new Page to be created in the context. If predicate is provided, it passes Page value into the predicate function and waits for predicate(event) to return a truthy value. Will throw an error if the context closes before new Page is created.

用法

await BrowserContext.RunAndWaitForPageAsync(action, options);

参数

  • action Func<Task> Added in: v1.12#

    触发事件的操作。

  • options BrowserContextRunAndWaitForPageOptions? (optional)

    • Predicate Func<Page?, bool> (optional)#

      接收 Page 对象,并在等待条件应该满足时解析为真值。

    • Timeout [float]? (optional)#

      等待的最长时间(以毫秒为单位)。默认为 30000(30 秒)。传入 0 可禁用超时。可以使用 BrowserContext.SetDefaultTimeout() 来更改默认值。

返回


WaitForPageAsync

Added in: v1.9 browserContext.WaitForPageAsync

执行操作并等待在上下文中创建新的 Page。如果提供了谓词,将把 Page 值传入 predicate 函数,并等待 predicate(event) 返回一个真值。如果在创建新 Page 之前上下文关闭,将会抛出错误。

🌐 Performs action and waits for a new Page to be created in the context. If predicate is provided, it passes Page value into the predicate function and waits for predicate(event) to return a truthy value. Will throw an error if the context closes before new Page is created.

用法

await BrowserContext.WaitForPageAsync(action, options);

参数

  • options BrowserContextRunAndWaitForPageOptions? (optional)
    • Predicate Func<Page?, bool> (optional)#

      接收 Page 对象,并在等待条件应该满足时解析为真值。

    • Timeout [float]? (optional)#

      等待的最长时间(以毫秒为单位)。默认为 30000(30 秒)。传入 0 可禁用超时。可以使用 BrowserContext.SetDefaultTimeout() 来更改默认值。

返回


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 [float]#

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


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 [float]#

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


SetExtraHTTPHeadersAsync

Added before v1.9 browserContext.SetExtraHTTPHeadersAsync

额外的 HTTP 头将随上下文中任何页面发起的每个请求一起发送。这些头会与使用 Page.SetExtraHTTPHeadersAsync() 设置的页面特定的额外 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.SetExtraHTTPHeadersAsync(). If page overrides a particular header, page-specific header value will be used instead of the browser context header value.

note

BrowserContext.SetExtraHTTPHeadersAsync() 并不保证发送请求中头部的顺序。:::

用法

await BrowserContext.SetExtraHTTPHeadersAsync(headers);

参数

  • headers IDictionary<string, string>#

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

返回


SetGeolocationAsync

Added before v1.9browserContext.SetGeolocationAsync

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

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

用法

await context.SetGeolocationAsync(new Geolocation()
{
Latitude = 59.95f,
Longitude = 30.31667f
});
note

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

参数

  • geolocation Geolocation?#
    • Latitude [float]

      纬度在 -90 到 90 之间。

    • Longitude [float]

      经度在 -180 到 180 之间。

    • Accuracy [float]? (optional)

      非负精度值。默认值为 0

返回


SetOfflineAsync

Added before v1.9 browserContext.SetOfflineAsync

用法

await BrowserContext.SetOfflineAsync(offline);

参数

  • offline bool#

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

返回


StorageStateAsync

Added before v1.9 browserContext.StorageStateAsync

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

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

用法

await BrowserContext.StorageStateAsync(options);

参数

  • options BrowserContextStorageStateOptions? (optional)
    • IndexedDB bool? (optional) Added in: v1.51#

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

    • Path string? (optional)#

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

返回


UnrouteAsync

Added before v1.9 browserContext.UnrouteAsync

移除使用 BrowserContext.RouteAsync() 创建的路由。当未指定 handler 时,将移除 url 的所有路由。

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

用法

await BrowserContext.UnrouteAsync(url, handler);

参数

返回


UnrouteAllAsync

Added in: v1.41 browserContext.UnrouteAllAsync

移除所有使用 BrowserContext.RouteAsync()BrowserContext.RouteFromHARAsync() 创建的路由。

🌐 Removes all routes created with BrowserContext.RouteAsync() and BrowserContext.RouteFromHARAsync().

用法

await BrowserContext.UnrouteAllAsync(options);

参数

  • options BrowserContextUnrouteAllOptions? (optional)
    • Behavior enum UnrouteBehavior { Wait, IgnoreErrors, Default }? (optional)#

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

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

返回


属性

🌐 Properties

APIRequest

Added in: v1.16 browserContext.APIRequest

与此上下文相关的 API 测试助手。使用此 API 发出的请求将使用上下文 Cookie。

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

用法

BrowserContext.APIRequest

类型


Clock

Added in: v1.45 browserContext.Clock

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

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

用法

BrowserContext.Clock

类型


Tracing

Added in: v1.12 browserContext.Tracing

用法

BrowserContext.Tracing

类型


事件

🌐 Events

event Close

Added before v1.9 browserContext.event Close

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

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

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

用法

BrowserContext.Close += async (_, browserContext) => {};

事件数据


event Console

Added in: v1.34 browserContext.event 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.Console += async (_, msg) =>
{
foreach (var arg in msg.Args)
Console.WriteLine(await arg.JsonValueAsync<object>());
};

await page.EvaluateAsync("console.log('hello', 5, { foo: 'bar' })");

事件数据


event Dialog

Added in: v1.34 browserContext.event Dialog

当 JavaScript 对话框出现时触发,例如 alertpromptconfirmbeforeunload。监听器必须调用 Dialog.AcceptAsync()Dialog.DismissAsync() 来处理对话框,否则页面将会冻结等待对话框,点击等操作将永远无法完成。

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

用法

Context.Dialog += async (_, dialog) =>
{
await dialog.AcceptAsync();
};
note

当没有 Page.DialogBrowserContext.Dialog 监听器时,所有对话框会自动被关闭。

事件数据


event Page

Added before v1.9 browserContext.event Page

当在 BrowserContext 中创建新页面时,会触发该事件。页面可能仍在加载中。弹出页面也会触发此事件。另请参见 Page.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.Popup to receive events about popups relevant to a specific page.

该页面最早可用的时刻是它已导航到初始 URL 的时候。例如,当使用 window.open('http://example.com') 打开一个弹出窗口时,当对 "http://example.com" 的网络请求完成并且响应开始在弹出窗口中加载时,此事件将触发。如果你想对该网络请求进行路由或监听,请分别使用 BrowserContext.RouteAsync()BrowserContext.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.RouteAsync() and BrowserContext.Request respectively instead of similar methods on the Page.

var popup = await context.RunAndWaitForPageAsync(async =>
{
await page.GetByText("open new page").ClickAsync();
});
Console.WriteLine(await popup.EvaluateAsync<string>("location.href"));
note

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

用法

BrowserContext.Page += async (_, page) => {};

事件数据


event Request

Added in: v1.12 browserContext.event Request

当从通过此上下文创建的任何页面发出请求时触发。 request 对象是只读的。要仅监听来自特定页面的请求,请使用 Page.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.Request.

为了拦截和修改请求,请参阅 BrowserContext.RouteAsync()Page.RouteAsync()

🌐 In order to intercept and mutate requests, see BrowserContext.RouteAsync() or Page.RouteAsync().

用法

BrowserContext.Request += async (_, request) => {};

事件数据


event RequestFailed

Added in: v1.12 browserContext.event RequestFailed

当请求失败时触发,例如超时。要仅监听来自特定页面的失败请求,请使用 Page.RequestFailed

🌐 Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page, use Page.RequestFailed.

note

HTTP 错误响应,例如 404 或 503,从 HTTP 的角度来看仍然是成功响应,因此请求将通过 BrowserContext.RequestFinished 事件完成,而不是通过 BrowserContext.RequestFailed 完成。

🌐 HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with BrowserContext.RequestFinished event and not with BrowserContext.RequestFailed.

用法

BrowserContext.RequestFailed += async (_, request) => {};

事件数据


event RequestFinished

Added in: v1.12 browserContext.event RequestFinished

当请求在下载响应主体后成功完成时触发。对于成功的响应,事件的顺序是 requestresponserequestfinished。要监听来自特定页面的成功请求,请使用 Page.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.RequestFinished.

用法

BrowserContext.RequestFinished += async (_, request) => {};

事件数据


event Response

Added in: v1.12 browserContext.event Response

当接收到请求的response状态和头信息时触发。对于成功的响应,事件的顺序是 requestresponserequestfinished。要监听来自特定页面的响应事件,请使用 Page.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.Response.

用法

BrowserContext.Response += async (_, response) => {};

事件数据


event WebError

Added in: v1.38 browserContext.event WebError

当此上下文中的任意页面出现未处理的异常时会触发此事件。若要监听特定页面的错误,请改用 Page.PageError

🌐 Emitted when exception is unhandled in any of the pages in this context. To listen for errors from a particular page, use Page.PageError instead.

用法

BrowserContext.WebError += async (_, webError) => {};

事件数据


已弃用

🌐 Deprecated

event BackgroundPage

Added in: v1.11 browserContext.event BackgroundPage
已弃用

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

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

此事件不会触发。

🌐 This event is not emitted.

用法

BrowserContext.BackgroundPage += async (_, page) => {};

事件数据


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

返回