Skip to main content

CDPSession

CDPSession 实例用于直接使用原生的 Chrome Devtools 协议进行通信:

🌐 The CDPSession instances are used to talk raw Chrome Devtools Protocol:

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

有用的链接:

🌐 Useful links:

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
});

方法

🌐 Methods

detach

Added before v1.9 cdpSession.detach

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

🌐 Detaches the CDPSession from the target. Once detached, the CDPSession object won't emit any events and can't be used to send messages.

用法

await cdpSession.detach();

返回


send

Added before v1.9 cdpSession.send

用法

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

参数

  • method string#

    协议方法名称。

  • params Object (optional)#

    可选方法参数。

返回


事件

🌐 Events

on('close')

Added in: v1.59 cdpSession.on('close')

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

🌐 Emitted when the session is closed, either because the target was closed or session.detach() was called.

用法

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

事件数据


on('event')

Added in: v1.59 cdpSession.on('event')

在从会话接收到每个 CDP 事件时发出。允许订阅所有 CDP 事件,而无需事先知道它们的名称。

🌐 Emitted for every CDP event received from the session. Allows subscribing to all CDP events at once without knowing their names ahead of time.

用法

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

事件数据