菜单
开源

context()

返回当前的 BrowserContext

注意

BrowserBrowserContext 之间是一对一映射,这意味着您不能并行运行 BrowserContexts。如果您想在已存在一个 BrowserContext 的情况下创建一个新的 BrowserContext,您需要 关闭 当前的 BrowserContext,然后使用 newContextnewPage 创建一个新的。与已关闭 BrowserContext 相关联的所有资源(例如 Page)也将被关闭和清理。

返回

类型描述
object | null如果已创建 BrowserContext,则返回当前的 BrowserContext,否则返回 null

示例

JavaScript
import { browser } from 'k6/browser';

export const options = {
  scenarios: {
    browser: {
      executor: 'shared-iterations',
      options: {
        browser: {
          type: 'chromium',
        },
      },
    },
  },
};

export default async function () {
  console.log(browser.context()); // null

  const page1 = await browser.newPage(); // implicitly creates a new browserContext
  const context = browser.context(); // underlying live browserContext associated with browser
  const page2 = await context.newPage(); // shares the browserContext with page1

  page1.close();
  page2.close();
  await context.close();
}