sitespeed.io 脚本教程:用 Cookie 与 Consent 横幅处理保证性能测量数据纯净

原创2026-10-13 13:57:441,976 阅读
文章标签:测试性能剖析指标监控

sitespeed.io 脚本教程:用 Cookie 与 Consent 横幅处理保证性能测量数据纯净

sitespeed.io 的脚本(Scripting)能力让你在测量真实浏览器导航时,先于页面加载注入、读取或删除 Cookie。本指南围绕Cookies and consent banners教程,讲解 Cookie API 的完整用法,以及"先丢弃同意横幅再测量"的三种经典模式:注入 Cookie、点击横幅、用 --preScript 只做一次。读完你可以在自己的站点上直接复制脚本,让 GDPR 同意横幅不再污染 First Visual Change 与每次运行的方差。

Cookie 在性能测量中的两种角色

Cookie 在脚本测量中通常服务于两个截然不同的目的:

  1. 业务性用途(想测的状态):有些页面必须携带 Cookie 才能呈现你真正想测量的形态——登录后的视图、A/B 测试的实验组(cell)、功能开关(feature flag)的某个分支。
  2. 干扰性来源(想消除的噪声):欧洲几乎所有站点都会弹出 GDPR 同意横幅(consent banner)。它会导致 First Visual Change 提前触发、在用户点击前阻塞页面渲染,并给每一次运行叠加几十到几百毫秒的额外方差。如果不处理,横幅会对你的性能数据造成系统性污染。

本教程覆盖这两类场景的全部处理方式。

Cookie API:设置、读取与删除

Cookie 命令的完整参考在 Cookie command page。核心形态如下:

// Set a cookie before measuring
await commands.cookie.set('consent', 'true');
await commands.cookie.set('ab_variant', 'B', { path: '/', secure: true });

// Read a cookie
const value = await commands.cookie.get('consent');

// Read everything
const all = await commands.cookie.getAll();

// Delete one or all
await commands.cookie.delete('session');
await commands.cookie.deleteAll();

方法签名与参数

根据仓库内自动生成的 API 参考,Cookie 命令共有 5 个异步方法:

方法 签名 说明
set set(name, value, options?) → Promise<void> 设置一个 Cookie
get get(name) → Promise<Object|undefined> 按名称读取 Cookie,找不到时返回 undefined
getAll getAll() → Promise<Array> 读取当前页面全部 Cookie,返回对象数组
delete delete(name) → Promise<void> 按名称删除一个 Cookie
deleteAll deleteAll() → Promise<void> 删除当前页面的全部 Cookie

set 的可选 options 对象支持以下属性:

  • domain(string):该 Cookie 可见的域名;
  • path(string):Cookie 路径;
  • secure(boolean):是否为 secure Cookie(仅 HTTPS 传输);
  • httpOnly(boolean):是否仅限 HTTP 访问(脚本无法读取);
  • expiry(Date):Cookie 的过期时间。

注意 get 返回的是一个 Cookie 对象而非纯字符串,判断是否存在时应检查返回值是否为 undefined。

作用域规则:先导航、再设置

Cookie 被限定在当前域名(current domain)内——必须先至少导航到该站点一次,才能为它设置 Cookie,因为浏览器需要知道这个 Cookie 属于哪个 origin。这也是下面所有模式都先执行 commands.navigate(...) 再调用 commands.cookie.set(...) 的原因。

幂等性

commands.cookie.set 是幂等的:重复设置同名 Cookie 会覆盖旧值。这意味着脚本可以安全地放在循环或多次运行的场景里,不会因为重复执行而报错或产生副作用。

模式一:测量前注入同意 Cookie(推荐)

如果你的站点会显示同意横幅,而你希望指标反映的是"用户已经同意"的状态,就在测量开始前设置好同意 Cookie。大多数横幅脚本会读取类似 cookieConsent=true 或 OptanonAlertBoxClosed=... 这样的 Cookie,检测到已设置便跳过渲染。

/**
 * @param {import('browsertime').BrowsertimeContext} context
 * @param {import('browsertime').BrowsertimeCommands} commands
 */
export default async function (context, commands) {
  // Land on the origin so we can set the cookie for it
  await commands.navigate('https://www.example.org');

  // Inject the consent cookie — the exact name depends on your banner
  await commands.cookie.set('cookieConsent', 'true', {
    path: '/',
    secure: true
  });

  // Now measure — the banner is gone, no First Visual Change penalty
  return commands.measure.start('https://www.example.org/');
};

常见厂商 Cookie 名称速查

具体 Cookie 名称因横幅供应商而异,常见映射如下:

供应商 Cookie 名
OneTrust OptanonAlertBoxClosed
Cookiebot CookieConsent
HubSpot __hs_opt_out
自制横幅 cookielaw_accepted 等

获取准确名称的方法是:在 DevTools → Application → Cookies 面板中手动点击一次 "Accept" 按钮,然后查看浏览器写入了哪个 Cookie,把名称和值复制进你的脚本。

模式二:点击横幅关闭

如果你不知道 Cookie 名称,或者横幅只对部分用户显示,可以在脚本里直接把横幅点掉。代价是 measure.start 之前多一次点击;好处是不需要了解 Cookie 的具体形态。

/**
 * @param {import('browsertime').BrowsertimeContext} context
 * @param {import('browsertime').BrowsertimeCommands} commands
 */
export default async function (context, commands) {
  await commands.navigate('https://www.example.org');

  // Skip the click cleanly if the banner already isn't showing
  // (e.g. the consent cookie is already set from a previous run)
  if (await commands.exists('#accept-cookies')) {
    await commands.click('#accept-cookies');
  }

  return commands.measure.start('https://www.example.org/');
};

commands.exists 的存在性检查非常重要。如果横幅已经被关闭(例如复用了浏览器会话,或横幅每个 origin 只渲染一次),直接 click 会因为找不到元素而抛错——exists 让你能干净地跳过点击。

关于元素交互的更多细节(统一选择器语法、exists、click 的行为与超时控制),可以参考 Interact with the page 教程。其中提到,Browsertime 默认会为元素相关命令自动等待最多 6 秒(可通过 --timeouts.elementWait 调整),因此点击横幅前通常无需额外的显式等待。

模式三:用 --preScript 只处理一次,多个页面复用

如果你要在同一站点上测量很多页面,就把同意流程放进一个 --preScript,在逐页脚本中跳过它。这比在每个页面上重复点击快得多。

// preScript-consent.mjs
export default async function (context, commands) {
  await commands.navigate('https://www.example.org');
  await commands.cookie.set('cookieConsent', 'true', { path: '/', secure: true });
};

运行方式:

sitespeed.io --preScript preScript-consent.mjs https://www.example.org/page1 https://www.example.org/page2

preScript 的行为语义

从仓库源码看,--preScript 与 --postScript 在 lib/cli/options/browser.js 中定义,说明文字明确写着它们"在分析阶段之外运行,且可以多次传递"。结合 Pre and post scripts 教程,需要理解以下几点:

  • 每次迭代(iteration)都会启动全新浏览器:-n 指定迭代次数,每个迭代开始时 preScript 都会重新执行、结束时 postScript 执行。这是刻意的设计——否则第二个迭代会在无任何登录/Cookie/地理围栏设置下测量。
  • 同一个迭代内只执行一次:在同一次迭代中,多个 URL 共享同一个浏览器会话,因此"登录/同意一次、测量多页"的模式对一批 URL 完全成立。
  • 不产生指标:在 preScript / postScript 里调用 commands.measure.start 会被忽略,它们只负责设置状态。请把 measure.start 放在测试脚本里。
  • 跨脚本共享状态靠浏览器而非 JavaScript:Cookie、localStorage、已导航到的 DOM 会带过去;preScript 里的局部变量不会,因为每个脚本是独立模块。

--preScript 可以多次传参并按顺序执行,方便组合:一个 consent 脚本、一个 login 脚本、一个 geo 脚本。

完整的 pre/post 脚本模式(包括登录一次、传参避免硬编码密码、postScript 登出清理)见 Pre and post scripts 教程。

把 Cookie 名称参数化,避免硬编码

配合 Tips and tricks 教程中"向脚本传自定义选项"的技巧,你可以把横幅 Cookie 名和值通过命令行传入,而不是写死在脚本里:

sitespeed.io \
  --preScript preScript-consent.mjs \
  --browsertime.my.consentName OptanonAlertBoxClosed \
  --browsertime.my.consentValue '1' \
  https://www.example.org/page1
// preScript-consent.mjs
export default async function (context, commands) {
  await commands.navigate('https://www.example.org');
  await commands.cookie.set(
    context.options.my.consentName,
    context.options.my.consentValue,
    { path: '/', secure: true }
  );
};

何时选择哪种模式

场景 推荐模式
知道横幅 Cookie 名称,且横幅固定出现 模式一:注入 Cookie
不知道 Cookie 名称,或横幅只在部分用户身上出现 模式二:exists + 点击
同一站点要测量多个页面,希望最快 模式三:--preScript 只做一次

三种模式可以混合:例如用 --preScript 注入 Cookie,再在页内脚本中用 exists 点击兜底,覆盖横幅行为不一致的情况。

验证与排错

  • 确认 Cookie 是否真的生效:在脚本中调用 await commands.cookie.get('cookieConsent'),检查返回对象是否存在,或调用 getAll() 列出全部 Cookie 核对名称与值。
  • 横幅未消失:Cookie 名称写错是最高频错误。回到 DevTools → Application → Cookies,对照 "Accept" 一次后浏览器实际写入的名称。
  • 点击失败:确认选择器与页面结构匹配。若横幅元素在部分运行中不存在,务必保留 exists 前置检查。
  • 脚本抛错:未捕获的错误会被 sitespeed.io 记录并上报到 HTML 报告与 Graphite/InfluxDB 的 browsertime.statistics.errors 指标;如需自定义错误上报,可参考 Error handling 教程。

延伸阅读

登录后查看全文
sitespeed.io