跳转到主要内容

CDPSession

CDPSession 实例用于与原始 Chrome Devtools 协议通信

  • 协议方法可以通过 session.send 方法调用。
  • 协议事件可以通过 session.on 方法订阅。

有用链接

const client = await page.context().newCDPSession(page);
await client.send('Animation.enable');
client.on('Animation.animationCreated', () => console.log('Animation created!'));
const response = await client.send('Animation.getPlaybackRate');
console.log('playback rate is ' + response.playbackRate);
await client.send('Animation.setPlaybackRate', {
playbackRate: response.playbackRate / 2
});

方法

detach

v1.9 之前添加 cdpSession.detach

将 CDPSession 从目标分离。一旦分离,CDPSession 对象将不再发出任何事件,也无法用于发送消息。

用法

await cdpSession.detach();

返回


send

v1.9 之前添加 cdpSession.send

用法

await cdpSession.send(method);
await cdpSession.send(method, params);

参数

  • method string#

    协议方法名称。

  • params Object (可选)#

    可选方法参数。

返回


事件

on('close')

新增于: v1.59 cdpSession.on('close')

当会话关闭时触发,原因可能是目标(target)被关闭,或者调用了 session.detach()

用法

cdpSession.on('close', data => {});

事件数据


on('event')

新增于: v1.59 cdpSession.on('event')

当从会话接收到每个 CDP 事件时触发。允许在不预先知道事件名称的情况下一次性订阅所有 CDP 事件。

用法

session.on('event', ({ name, params }) => {
console.log(`CDP event: ${name}`, params);
});

事件数据