自动化

使用仅限 Window 的 DOM 工具、访问 closed Shadow Root,并通过 automation 能力派发可信事件。

能力:automationAPI:window.chrovia.automation。不需要 EP 配置。Window 上下文还需要 unrestrictedApi;Service Worker 不提供 automation。

查询与交互

在你控制的测试页面 DOM 就绪后运行。此例创建 closed Shadow Root,再通过 SDK 显式访问:

const automation = window.chrovia?.automation;
if (!automation) {
  throw new Error('automation and unrestrictedApi are required');
}
const host = document.createElement('div');
document.body.append(host);
const shadow = host.attachShadow({ mode: 'closed' });
const button = document.createElement('button');
button.textContent = 'SDK test';
button.addEventListener('click', event => console.log(event.isTrusted));
shadow.append(button);
const root = automation.getShadowRoot(host);
const target = automation.querySelector(root, 'button');
if (target) {
  automation.dispatchTrustedEvent(target, new MouseEvent('click', { bubbles: true }));
}

监听器收到的事件应满足 isTrusted === true。由于创建的是 closed root,普通 host.shadowRoot 仍为 null

方法

方法返回值
getShadowRoot(element)ShadowRoot 或 null,包括 closed root
querySelector(selectors)当前文档中的首个匹配项或 null
querySelector(root, selectors)Element 或 ShadowRoot 下的首个匹配项
querySelectorAll(selectors)当前文档的 NodeList
querySelectorAll(root, selectors)指定根节点下的 NodeList
getBoundingClientRect(element)元素的 DOMRect
dispatchTrustedEvent(target, event)布尔派发结果

这些调用都是同步的。无效 CSS 选择器可能抛错。查询不会自动穿透所有 Shadow Root 或 iframe,需要分别取得根节点再查询。派发成功不代表表单已提交或网络请求成功。

限制与验证

导航和等待应使用普通 DOM 与浏览器自动化工具。此 API 域没有 click()type()launch(),也不会创建 Node.js 浏览器控制器。焦点、输入值、选区及应用事件顺序仍由集成代码负责。

可信事件不保证具有所有原生用户激活或系统输入效果,应测试实际页面行为。API 缺失时,检查两项能力,并确认运行于 Window 而不是扩展后台 Worker。参见 API 上下文