newPage([options])
如果尚未为 浏览器 初始化 BrowserContext
,则在新的 BrowserContext 中创建并返回一个新的 Page。如果 BrowserContext
已初始化,则会抛出错误。
注意
Browser 和
BrowserContext
之间是一一映射关系,这意味着您无法并发运行多个BrowserContext
。由于此限制,如果已存在一个BrowserContext
,则必须先 获取 并 关闭 它,然后才能创建新的。
注意
已打开的页面应该使用
Page.close
关闭。未关闭的页面可能会扭曲 Web Vital 指标的结果。
参数 | 类型 | 默认值 | 描述 |
---|---|---|---|
options | object | null | |
options.bypassCSP | boolean | false | 是否绕过页面的 Content-Security-Policy。 |
options.colorScheme | string | 'light' | 通过模拟“prefers-colors-scheme”媒体特性,是否以暗模式或亮模式显示页面。可以是 'light' 、'dark' 或 'no-preference' 之一。 |
options.deviceScaleFactor | number | 1 | 设置物理像素分辨率与 CSS 像素分辨率的比率,例如,如果设置为高于 1 ,则在高像素密度屏幕上的图像会更清晰。请参阅下面的示例。 |
options.extraHTTPHeaders | object | null | 包含随每个请求发送的附加 HTTP 头部,其中键是 HTTP 头部名称,值是 HTTP 头部值。 |
options.geolocation | object | null | 设置用户的地理位置。 |
options.geolocation.latitude | number | 0 | 纬度应在 -90 到 90 之间。 |
options.geolocation.longitude | number | 0 | 经度应在 -180 到 180 之间。 |
options.geolocation.accuracy | number | 0 | 精度应为非负数。默认为 0 。 |
options.hasTouch | boolean | false | 是否模拟带有触摸事件的设备。 |
options.httpCredentials | object | null | 设置使用基本认证 (Basic Auth) 进行 HTTP 认证的凭据。 |
options.httpCredentials.username | string | '' | 要传递给网络浏览器进行基本 HTTP 认证的用户名。 |
options.httpCredentials.password | string | '' | 要传递给网络浏览器进行基本 HTTP 认证的密码。 |
options.ignoreHTTPSErrors | boolean | false | 是否忽略由无效证书引起的 HTTPS 错误。 |
options.isMobile | boolean | false | 是否模拟移动设备。 |
options.javaScriptEnabled | boolean | true | 是否为上下文激活 JavaScript 支持。 |
options.locale | string | system | 指定用户的区域设置,例如 'en-US' 、'tr-TR' 等。 |
options.offline | boolean | false | 是否模拟离线网络。 |
options.permissions | Array | null | 要授予上下文页面的权限。有关选项,请参见 browserContext.grantPermissions()。 |
options.reducedMotion | string | 'no-preference' | 通过模拟“prefers-reduced-motion”媒体特性,最大限度地减少运动量。可以是 'reduce' 和 'no-preference' 之一。有关选项,请参见 page.emulateMedia()。 |
options.screen | object | {'width': 1280, 'height': 720} | 为上下文中的所有页面设置窗口屏幕大小。仅当设置了视口时才能使用。 |
options.screen.width | number | 1280 | 页面的像素宽度。 |
options.screen.height | number | 720 | 页面的像素高度。 |
options.timezoneID | string | system | 更改上下文的时区。有关支持的时区 ID 列表,请参见 ICU 的 metaZones.txt。 |
options.userAgent | string | browser | 指定要在上下文中使用的用户代理。 |
options.viewport | object | {'width': 1280, 'height': 720} | 为上下文中的所有页面设置视口大小。null 会禁用默认视口。 |
options.viewport.width | number | 1280 | 页面的像素宽度。 |
options.viewport.height | number | 720 | 页面的像素高度。 |
返回值
类型 | 描述 |
---|---|
Promise<Page> | 一个 Promise,解析后包含一个 Page 对象。 |
deviceScaleFactor 示例
import { browser } from 'k6/browser';
export const options = {
scenarios: {
browser: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};
export default async function () {
const page = await browser.newPage({
viewport: {
width: 375,
height: 812,
},
deviceScaleFactor: 3,
});
try {
await page.goto('https://test.k6.io/');
} finally {
await page.close();
}
}