《Chrome CDP 系列》输入模拟与存储安全:Input / Storage / Security

17 阅读12分钟

协议快照:devtools-protocol 0.0.1748923
本文是 CDP 系列第 8 篇,聚焦 Input、Storage 与 Security 域。
《CDP 系列》专栏

先附上官方文档


这篇解决什么问题

自动化工具最终都要回答三个问题:

  1. 怎样把键盘、鼠标、触摸、拖拽动作送进页面;
  2. 怎样初始化、读取、观察和清理 Cookie、IndexedDB、CacheStorage 等站点状态;
  3. 怎样处理证书错误,以及如何观察页面的安全状态。

这三个问题分别对应 Input、Storage、Security。它们经常一起出现:一个登录用例可能要先设置 Cookie,再模拟点击和输入,最后确认页面安全状态;一个存储回归用例可能要清理 IndexedDB,观察更新事件,再模拟一组交互触发写入。

职责边界

Input 管什么

  • 键盘事件:keyDown / keyUp / rawKeyDown / char
  • 鼠标事件:按下、释放、移动、滚轮
  • 触摸事件:touchStart / touchMove / touchEnd / touchCancel
  • 拖拽事件与拖拽拦截
  • IME 文本插入与候选组合
  • 高层手势合成:tap、scroll、pinch
  • 输入忽略开关

Input 的坐标单位是主 frame viewport 内的 CSS 像素,Y 轴向下增长。

Storage 管什么

  • 按 origin 或 storage key 清理存储
  • 读取、设置、清空浏览器 Cookie
  • 查询存储用量与配额
  • 跟踪 CacheStorage / IndexedDB 更新
  • 跟踪和删除 Storage Bucket
  • Trust Tokens、Private Verification Tokens 等实验状态

Storage 依赖 Browser 和 Network:BrowserContextID 来自 Browser 域,Cookie 类型复用 Network.Cookie 与 Network.CookieParam。

Security 管什么

  • 开启或关闭安全状态跟踪
  • 忽略所有证书错误
  • 暴露页面当前可见安全状态与证书信息

它不负责页面权限、网络请求拦截、CSP 审计或登录态管理。

当前状态

按当前 JSON 快照统计:

域域级状态命令事件稳定命令稳定事件实验命令废弃命令
Input稳定1315080
Storage实验277146121
Security稳定533002

注意两点:

  • Storage 域级标记为 experimental,但其中不少命令在 item 级是稳定项。能不能用仍取决于客户端和 Chrome 版本如何暴露域。
  • Security 没有稳定事件。当前能提供完整页面安全状态的是实验事件 visibleSecurityStateChanged;旧的 securityStateChanged 已废弃。

Input 核心命令

Input.dispatchKeyEvent

发送键盘事件。

{
  "method": "Input.dispatchKeyEvent",
  "params": {
    "type": "keyDown",
    "key": "a",
    "code": "KeyA",
    "text": "a",
    "windowsVirtualKeyCode": 65,
    "nativeVirtualKeyCode": 65
  }
}

type 有四种:

  • keyDown
  • keyUp
  • rawKeyDown
  • char

常用参数:

  • key:DOM KeyboardEvent.key
  • code:物理键,例如 KeyA、Enter
  • text:按键产生的文本;keyUp / rawKeyDown 不需要
  • windowsVirtualKeyCode / nativeVirtualKeyCode
  • modifiers:位标记,Alt=1、Ctrl=2、Meta=4、Shift=8
  • timestamp
  • autoRepeat
  • location

输入一个普通字符通常需要 keyDown 和 keyUp 两个事件,并给 keyDown 提供 text。快捷键还需要正确的 modifier 位和 virtual key code。

Input.insertText

实验命令,用于插入不是由按键直接产生的文本,例如 emoji 面板或 IME 输入。

{
  "method": "Input.insertText",
  "params": { "text": "你好,CDP" }
}

它更像“提交一段文本”,不是完整的 keydown/keyup 序列。页面监听按键细节时,不要用它替代键盘事件。

Input.dispatchMouseEvent

发送鼠标事件。

{
  "method": "Input.dispatchMouseEvent",
  "params": {
    "type": "mousePressed",
    "x": 120,
    "y": 80,
    "button": "left",
    "buttons": 1,
    "clickCount": 1
  }
}

type 支持:

  • mousePressed
  • mouseReleased
  • mouseMoved
  • mouseWheel

常用参数:

  • x / y:viewport CSS 像素
  • button:none / left / middle / right / back / forward
  • buttons:当前按下按钮的位标记,Left=1、Right=2、Middle=4、Back=8、Forward=16
  • clickCount
  • modifiers
  • deltaX / deltaY:滚轮事件使用
  • pointerType:mouse / pen
  • timestamp

一次左键点击应发送 mousePressed 和 mouseReleased,并保持 x/y/button/clickCount 一致。

Input.dispatchTouchEvent

发送触摸事件。

{
  "method": "Input.dispatchTouchEvent",
  "params": {
    "type": "touchStart",
    "touchPoints": [
      { "x": 100, "y": 200, "id": 1 }
    ]
  }
}

规则:

  • touchStart / touchMove 至少要有一个 touch point
  • touchEnd / touchCancel 不携带 touch point
  • id 用于跨事件追踪同一个触点

TouchPoint 还支持 radiusX、radiusY、rotationAngle、force、tiltX、tiltY 等字段;tangentialPressure、twist 是实验字段。

Input.synthesizeTapGesture

实验命令,合成一次或多次 tap。

{
  "method": "Input.synthesizeTapGesture",
  "params": {
    "x": 100,
    "y": 200,
    "duration": 50,
    "tapCount": 1
  }
}

它按时间段派发合适的触摸事件,比手工拼 touchStart/touchEnd 更方便。tapCount: 2 可用于 double tap。

同类命令:

  • synthesizeScrollGesture
  • synthesizePinchGesture

这些高层手势都是实验命令,且 gestureSourceType 可选 default / touch / mouse。跨版本自动化应做好能力探测。

Input.dispatchDragEvent 与拖拽拦截

实验命令 dispatchDragEvent 支持:

  • dragEnter
  • dragOver
  • drop
  • dragCancel

实验命令 setInterceptDrags(true) 会阻止默认拖放行为,并触发 Input.dragIntercepted 事件;客户端可以用事件中的 DragData 再调用 dispatchDragEvent 恢复或改写拖放行为。

Input.cancelDragging 是稳定命令,用于取消页面中的活动拖拽。

Input.setIgnoreInputEvents

忽略输入事件处理,常用于审计页面时避免用户或外部输入干扰。

{
  "method": "Input.setIgnoreInputEvents",
  "params": { "ignore": true }
}

这是全局开关,不要在普通自动化用例中长期开启,否则后续输入会全部失效。

Input 常见协作

  • Emulation.setTouchEmulationEnabled:改变触摸能力检测;具体触摸序列仍由 Input 派发
  • DOM.getDocument / DOM.querySelector / DOM.resolveNode:查找元素并计算坐标
  • Runtime.evaluate:可直接调用 getBoundingClientRect() 获取 CSS 像素坐标
  • Page:导航、生命周期和视口
  • Input.setIgnoreInputEvents:审计时屏蔽输入

Storage 核心命令

Storage.getStorageKey

实验命令,返回当前目标或指定 frame 的 storage key。

{
  "method": "Storage.getStorageKey",
  "params": {}
}

返回:

{
  "storageKey": "https://example.com"
}

同域还有一个 getStorageKeyForFrame,但它已废弃,不应在新代码中使用。

Storage key 与 origin 不总是同一概念。分区存储、第三方上下文和 Storage Bucket 场景下,用 storage key 能更准确描述数据归属。

Storage.clearDataForOrigin / clearDataForStorageKey

清理指定 origin 或 storage key 的数据。

{
  "method": "Storage.clearDataForStorageKey",
  "params": {
    "storageKey": "https://example.com",
    "storageTypes": "indexeddb,cache_storage,local_storage"
  }
}

storageTypes 是逗号分隔字符串,可用类型来自 StorageType:

  • cookies
  • file_systems
  • indexeddb
  • local_storage
  • shader_cache
  • websql
  • service_workers
  • cache_storage
  • storage_buckets
  • all
  • other

测试隔离时优先精确清理,少用 all,避免误删下载状态、权限或浏览器级配置这类不属于页面存储的数据。

Storage.getCookies

返回所有浏览器 Cookie。

{
  "method": "Storage.getCookies",
  "params": {
    "browserContextId": "..."
  }
}

browserContextId 是可选参数,只在 browser endpoint 调用时使用。返回的 Cookie 是 Network.Cookie[],包含 name、value、domain、path、expires、size、httpOnly、secure、session、sameSite 等字段。

它与 Network.getCookies 的视角不同:Network 面向当前 URL / 请求上下文,Storage 面向浏览器存储和 browser context。

Storage.setCookies

批量写入 Cookie。

{
  "method": "Storage.setCookies",
  "params": {
    "cookies": [
      {
        "name": "session",
        "value": "abc123",
        "url": "https://example.com/",
        "httpOnly": true,
        "secure": true,
        "sameSite": "Lax"
      }
    ]
  }
}

CookieParam 的关键字段:

  • name、value
  • url:请求 URI,会影响默认 domain/path/source port/source scheme
  • domain、path
  • secure、httpOnly
  • sameSite
  • expires:不设置则为 session cookie

priority、sourceScheme、sourcePort、partitionKey 是实验字段。建议优先用 url 表达归属;显式混用 url 和 domain/path 时要确认浏览器最终作用域。

Storage.clearCookies

清空 Cookie。可在 browser endpoint 上通过 browserContextId 限定 browser context。

{
  "method": "Storage.clearCookies",
  "params": { "browserContextId": "..." }
}

它比 clearDataForOrigin(storageTypes: "cookies") 更直接,但作用范围也更宽。测试用例应明确自己要“删除某站点 Cookie”还是“清空整个 context Cookie”。

Storage.getUsageAndQuota

查询 origin 的存储用量与配额。

{
  "method": "Storage.getUsageAndQuota",
  "params": { "origin": "https://example.com" }
}

返回:

  • usage
  • quota
  • overrideActive
  • usageBreakdown

usageBreakdown 按 StorageType 拆分字节数,适合判断是 IndexedDB、CacheStorage 还是其他存储占用了空间。

Storage.overrideQuotaForOrigin

实验命令,为指定 origin 覆盖配额。多次调用以最后一次为准;不传 quotaSize 可恢复默认。它没有单独的 clear 命令,测试结束要显式调用一次无 quotaSize 的覆盖来重置。

CacheStorage / IndexedDB 追踪

按 storage key 注册追踪:

{
  "method": "Storage.trackIndexedDBForStorageKey",
  "params": {
    "storageKey": "https://example.com"
  }
}

注册即开启追踪;对应 untrackIndexedDBForStorageKey 取消。

可注册的事件源:

  • CacheStorage:trackCacheStorageForOrigin / trackCacheStorageForStorageKey
  • IndexedDB:trackIndexedDBForOrigin / trackIndexedDBForStorageKey

对应 untrack 命令成对存在。

Storage Bucket

实验命令:

  • setStorageBucketTracking(storageKey, enable)
  • deleteStorageBucket(bucket)

StorageBucket 由 storageKey 和可选 bucketName 组成;未指定 bucket name 时表示默认 bucket。事件包括:

  • storageBucketCreatedOrUpdated
  • storageBucketDeleted

这是当前快照中较新的能力,部署前要确认 Chrome 支持。

Storage 核心事件

CacheStorage

  • cacheStorageListUpdated:cache 被添加或删除
  • cacheStorageContentUpdated:cache 内容变化

事件参数包含 origin、storageKey、bucketId,内容更新还包含 cacheName。

IndexedDB

  • indexedDBListUpdated:数据库列表变化
  • indexedDBContentUpdated:object store 内容变化

内容更新参数包含 databaseName 和 objectStoreName。

Storage Bucket

  • storageBucketCreatedOrUpdated
  • storageBucketDeleted

Private Verification Tokens

实验事件 privateVerificationTokensUpdated 表示 token 被存储或删除。相关查询、删除、追踪命令也全部是实验项。

Security 核心命令

Security.enable / Security.disable

开启或关闭安全状态跟踪。

{
  "method": "Security.enable"
}

开启后可以观察 visibleSecurityStateChanged。注意该事件本身是实验事件。

Security.setIgnoreCertificateErrors

忽略所有证书错误。

{
  "method": "Security.setIgnoreCertificateErrors",
  "params": { "ignore": true }
}

这是粗粒度开关:它不区分过期证书、域名不匹配、自签证书或被撤销证书。适合本地 HTTPS 测试环境,不应作为生产或外部站点抓取的默认策略。

更安全的方式是在启动浏览器时为测试站点配置受信证书,或只对明确的本地域名启用例外。

废弃的证书错误处理链路

以下命令与事件已废弃:

  • Security.setOverrideCertificateErrors
  • Security.handleCertificateError
  • Security.certificateError

旧流程是开启 override,收到 certificateError,再按 eventId 回复 continue 或 cancel。当前快照明确标记 deprecated,新代码不要基于这条链路设计。

Security 核心事件

Security.visibleSecurityStateChanged

实验事件,返回页面当前可见安全状态。

{
  "method": "Security.visibleSecurityStateChanged",
  "params": {
    "visibleSecurityState": {
      "securityState": "secure",
      "certificateSecurityState": {
        "protocol": "TLS 1.3",
        "certificate": ["..."],
        "subjectName": "example.com"
      },
      "securityStateIssueIds": []
    }
  }
}

securityState 可能是:

  • unknown
  • neutral
  • insecure
  • secure
  • info
  • insecure-broken

CertificateSecurityState 还提供 protocol、keyExchange、cipher、证书链、subject、issuer、有效期、弱签名、SHA-1 链、旧协议/旧算法等信息。

Security.securityStateChanged

已废弃,且 PDL 注释说明它不再发送。不要把旧教程中的这个事件当成当前方案。

最小示例:点击、输入、读取 Cookie

let nextId = 1;
const pending = new Map();

function send(method, params = {}, sessionId) {
  const id = nextId++;
  const message = { id, method, params };
  if (sessionId) message.sessionId = sessionId;

  ws.send(JSON.stringify(message));
  return new Promise((resolve, reject) => {
    pending.set(id, { resolve, reject });
  });
}

async function click(x, y) {
  await send("Input.dispatchMouseEvent", {
    type: "mousePressed",
    x,
    y,
    button: "left",
    buttons: 1,
    clickCount: 1,
  });

  await send("Input.dispatchMouseEvent", {
    type: "mouseReleased",
    x,
    y,
    button: "left",
    buttons: 1,
    clickCount: 1,
  });
}

async function typeText(text) {
  for (const ch of text) {
    await send("Input.dispatchKeyEvent", {
      type: "keyDown",
      text: ch,
      key: ch,
    });
    await send("Input.dispatchKeyEvent", {
      type: "keyUp",
      key: ch,
    });
  }
}

async function loginFlow() {
  await send("Page.enable");
  await send("Page.navigate", { url: "https://example.com/login" });

  // 实际实现应等待 Page.loadEventFired 或特定 DOM 状态
  await click(100, 100);
  await typeText("user@example.com");
  await click(100, 150);
  await typeText("password");
  await click(160, 220);

  // 等待导航或登录请求完成后读取
  const { cookies } = await send("Storage.getCookies");
  console.log(cookies.filter((cookie) => cookie.httpOnly));
}

这段代码展示 Input 与 Storage 的组合。示例基于协议定义推导,未在真实 Chrome 会话中验证;真实用例应加入元素定位、焦点检查、事件等待和异常恢复。

最小示例:清理站点状态并观察 IndexedDB

const events = [];

ws.on("message", (raw) => {
  const msg = JSON.parse(raw.toString());

  if (msg.method === "Storage.indexedDBContentUpdated") {
    events.push({
      type: "content",
      database: msg.params.databaseName,
      store: msg.params.objectStoreName,
    });
  }

  if (msg.method === "Storage.indexedDBListUpdated") {
    events.push({ type: "list" });
  }
});

async function resetStorage(storageKey) {
  await send("Storage.clearDataForStorageKey", {
    storageKey,
    storageTypes: "indexeddb,cache_storage,local_storage",
  });

  await send("Storage.trackIndexedDBForStorageKey", { storageKey });
  await send("Page.navigate", { url: `${storageKey}/app` });

  // 等待应用初始化完成后取消追踪
  await send("Storage.untrackIndexedDBForStorageKey", { storageKey });
}

事件是否触发取决于站点实际写入、浏览器实现和 session 归属。对 service worker 或跨 frame 写入,还要确认事件来自正确的 target session。

最小示例:观察安全状态

ws.on("message", (raw) => {
  const msg = JSON.parse(raw.toString());

  if (msg.method === "Security.visibleSecurityStateChanged") {
    const state = msg.params.visibleSecurityState;
    console.log("security:", state.securityState);
    console.log("issues:", state.securityStateIssueIds);

    if (state.certificateSecurityState) {
      console.log("protocol:", state.certificateSecurityState.protocol);
      console.log("subject:", state.certificateSecurityState.subjectName);
    }
  }
});

await send("Security.enable");
await send("Page.navigate", { url: "https://example.com" });

如果站点是 insecure 或 insecure-broken,再结合 Network 事件定位具体请求;Security 事件给出页面状态,不保证逐请求解释所有安全问题。

与 Puppeteer / Playwright 的对照

这两个工具把本篇的协议细节封装成了更高层 API:

诉求原生 CDP高层工具常见形态
点击Input.dispatchMouseEvent pressed/releasedpage.click(selector)
输入dispatchKeyEvent 序列或 insertTextpage.type() / page.fill()
触摸dispatchTouchEvent 或 gesture 合成touch / pointer 相关 API,视工具而定
CookieStorage.getCookies/setCookiescontext 或 page 级 cookie API
存储清理clearDataForOrigin/StorageKey通常通过 CDP session 或专用 API
忽略证书错误Security.setIgnoreCertificateErrorslaunch / context 选项

工具会隐藏坐标计算、事件序列、session 归属和部分版本差异。直接使用 CDP 的价值在于:更细的事件控制、绕过封装限制、定位工具行为,以及构建自己的自动化基础设施。

常见坑

坐标不是屏幕坐标

Input 的 x/y 是主 frame viewport 的 CSS 像素,不是操作系统屏幕坐标,也不是物理设备像素。设备缩放、页面滚动、frame 布局变化都会影响命中结果。

点击前没有确认元素可交互

CDP 派发的是输入事件,不保证元素存在、可见、未被遮挡、未 disabled,也不自动等待。应在点击前通过 DOM/Runtime 检查状态,并在必要时等待布局稳定。

把 insertText 当完整键盘

insertText 是实验命令,适合 IME/emoji 式文本提交;页面依赖 keydown、keyup、shortcut 或 virtual key code 时,应发送 dispatchKeyEvent 序列。

手写触摸序列缺少状态一致性

同一个触点的 move/end 应复用相同 id;touchEnd 不携带触点;多点触控要理解“changed points”语义。复杂手势优先考虑实验的 synthesize 命令,或使用高层工具封装。

Origin 和 storage key 混用

旧的清理和追踪命令按 origin,新命令按 storage key。分区存储和第三方上下文中二者可能不同。写测试时应明确数据归属,优先使用与被测 API 一致的键。

Cookie 作用域不如预期

CookieParam 中 url、domain、path、sourcePort、sourceScheme 会共同影响最终作用域。建议用 url 作为主入口;__Host-、__Secure-、SameSite、Secure、HttpOnly 也要符合浏览器规则。

忽略证书错误的范围过大

setIgnoreCertificateErrors(true) 是全局性粗开关。用于本地测试可以,用于外部站点会把真实安全故障掩盖掉,还可能让自动化继续访问错误站点。

Security 稳定事件缺失

当前快照中 securityStateChanged 已废弃,visibleSecurityStateChanged 是实验事件。依赖安全状态的项目要把它当作实验能力,做好 Chrome 版本探测。

稳定状态速查

能力状态
Input.dispatchKeyEvent / dispatchMouseEvent / dispatchTouchEvent稳定
Input.cancelDragging / setIgnoreInputEvents稳定
Input.insertText / imeSetComposition实验
Input drag dispatch / intercept / dragIntercepted实验
Input synthesize tap / scroll / pinch实验
Storage 域域级实验
Storage clearData / cookies / usage / cache / IndexedDB tracking多数为稳定项
Storage getStorageKey实验
Storage getStorageKeyForFrame废弃
Storage quota override / bucket / Trust Tokens / PVT实验
Storage cache / IndexedDB / bucket 更新事件多数为稳定项
Security.enable / disable / setIgnoreCertificateErrors稳定
Security.visibleSecurityStateChanged实验事件
Security.handleCertificateError / setOverrideCertificateErrors / certificateError废弃
Security.securityStateChanged废弃且不再发送

下一篇

核心域篇到这里已经覆盖了页面、网络、DOM、JS、目标管理、仿真性能、输入存储与安全。全系列的下一篇,收尾篇:会对比 CDP 与 Puppeteer / Playwright 的抽象层次,说明这些工具如何封装 CDP,以及什么时候应该直接使用协议。