Skip to main content
Version: 22.9.0

Keyboard 类

¥Keyboard class

Keyboard 提供了用于管理虚拟键盘的 api。高级 API 是 Keyboard.type(),它采用原始字符并在页面上生成正确的 keydown、keypress/input 和 keyup 事件。

¥Keyboard provides an api for managing a virtual keyboard. The high level api is Keyboard.type(), which takes raw characters and generates proper keydown, keypress/input, and keyup events on your page.

签名:

¥Signature:

export declare abstract class Keyboard

备注

¥Remarks

为了更好地控制,你可以使用 Keyboard.down()Keyboard.up()Keyboard.sendCharacter() 手动触发事件,就像它们是从真正的键盘生成的一样。

¥For finer control, you can use Keyboard.down(), Keyboard.up(), and Keyboard.sendCharacter() to manually fire events as if they were generated from a real keyboard.

在 macOS 上,诸如 ⌘ A -> 全选之类的键盘快捷键不起作用。参见 #1313

¥On macOS, keyboard shortcuts like ⌘ A -> Select All do not work. See #1313.

此类的构造函数被标记为内部构造函数。第三方代码不应直接调用构造函数或创建扩展 Keyboard 类的子类。

¥The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the Keyboard class.

示例 1

¥Example 1

按住 Shift 以选择和删除某些文本的示例:

¥An example of holding down Shift in order to select and delete some text:

await page.keyboard.type('Hello World!');
await page.keyboard.press('ArrowLeft');

await page.keyboard.down('Shift');
for (let i = 0; i < ' World'.length; i++)
await page.keyboard.press('ArrowLeft');
await page.keyboard.up('Shift');

await page.keyboard.press('Backspace');
// Result text will end up saying 'Hello!'

示例 2

¥Example 2

A 的示例

¥An example of pressing A

await page.keyboard.down('Shift');
await page.keyboard.press('KeyA');
await page.keyboard.up('Shift');

方法

¥Methods

方法

修饰符

描述

down(key, options)

调度 keydown 事件。

评论:

如果 key 是单个字符,并且除了 Shift 之外没有按下任何修改键,也会生成 keypress/input 事件。可以指定 text 选项来强制生成输入事件。如果 key 是修饰键、ShiftMetaControlAlt,则后续按键将在该修饰键处于活动状态时发送。要释放修饰键,请使用 Keyboard.up()

按下该键一次后,后续调用 Keyboard.down() 会将 repeat 设置为 true。要释放密钥,请使用 Keyboard.up()

修饰键确实会影响 Keyboard.down()。按住 Shift 将以大写形式键入文本。

press(key, options)

Keyboard.down()Keyboard.up() 的快捷方式。

评论:

如果 key 是单个字符,并且除了 Shift 之外没有按下任何修改键,也会生成 keypress/input 事件。可以指定 text 选项来强制生成输入事件。

修饰键 DO 效果 Keyboard.press()。按住 Shift 将以大写形式键入文本。

sendCharacter(char)

调度 keypressinput 事件。这不会发送 keydownkeyup 事件。

评论:

修改键不会影响 Keyboard.sendCharacter。按住 Shift 将不会键入大写文本。

type(text, options)

为文本中的每个字符发送 keydownkeypress/inputkeyup 事件。

评论:

要按特殊键,例如 ControlArrowDown,请使用 Keyboard.press()

修改键不会影响 keyboard.type。按住 Shift 将不会键入大写文本。

up(key)

调度 keyup 事件。