refactor: use input API for CDP inputs (#10401)

This commit is contained in:
jrandolf 2023-06-19 10:12:43 +02:00 committed by GitHub
parent 138cc5c961
commit 39847bd231
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
22 changed files with 209 additions and 524 deletions

View File

@ -92,6 +92,7 @@ sidebar_label: API
| [InternalNetworkConditions](./puppeteer.internalnetworkconditions.md) | | | [InternalNetworkConditions](./puppeteer.internalnetworkconditions.md) | |
| [JSCoverageEntry](./puppeteer.jscoverageentry.md) | The CoverageEntry class for JavaScript | | [JSCoverageEntry](./puppeteer.jscoverageentry.md) | The CoverageEntry class for JavaScript |
| [JSCoverageOptions](./puppeteer.jscoverageoptions.md) | Set of configurable options for JS coverage. | | [JSCoverageOptions](./puppeteer.jscoverageoptions.md) | Set of configurable options for JS coverage. |
| [KeyDownOptions](./puppeteer.keydownoptions.md) | |
| [LaunchOptions](./puppeteer.launchoptions.md) | Generic launch options that can be passed when launching any browser. | | [LaunchOptions](./puppeteer.launchoptions.md) | Generic launch options that can be passed when launching any browser. |
| [LocatorEventObject](./puppeteer.locatoreventobject.md) | | | [LocatorEventObject](./puppeteer.locatoreventobject.md) | |
| [LocatorOptions](./puppeteer.locatoroptions.md) | | | [LocatorOptions](./puppeteer.locatoroptions.md) | |
@ -108,7 +109,6 @@ sidebar_label: API
| [PDFMargin](./puppeteer.pdfmargin.md) | | | [PDFMargin](./puppeteer.pdfmargin.md) | |
| [PDFOptions](./puppeteer.pdfoptions.md) | Valid options to configure PDF generation via [Page.pdf()](./puppeteer.page.pdf.md). | | [PDFOptions](./puppeteer.pdfoptions.md) | Valid options to configure PDF generation via [Page.pdf()](./puppeteer.page.pdf.md). |
| [Point](./puppeteer.point.md) | | | [Point](./puppeteer.point.md) | |
| [PressOptions](./puppeteer.pressoptions.md) | |
| [PuppeteerErrors](./puppeteer.puppeteererrors.md) | | | [PuppeteerErrors](./puppeteer.puppeteererrors.md) | |
| [PuppeteerLaunchOptions](./puppeteer.puppeteerlaunchoptions.md) | | | [PuppeteerLaunchOptions](./puppeteer.puppeteerlaunchoptions.md) | |
| [RemoteAddress](./puppeteer.remoteaddress.md) | | | [RemoteAddress](./puppeteer.remoteaddress.md) | |
@ -118,6 +118,7 @@ sidebar_label: API
| [SerializedAXNode](./puppeteer.serializedaxnode.md) | Represents a Node and the properties of it that are relevant to Accessibility. | | [SerializedAXNode](./puppeteer.serializedaxnode.md) | Represents a Node and the properties of it that are relevant to Accessibility. |
| [SnapshotOptions](./puppeteer.snapshotoptions.md) | | | [SnapshotOptions](./puppeteer.snapshotoptions.md) | |
| [TracingOptions](./puppeteer.tracingoptions.md) | | | [TracingOptions](./puppeteer.tracingoptions.md) | |
| [TypeOptions](./puppeteer.typeoptions.md) | |
| [Viewport](./puppeteer.viewport.md) | Sets the viewport of the page. | | [Viewport](./puppeteer.viewport.md) | Sets the viewport of the page. |
| [WaitForOptions](./puppeteer.waitforoptions.md) | | | [WaitForOptions](./puppeteer.waitforoptions.md) | |
| [WaitForSelectorOptions](./puppeteer.waitforselectoroptions.md) | | | [WaitForSelectorOptions](./puppeteer.waitforselectoroptions.md) | |
@ -165,6 +166,7 @@ sidebar_label: API
| [InnerParams](./puppeteer.innerparams.md) | | | [InnerParams](./puppeteer.innerparams.md) | |
| [InterceptResolutionStrategy](./puppeteer.interceptresolutionstrategy.md) | | | [InterceptResolutionStrategy](./puppeteer.interceptresolutionstrategy.md) | |
| [KeyInput](./puppeteer.keyinput.md) | All the valid keys that can be passed to functions that take user input, such as [keyboard.press](./puppeteer.keyboard.press.md) | | [KeyInput](./puppeteer.keyinput.md) | All the valid keys that can be passed to functions that take user input, such as [keyboard.press](./puppeteer.keyboard.press.md) |
| [KeyPressOptions](./puppeteer.keypressoptions.md) | |
| [LowerCasePaperFormat](./puppeteer.lowercasepaperformat.md) | | | [LowerCasePaperFormat](./puppeteer.lowercasepaperformat.md) | |
| [MouseButton](./puppeteer.mousebutton.md) | | | [MouseButton](./puppeteer.mousebutton.md) | |
| [NodeFor](./puppeteer.nodefor.md) | | | [NodeFor](./puppeteer.nodefor.md) | |

View File

@ -10,16 +10,16 @@ Focuses the element, and then uses [Keyboard.down()](./puppeteer.keyboard.down.m
```typescript ```typescript
class ElementHandle { class ElementHandle {
press(key: KeyInput, options?: PressOptions): Promise<void>; press(key: KeyInput, options?: Readonly<KeyPressOptions>): Promise<void>;
} }
``` ```
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | --------- | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| key | [KeyInput](./puppeteer.keyinput.md) | Name of key to press, such as <code>ArrowLeft</code>. See [KeyInput](./puppeteer.keyinput.md) for a list of all key names. | | key | [KeyInput](./puppeteer.keyinput.md) | Name of key to press, such as <code>ArrowLeft</code>. See [KeyInput](./puppeteer.keyinput.md) for a list of all key names. |
| options | [PressOptions](./puppeteer.pressoptions.md) | _(Optional)_ | | options | Readonly&lt;[KeyPressOptions](./puppeteer.keypressoptions.md)&gt; | _(Optional)_ |
**Returns:** **Returns:**

View File

@ -12,21 +12,16 @@ To press a special key, like `Control` or `ArrowDown`, use [ElementHandle.press(
```typescript ```typescript
class ElementHandle { class ElementHandle {
type( type(text: string, options?: Readonly<TypeOptions>): Promise<void>;
text: string,
options?: {
delay: number;
}
): Promise<void>;
} }
``` ```
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | ------------------ | -------------------------------------------------- | | --------- | --------------------------------------------------------- | -------------------------------------------------- |
| text | string | | | text | string | |
| options | { delay: number; } | _(Optional)_ Delay in milliseconds. Defaults to 0. | | options | Readonly&lt;[TypeOptions](./puppeteer.typeoptions.md)&gt; | _(Optional)_ Delay in milliseconds. Defaults to 0. |
**Returns:** **Returns:**

View File

@ -10,22 +10,16 @@ Dispatches a `keydown` event.
```typescript ```typescript
class Keyboard { class Keyboard {
down( down(key: KeyInput, options?: Readonly<KeyDownOptions>): Promise<void>;
key: KeyInput,
options?: {
text?: string;
commands?: string[];
}
): Promise<void>;
} }
``` ```
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | --------- | --------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| key | [KeyInput](./puppeteer.keyinput.md) | Name of key to press, such as <code>ArrowLeft</code>. See [KeyInput](./puppeteer.keyinput.md) for a list of all key names. | | key | [KeyInput](./puppeteer.keyinput.md) | Name of key to press, such as <code>ArrowLeft</code>. See [KeyInput](./puppeteer.keyinput.md) for a list of all key names. |
| options | { text?: string; commands?: string\[\]; } | _(Optional)_ An object of options. Accepts text which, if specified, generates an input event with this text. Accepts commands which, if specified, is the commands of keyboard shortcuts, see [Chromium Source Code](https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/editing/commands/editor_command_names.h) for valid command names. | | options | Readonly&lt;[KeyDownOptions](./puppeteer.keydownoptions.md)&gt; | _(Optional)_ An object of options. Accepts text which, if specified, generates an input event with this text. Accepts commands which, if specified, is the commands of keyboard shortcuts, see [Chromium Source Code](https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/editing/commands/editor_command_names.h) for valid command names. |
**Returns:** **Returns:**

View File

@ -10,23 +10,16 @@ Shortcut for [Keyboard.down()](./puppeteer.keyboard.down.md) and [Keyboard.up()]
```typescript ```typescript
class Keyboard { class Keyboard {
press( press(key: KeyInput, options?: Readonly<KeyPressOptions>): Promise<void>;
key: KeyInput,
options?: {
delay?: number;
text?: string;
commands?: string[];
}
): Promise<void>;
} }
``` ```
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | --------- | ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| key | [KeyInput](./puppeteer.keyinput.md) | Name of key to press, such as <code>ArrowLeft</code>. See [KeyInput](./puppeteer.keyinput.md) for a list of all key names. | | key | [KeyInput](./puppeteer.keyinput.md) | Name of key to press, such as <code>ArrowLeft</code>. See [KeyInput](./puppeteer.keyinput.md) for a list of all key names. |
| options | { delay?: number; text?: string; commands?: string\[\]; } | _(Optional)_ An object of options. Accepts text which, if specified, generates an input event with this text. Accepts delay which, if specified, is the time to wait between <code>keydown</code> and <code>keyup</code> in milliseconds. Defaults to 0. Accepts commands which, if specified, is the commands of keyboard shortcuts, see [Chromium Source Code](https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/editing/commands/editor_command_names.h) for valid command names. | | options | Readonly&lt;[KeyPressOptions](./puppeteer.keypressoptions.md)&gt; | _(Optional)_ An object of options. Accepts text which, if specified, generates an input event with this text. Accepts delay which, if specified, is the time to wait between <code>keydown</code> and <code>keyup</code> in milliseconds. Defaults to 0. Accepts commands which, if specified, is the commands of keyboard shortcuts, see [Chromium Source Code](https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/editing/commands/editor_command_names.h) for valid command names. |
**Returns:** **Returns:**

View File

@ -10,21 +10,16 @@ Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in t
```typescript ```typescript
class Keyboard { class Keyboard {
type( type(text: string, options?: Readonly<TypeOptions>): Promise<void>;
text: string,
options?: {
delay?: number;
}
): Promise<void>;
} }
``` ```
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | --------- | --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| text | string | A text to type into a focused element. | | text | string | A text to type into a focused element. |
| options | { delay?: number; } | _(Optional)_ An object of options. Accepts delay which, if specified, is the time to wait between <code>keydown</code> and <code>keyup</code> in milliseconds. Defaults to 0. | | options | Readonly&lt;[TypeOptions](./puppeteer.typeoptions.md)&gt; | _(Optional)_ An object of options. Accepts delay which, if specified, is the time to wait between <code>keydown</code> and <code>keyup</code> in milliseconds. Defaults to 0. |
**Returns:** **Returns:**

View File

@ -0,0 +1,18 @@
---
sidebar_label: KeyDownOptions
---
# KeyDownOptions interface
#### Signature:
```typescript
export interface KeyDownOptions
```
## Properties
| Property | Modifiers | Type | Description | Default |
| -------- | --------------------- | ---------- | ----------- | ------- |
| commands | <code>optional</code> | string\[\] | | |
| text | <code>optional</code> | string | | |

View File

@ -0,0 +1,13 @@
---
sidebar_label: KeyPressOptions
---
# KeyPressOptions type
#### Signature:
```typescript
export type KeyPressOptions = KeyDownOptions & TypeOptions;
```
**References:** [KeyDownOptions](./puppeteer.keydownoptions.md), [TypeOptions](./puppeteer.typeoptions.md)

View File

@ -10,15 +10,15 @@ Presses the mouse.
```typescript ```typescript
class Mouse { class Mouse {
down(options?: MouseOptions): Promise<void>; down(options?: Readonly<MouseOptions>): Promise<void>;
} }
``` ```
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | ------------------------------------------- | ------------------------------------------- | | --------- | ----------------------------------------------------------- | ------------------------------------------- |
| options | [MouseOptions](./puppeteer.mouseoptions.md) | _(Optional)_ Options to configure behavior. | | options | Readonly&lt;[MouseOptions](./puppeteer.mouseoptions.md)&gt; | _(Optional)_ Options to configure behavior. |
**Returns:** **Returns:**

View File

@ -10,17 +10,21 @@ Moves the mouse to the given coordinate.
```typescript ```typescript
class Mouse { class Mouse {
move(x: number, y: number, options?: MouseMoveOptions): Promise<void>; move(
x: number,
y: number,
options?: Readonly<MouseMoveOptions>
): Promise<void>;
} }
``` ```
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | --------------------------------------------------- | ------------------------------------------- | | --------- | ------------------------------------------------------------------- | ------------------------------------------- |
| x | number | Horizontal position of the mouse. | | x | number | Horizontal position of the mouse. |
| y | number | Vertical position of the mouse. | | y | number | Vertical position of the mouse. |
| options | [MouseMoveOptions](./puppeteer.mousemoveoptions.md) | _(Optional)_ Options to configure behavior. | | options | Readonly&lt;[MouseMoveOptions](./puppeteer.mousemoveoptions.md)&gt; | _(Optional)_ Options to configure behavior. |
**Returns:** **Returns:**

View File

@ -10,15 +10,15 @@ Releases the mouse.
```typescript ```typescript
class Mouse { class Mouse {
up(options?: MouseOptions): Promise<void>; up(options?: Readonly<MouseOptions>): Promise<void>;
} }
``` ```
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | ------------------------------------------- | ------------------------------------------- | | --------- | ----------------------------------------------------------- | ------------------------------------------- |
| options | [MouseOptions](./puppeteer.mouseoptions.md) | _(Optional)_ Options to configure behavior. | | options | Readonly&lt;[MouseOptions](./puppeteer.mouseoptions.md)&gt; | _(Optional)_ Options to configure behavior. |
**Returns:** **Returns:**

View File

@ -10,15 +10,15 @@ Dispatches a `mousewheel` event.
```typescript ```typescript
class Mouse { class Mouse {
wheel(options?: MouseWheelOptions): Promise<void>; wheel(options?: Readonly<MouseWheelOptions>): Promise<void>;
} }
``` ```
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | ----------------------------------------------------- | ------------------------------------------------------ | | --------- | --------------------------------------------------------------------- | ------------------------------------------------------ |
| options | [MouseWheelOptions](./puppeteer.mousewheeloptions.md) | _(Optional)_ Optional: <code>MouseWheelOptions</code>. | | options | Readonly&lt;[MouseWheelOptions](./puppeteer.mousewheeloptions.md)&gt; | _(Optional)_ Optional: <code>MouseWheelOptions</code>. |
**Returns:** **Returns:**

View File

@ -1,18 +0,0 @@
---
sidebar_label: PressOptions
---
# PressOptions interface
#### Signature:
```typescript
export interface PressOptions
```
## Properties
| Property | Modifiers | Type | Description | Default |
| -------- | --------------------- | ------ | ------------------------------------------------------------------------------------------------ | ------- |
| delay | <code>optional</code> | number | Time to wait between <code>keydown</code> and <code>keyup</code> in milliseconds. Defaults to 0. | |
| text | <code>optional</code> | string | If specified, generates an input event with this text. | |

View File

@ -0,0 +1,17 @@
---
sidebar_label: TypeOptions
---
# TypeOptions interface
#### Signature:
```typescript
export interface TypeOptions
```
## Properties
| Property | Modifiers | Type | Description | Default |
| -------- | --------------------- | ------ | ----------- | ------- |
| delay | <code>optional</code> | number | | |

View File

@ -20,7 +20,6 @@ import {Frame} from '../api/Frame.js';
import {CDPSession} from '../common/Connection.js'; import {CDPSession} from '../common/Connection.js';
import {ExecutionContext} from '../common/ExecutionContext.js'; import {ExecutionContext} from '../common/ExecutionContext.js';
import {getQueryHandlerAndSelector} from '../common/GetQueryHandler.js'; import {getQueryHandlerAndSelector} from '../common/GetQueryHandler.js';
import {MouseClickOptions} from '../common/Input.js';
import {WaitForSelectorOptions} from '../common/IsolatedWorld.js'; import {WaitForSelectorOptions} from '../common/IsolatedWorld.js';
import {LazyArg} from '../common/LazyArg.js'; import {LazyArg} from '../common/LazyArg.js';
import { import {
@ -35,6 +34,7 @@ import {isString, withSourcePuppeteerURLIfNone} from '../common/util.js';
import {assert} from '../util/assert.js'; import {assert} from '../util/assert.js';
import {AsyncIterableUtil} from '../util/AsyncIterableUtil.js'; import {AsyncIterableUtil} from '../util/AsyncIterableUtil.js';
import {KeyPressOptions, MouseClickOptions, TypeOptions} from './Input.js';
import {JSHandle} from './JSHandle.js'; import {JSHandle} from './JSHandle.js';
import {ScreenshotOptions} from './Page.js'; import {ScreenshotOptions} from './Page.js';
@ -88,20 +88,6 @@ export interface ClickOptions extends MouseClickOptions {
offset?: Offset; offset?: Offset;
} }
/**
* @public
*/
export interface PressOptions {
/**
* Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
*/
delay?: number;
/**
* If specified, generates an input event with this text.
*/
text?: string;
}
/** /**
* @public * @public
*/ */
@ -858,7 +844,7 @@ export class ElementHandle<
* *
* @param options - Delay in milliseconds. Defaults to 0. * @param options - Delay in milliseconds. Defaults to 0.
*/ */
async type(text: string, options?: {delay: number}): Promise<void>; async type(text: string, options?: Readonly<TypeOptions>): Promise<void>;
async type(): Promise<void> { async type(): Promise<void> {
throw new Error('Not implemented'); throw new Error('Not implemented');
} }
@ -877,7 +863,10 @@ export class ElementHandle<
* @param key - Name of key to press, such as `ArrowLeft`. * @param key - Name of key to press, such as `ArrowLeft`.
* See {@link KeyInput} for a list of all key names. * See {@link KeyInput} for a list of all key names.
*/ */
async press(key: KeyInput, options?: PressOptions): Promise<void>; async press(
key: KeyInput,
options?: Readonly<KeyPressOptions>
): Promise<void>;
async press(): Promise<void> { async press(): Promise<void> {
throw new Error('Not implemented'); throw new Error('Not implemented');
} }

View File

@ -82,6 +82,11 @@ export type KeyPressOptions = KeyDownOptions & TypeOptions;
* @public * @public
*/ */
export class Keyboard { export class Keyboard {
/**
* @internal
*/
constructor() {}
/** /**
* Dispatches a `keydown` event. * Dispatches a `keydown` event.
* *
@ -354,6 +359,11 @@ export type MouseButton = (typeof MouseButton)[keyof typeof MouseButton];
* @public * @public
*/ */
export class Mouse { export class Mouse {
/**
* @internal
*/
constructor() {}
/** /**
* Resets the mouse to the default state: No buttons pressed; position at * Resets the mouse to the default state: No buttons pressed; position at
* (0,0). * (0,0).
@ -504,6 +514,11 @@ export class Mouse {
* @public * @public
*/ */
export class Touchscreen { export class Touchscreen {
/**
* @internal
*/
constructor() {}
/** /**
* Dispatches a `touchstart` and `touchend` event. * Dispatches a `touchstart` and `touchend` event.
* @param x - Horizontal position of the tap. * @param x - Horizontal position of the tap.

View File

@ -29,7 +29,6 @@ import type {Dialog} from '../common/Dialog.js';
import {TargetCloseError} from '../common/Errors.js'; import {TargetCloseError} from '../common/Errors.js';
import {EventEmitter, Handler} from '../common/EventEmitter.js'; import {EventEmitter, Handler} from '../common/EventEmitter.js';
import type {FileChooser} from '../common/FileChooser.js'; import type {FileChooser} from '../common/FileChooser.js';
import type {Keyboard, Mouse, Touchscreen} from '../common/Input.js';
import type {WaitForSelectorOptions} from '../common/IsolatedWorld.js'; import type {WaitForSelectorOptions} from '../common/IsolatedWorld.js';
import type {PuppeteerLifeCycleEvent} from '../common/LifecycleWatcher.js'; import type {PuppeteerLifeCycleEvent} from '../common/LifecycleWatcher.js';
import { import {
@ -72,6 +71,7 @@ import type {
FrameAddStyleTagOptions, FrameAddStyleTagOptions,
FrameWaitForFunctionOptions, FrameWaitForFunctionOptions,
} from './Frame.js'; } from './Frame.js';
import {Keyboard, Mouse, Touchscreen} from './Input.js';
import type {JSHandle} from './JSHandle.js'; import type {JSHandle} from './JSHandle.js';
import {Locator} from './Locator.js'; import {Locator} from './Locator.js';

View File

@ -19,6 +19,7 @@ export * from './BrowserContext.js';
export * from './Page.js'; export * from './Page.js';
export * from './JSHandle.js'; export * from './JSHandle.js';
export * from './ElementHandle.js'; export * from './ElementHandle.js';
export * from './Input.js';
export * from './Frame.js'; export * from './Frame.js';
export * from './HTTPResponse.js'; export * from './HTTPResponse.js';
export * from './HTTPRequest.js'; export * from './HTTPRequest.js';

View File

@ -23,8 +23,8 @@ import {
ElementHandle, ElementHandle,
Offset, Offset,
Point, Point,
PressOptions,
} from '../api/ElementHandle.js'; } from '../api/ElementHandle.js';
import {KeyPressOptions, TypeOptions} from '../api/Input.js';
import {Page, ScreenshotOptions} from '../api/Page.js'; import {Page, ScreenshotOptions} from '../api/Page.js';
import {assert} from '../util/assert.js'; import {assert} from '../util/assert.js';
@ -458,12 +458,18 @@ export class CDPElementHandle<
await this.#page.touchscreen.touchEnd(); await this.#page.touchscreen.touchEnd();
} }
override async type(text: string, options?: {delay: number}): Promise<void> { override async type(
text: string,
options?: Readonly<TypeOptions>
): Promise<void> {
await this.focus(); await this.focus();
await this.#page.keyboard.type(text, options); await this.#page.keyboard.type(text, options);
} }
override async press(key: KeyInput, options?: PressOptions): Promise<void> { override async press(
key: KeyInput,
options?: Readonly<KeyPressOptions>
): Promise<void> {
await this.focus(); await this.focus();
await this.#page.keyboard.press(key, options); await this.#page.keyboard.press(key, options);
} }

View File

@ -17,6 +17,19 @@
import {Protocol} from 'devtools-protocol'; import {Protocol} from 'devtools-protocol';
import {Point} from '../api/ElementHandle.js'; import {Point} from '../api/ElementHandle.js';
import {
Keyboard,
KeyDownOptions,
KeyPressOptions,
Mouse,
MouseButton,
MouseClickOptions,
MouseMoveOptions,
MouseOptions,
MouseWheelOptions,
Touchscreen,
TypeOptions,
} from '../api/Input.js';
import {assert} from '../util/assert.js'; import {assert} from '../util/assert.js';
import {CDPSession} from './Connection.js'; import {CDPSession} from './Connection.js';
@ -27,47 +40,9 @@ type KeyDescription = Required<
>; >;
/** /**
* Keyboard provides an api for managing a virtual keyboard. * @internal
* The high level api is {@link Keyboard."type"},
* which takes raw characters and generates proper keydown, keypress/input,
* and keyup events on your page.
*
* @remarks
* For finer control, you can use {@link Keyboard.down},
* {@link Keyboard.up}, and {@link Keyboard.sendCharacter}
* to manually fire events as if they were generated from a real keyboard.
*
* On macOS, keyboard shortcuts like `⌘ A` -\> Select All do not work.
* See {@link https://github.com/puppeteer/puppeteer/issues/1313 | #1313}.
*
* @example
* An example of holding down `Shift` in order to select and delete some text:
*
* ```ts
* 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!'
* ```
*
* @example
* An example of pressing `A`
*
* ```ts
* await page.keyboard.down('Shift');
* await page.keyboard.press('KeyA');
* await page.keyboard.up('Shift');
* ```
*
* @public
*/ */
export class Keyboard { export class CDPKeyboard extends Keyboard {
#client: CDPSession; #client: CDPSession;
#pressedKeys = new Set<string>(); #pressedKeys = new Set<string>();
@ -80,39 +55,13 @@ export class Keyboard {
* @internal * @internal
*/ */
constructor(client: CDPSession) { constructor(client: CDPSession) {
super();
this.#client = client; this.#client = client;
} }
/** override async down(
* Dispatches a `keydown` event.
*
* @remarks
* If `key` is a single character and no modifier keys besides `Shift`
* are being held down, a `keypress`/`input` event will also generated.
* The `text` option can be specified to force an input event to be generated.
* If `key` is a modifier key, `Shift`, `Meta`, `Control`, or `Alt`,
* subsequent key presses will be sent with that modifier active.
* To release the modifier key, use {@link Keyboard.up}.
*
* After the key is pressed once, subsequent calls to
* {@link Keyboard.down} will have
* {@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat | repeat}
* set to true. To release the key, use {@link Keyboard.up}.
*
* Modifier keys DO influence {@link Keyboard.down}.
* Holding down `Shift` will type the text in upper case.
*
* @param key - Name of key to press, such as `ArrowLeft`.
* See {@link KeyInput} for a list of all key names.
*
* @param options - An object of options. Accepts text which, if specified,
* generates an input event with this text. Accepts commands which, if specified,
* is the commands of keyboard shortcuts,
* see {@link https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/editing/commands/editor_command_names.h | Chromium Source Code} for valid command names.
*/
async down(
key: KeyInput, key: KeyInput,
options: {text?: string; commands?: string[]} = { options: Readonly<KeyDownOptions> = {
text: undefined, text: undefined,
commands: [], commands: [],
} }
@ -209,14 +158,7 @@ export class Keyboard {
return description; return description;
} }
/** override async up(key: KeyInput): Promise<void> {
* Dispatches a `keyup` event.
*
* @param key - Name of key to release, such as `ArrowLeft`.
* See {@link KeyInput | KeyInput}
* for a list of all key names.
*/
async up(key: KeyInput): Promise<void> {
const description = this.#keyDescriptionForString(key); const description = this.#keyDescriptionForString(key);
this._modifiers &= ~this.#modifierBit(description.key); this._modifiers &= ~this.#modifierBit(description.key);
@ -231,23 +173,7 @@ export class Keyboard {
}); });
} }
/** override async sendCharacter(char: string): Promise<void> {
* Dispatches a `keypress` and `input` event.
* This does not send a `keydown` or `keyup` event.
*
* @remarks
* Modifier keys DO NOT effect {@link Keyboard.sendCharacter | Keyboard.sendCharacter}.
* Holding down `Shift` will not type the text in upper case.
*
* @example
*
* ```ts
* page.keyboard.sendCharacter('嗨');
* ```
*
* @param char - Character to send into the page.
*/
async sendCharacter(char: string): Promise<void> {
await this.#client.send('Input.insertText', {text: char}); await this.#client.send('Input.insertText', {text: char});
} }
@ -255,30 +181,10 @@ export class Keyboard {
return !!_keyDefinitions[char as KeyInput]; return !!_keyDefinitions[char as KeyInput];
} }
/** override async type(
* Sends a `keydown`, `keypress`/`input`, text: string,
* and `keyup` event for each character in the text. options: Readonly<TypeOptions> = {}
* ): Promise<void> {
* @remarks
* To press a special key, like `Control` or `ArrowDown`,
* use {@link Keyboard.press}.
*
* Modifier keys DO NOT effect `keyboard.type`.
* Holding down `Shift` will not type the text in upper case.
*
* @example
*
* ```ts
* await page.keyboard.type('Hello'); // Types instantly
* await page.keyboard.type('World', {delay: 100}); // Types slower, like a user
* ```
*
* @param text - A text to type into a focused element.
* @param options - An object of options. Accepts delay which,
* if specified, is the time to wait between `keydown` and `keyup` in milliseconds.
* Defaults to 0.
*/
async type(text: string, options: {delay?: number} = {}): Promise<void> {
const delay = options.delay || undefined; const delay = options.delay || undefined;
for (const char of text) { for (const char of text) {
if (this.charIsKey(char)) { if (this.charIsKey(char)) {
@ -294,31 +200,9 @@ export class Keyboard {
} }
} }
/** override async press(
* Shortcut for {@link Keyboard.down}
* and {@link Keyboard.up}.
*
* @remarks
* If `key` is a single character and no modifier keys besides `Shift`
* are being held down, a `keypress`/`input` event will also generated.
* The `text` option can be specified to force an input event to be generated.
*
* Modifier keys DO effect {@link Keyboard.press}.
* Holding down `Shift` will type the text in upper case.
*
* @param key - Name of key to press, such as `ArrowLeft`.
* See {@link KeyInput} for a list of all key names.
*
* @param options - An object of options. Accepts text which, if specified,
* generates an input event with this text. Accepts delay which,
* if specified, is the time to wait between `keydown` and `keyup` in milliseconds.
* Defaults to 0. Accepts commands which, if specified,
* is the commands of keyboard shortcuts,
* see {@link https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/editing/commands/editor_command_names.h | Chromium Source Code} for valid command names.
*/
async press(
key: KeyInput, key: KeyInput,
options: {delay?: number; text?: string; commands?: string[]} = {} options: Readonly<KeyPressOptions> = {}
): Promise<void> { ): Promise<void> {
const {delay = null} = options; const {delay = null} = options;
await this.down(key, options); await this.down(key, options);
@ -331,82 +215,6 @@ export class Keyboard {
} }
} }
/**
* @public
*/
export interface MouseOptions {
/**
* Determines which button will be pressed.
*
* @defaultValue `'left'`
*/
button?: MouseButton;
/**
* @deprecated Use {@link MouseClickOptions.count}.
*
* Determines the click count for the mouse event. This does not perform
* multiple clicks.
*
* @defaultValue `1`
*/
clickCount?: number;
}
/**
* @public
*/
export interface MouseClickOptions extends MouseOptions {
/**
* Time (in ms) to delay the mouse release after the mouse press.
*/
delay?: number;
/**
* Number of clicks to perform.
*
* @defaultValue `1`
*/
count?: number;
}
/**
* @public
*/
export interface MouseWheelOptions {
deltaX?: number;
deltaY?: number;
}
/**
* @public
*/
export interface MouseMoveOptions {
/**
* Determines the number of movements to make from the current mouse position
* to the new one.
*
* @defaultValue `1`
*/
steps?: number;
}
/**
* Enum of valid mouse buttons.
*
* @public
*/
export const MouseButton = Object.freeze({
Left: 'left',
Right: 'right',
Middle: 'middle',
Back: 'back',
Forward: 'forward',
}) satisfies Record<string, Protocol.Input.MouseButton>;
/**
* @public
*/
export type MouseButton = (typeof MouseButton)[keyof typeof MouseButton];
/** /**
* This must follow {@link Protocol.Input.DispatchMouseEventRequest.buttons}. * This must follow {@link Protocol.Input.DispatchMouseEventRequest.buttons}.
*/ */
@ -467,84 +275,17 @@ interface MouseState {
} }
/** /**
* The Mouse class operates in main-frame CSS pixels * @internal
* relative to the top-left corner of the viewport.
* @remarks
* Every `page` object has its own Mouse, accessible with [`page.mouse`](#pagemouse).
*
* @example
*
* ```ts
* // Using page.mouse to trace a 100x100 square.
* await page.mouse.move(0, 0);
* await page.mouse.down();
* await page.mouse.move(0, 100);
* await page.mouse.move(100, 100);
* await page.mouse.move(100, 0);
* await page.mouse.move(0, 0);
* await page.mouse.up();
* ```
*
* **Note**: The mouse events trigger synthetic `MouseEvent`s.
* This means that it does not fully replicate the functionality of what a normal user
* would be able to do with their mouse.
*
* For example, dragging and selecting text is not possible using `page.mouse`.
* Instead, you can use the {@link https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/getSelection | `DocumentOrShadowRoot.getSelection()`} functionality implemented in the platform.
*
* @example
* For example, if you want to select all content between nodes:
*
* ```ts
* await page.evaluate(
* (from, to) => {
* const selection = from.getRootNode().getSelection();
* const range = document.createRange();
* range.setStartBefore(from);
* range.setEndAfter(to);
* selection.removeAllRanges();
* selection.addRange(range);
* },
* fromJSHandle,
* toJSHandle
* );
* ```
*
* If you then would want to copy-paste your selection, you can use the clipboard api:
*
* ```ts
* // The clipboard api does not allow you to copy, unless the tab is focused.
* await page.bringToFront();
* await page.evaluate(() => {
* // Copy the selected content to the clipboard
* document.execCommand('copy');
* // Obtain the content of the clipboard as a string
* return navigator.clipboard.readText();
* });
* ```
*
* **Note**: If you want access to the clipboard API,
* you have to give it permission to do so:
*
* ```ts
* await browser
* .defaultBrowserContext()
* .overridePermissions('<your origin>', [
* 'clipboard-read',
* 'clipboard-write',
* ]);
* ```
*
* @public
*/ */
export class Mouse { export class CDPMouse extends Mouse {
#client: CDPSession; #client: CDPSession;
#keyboard: Keyboard; #keyboard: CDPKeyboard;
/** /**
* @internal * @internal
*/ */
constructor(client: CDPSession, keyboard: Keyboard) { constructor(client: CDPSession, keyboard: CDPKeyboard) {
super();
this.#client = client; this.#client = client;
this.#keyboard = keyboard; this.#keyboard = keyboard;
} }
@ -598,11 +339,7 @@ export class Mouse {
} }
} }
/** override async reset(): Promise<void> {
* Resets the mouse to the default state: No buttons pressed; position at
* (0,0).
*/
async reset(): Promise<void> {
const actions = []; const actions = [];
for (const [flag, button] of [ for (const [flag, button] of [
[MouseButtonFlag.Left, MouseButton.Left], [MouseButtonFlag.Left, MouseButton.Left],
@ -621,17 +358,10 @@ export class Mouse {
await Promise.all(actions); await Promise.all(actions);
} }
/** override async move(
* Moves the mouse to the given coordinate.
*
* @param x - Horizontal position of the mouse.
* @param y - Vertical position of the mouse.
* @param options - Options to configure behavior.
*/
async move(
x: number, x: number,
y: number, y: number,
options: MouseMoveOptions = {} options: Readonly<MouseMoveOptions> = {}
): Promise<void> { ): Promise<void> {
const {steps = 1} = options; const {steps = 1} = options;
const from = this.#state.position; const from = this.#state.position;
@ -656,12 +386,7 @@ export class Mouse {
} }
} }
/** override async down(options: Readonly<MouseOptions> = {}): Promise<void> {
* Presses the mouse.
*
* @param options - Options to configure behavior.
*/
async down(options: MouseOptions = {}): Promise<void> {
const {button = MouseButton.Left, clickCount = 1} = options; const {button = MouseButton.Left, clickCount = 1} = options;
const flag = getFlag(button); const flag = getFlag(button);
if (!flag) { if (!flag) {
@ -686,12 +411,7 @@ export class Mouse {
}); });
} }
/** override async up(options: Readonly<MouseOptions> = {}): Promise<void> {
* Releases the mouse.
*
* @param options - Options to configure behavior.
*/
async up(options: MouseOptions = {}): Promise<void> {
const {button = MouseButton.Left, clickCount = 1} = options; const {button = MouseButton.Left, clickCount = 1} = options;
const flag = getFlag(button); const flag = getFlag(button);
if (!flag) { if (!flag) {
@ -716,14 +436,7 @@ export class Mouse {
}); });
} }
/** override async click(
* Shortcut for `mouse.move`, `mouse.down` and `mouse.up`.
*
* @param x - Horizontal position of the mouse.
* @param y - Vertical position of the mouse.
* @param options - Options to configure behavior.
*/
async click(
x: number, x: number,
y: number, y: number,
options: Readonly<MouseClickOptions> = {} options: Readonly<MouseClickOptions> = {}
@ -753,29 +466,9 @@ export class Mouse {
await Promise.all(actions); await Promise.all(actions);
} }
/** override async wheel(
* Dispatches a `mousewheel` event. options: Readonly<MouseWheelOptions> = {}
* @param options - Optional: `MouseWheelOptions`. ): Promise<void> {
*
* @example
* An example of zooming into an element:
*
* ```ts
* await page.goto(
* 'https://mdn.mozillademos.org/en-US/docs/Web/API/Element/wheel_event$samples/Scaling_an_element_via_the_wheel?revision=1587366'
* );
*
* const elem = await page.$('div');
* const boundingBox = await elem.boundingBox();
* await page.mouse.move(
* boundingBox.x + boundingBox.width / 2,
* boundingBox.y + boundingBox.height / 2
* );
*
* await page.mouse.wheel({deltaY: -100});
* ```
*/
async wheel(options: MouseWheelOptions = {}): Promise<void> {
const {deltaX = 0, deltaY = 0} = options; const {deltaX = 0, deltaY = 0} = options;
const {position, buttons} = this.#state; const {position, buttons} = this.#state;
await this.#client.send('Input.dispatchMouseEvent', { await this.#client.send('Input.dispatchMouseEvent', {
@ -789,12 +482,10 @@ export class Mouse {
}); });
} }
/** override async drag(
* Dispatches a `drag` event. start: Point,
* @param start - starting point for drag target: Point
* @param target - point to drag to ): Promise<Protocol.Input.DragData> {
*/
async drag(start: Point, target: Point): Promise<Protocol.Input.DragData> {
const promise = new Promise<Protocol.Input.DragData>(resolve => { const promise = new Promise<Protocol.Input.DragData>(resolve => {
this.#client.once('Input.dragIntercepted', event => { this.#client.once('Input.dragIntercepted', event => {
return resolve(event.data); return resolve(event.data);
@ -806,12 +497,10 @@ export class Mouse {
return promise; return promise;
} }
/** override async dragEnter(
* Dispatches a `dragenter` event. target: Point,
* @param target - point for emitting `dragenter` event data: Protocol.Input.DragData
* @param data - drag data containing items and operations mask ): Promise<void> {
*/
async dragEnter(target: Point, data: Protocol.Input.DragData): Promise<void> {
await this.#client.send('Input.dispatchDragEvent', { await this.#client.send('Input.dispatchDragEvent', {
type: 'dragEnter', type: 'dragEnter',
x: target.x, x: target.x,
@ -821,12 +510,10 @@ export class Mouse {
}); });
} }
/** override async dragOver(
* Dispatches a `dragover` event. target: Point,
* @param target - point for emitting `dragover` event data: Protocol.Input.DragData
* @param data - drag data containing items and operations mask ): Promise<void> {
*/
async dragOver(target: Point, data: Protocol.Input.DragData): Promise<void> {
await this.#client.send('Input.dispatchDragEvent', { await this.#client.send('Input.dispatchDragEvent', {
type: 'dragOver', type: 'dragOver',
x: target.x, x: target.x,
@ -836,12 +523,10 @@ export class Mouse {
}); });
} }
/** override async drop(
* Performs a dragenter, dragover, and drop in sequence. target: Point,
* @param target - point to drop on data: Protocol.Input.DragData
* @param data - drag data containing items and operations mask ): Promise<void> {
*/
async drop(target: Point, data: Protocol.Input.DragData): Promise<void> {
await this.#client.send('Input.dispatchDragEvent', { await this.#client.send('Input.dispatchDragEvent', {
type: 'drop', type: 'drop',
x: target.x, x: target.x,
@ -851,15 +536,7 @@ export class Mouse {
}); });
} }
/** override async dragAndDrop(
* Performs a drag, dragenter, dragover, and drop in sequence.
* @param start - point to drag from
* @param target - point to drop on
* @param options - An object of options. Accepts delay which,
* if specified, is the time to wait between `dragover` and `drop` in milliseconds.
* Defaults to 0.
*/
async dragAndDrop(
start: Point, start: Point,
target: Point, target: Point,
options: {delay?: number} = {} options: {delay?: number} = {}
@ -879,37 +556,27 @@ export class Mouse {
} }
/** /**
* The Touchscreen class exposes touchscreen events. * @internal
* @public
*/ */
export class Touchscreen { export class CDPTouchscreen extends Touchscreen {
#client: CDPSession; #client: CDPSession;
#keyboard: Keyboard; #keyboard: CDPKeyboard;
/** /**
* @internal * @internal
*/ */
constructor(client: CDPSession, keyboard: Keyboard) { constructor(client: CDPSession, keyboard: CDPKeyboard) {
super();
this.#client = client; this.#client = client;
this.#keyboard = keyboard; this.#keyboard = keyboard;
} }
/** override async tap(x: number, y: number): Promise<void> {
* Dispatches a `touchstart` and `touchend` event.
* @param x - Horizontal position of the tap.
* @param y - Vertical position of the tap.
*/
async tap(x: number, y: number): Promise<void> {
await this.touchStart(x, y); await this.touchStart(x, y);
await this.touchEnd(); await this.touchEnd();
} }
/** override async touchStart(x: number, y: number): Promise<void> {
* Dispatches a `touchstart` event.
* @param x - Horizontal position of the tap.
* @param y - Vertical position of the tap.
*/
async touchStart(x: number, y: number): Promise<void> {
const touchPoints = [{x: Math.round(x), y: Math.round(y)}]; const touchPoints = [{x: Math.round(x), y: Math.round(y)}];
await this.#client.send('Input.dispatchTouchEvent', { await this.#client.send('Input.dispatchTouchEvent', {
type: 'touchStart', type: 'touchStart',
@ -917,12 +584,8 @@ export class Touchscreen {
modifiers: this.#keyboard._modifiers, modifiers: this.#keyboard._modifiers,
}); });
} }
/**
* Dispatches a `touchMove` event. override async touchMove(x: number, y: number): Promise<void> {
* @param x - Horizontal position of the move.
* @param y - Vertical position of the move.
*/
async touchMove(x: number, y: number): Promise<void> {
const movePoints = [{x: Math.round(x), y: Math.round(y)}]; const movePoints = [{x: Math.round(x), y: Math.round(y)}];
await this.#client.send('Input.dispatchTouchEvent', { await this.#client.send('Input.dispatchTouchEvent', {
type: 'touchMove', type: 'touchMove',
@ -930,10 +593,8 @@ export class Touchscreen {
modifiers: this.#keyboard._modifiers, modifiers: this.#keyboard._modifiers,
}); });
} }
/**
* Dispatches a `touchend` event. override async touchEnd(): Promise<void> {
*/
async touchEnd(): Promise<void> {
await this.#client.send('Input.dispatchTouchEvent', { await this.#client.send('Input.dispatchTouchEvent', {
type: 'touchEnd', type: 'touchEnd',
touchPoints: [], touchPoints: [],

View File

@ -60,7 +60,7 @@ import {EmulationManager} from './EmulationManager.js';
import {TargetCloseError} from './Errors.js'; import {TargetCloseError} from './Errors.js';
import {FileChooser} from './FileChooser.js'; import {FileChooser} from './FileChooser.js';
import {FrameManager, FrameManagerEmittedEvents} from './FrameManager.js'; import {FrameManager, FrameManagerEmittedEvents} from './FrameManager.js';
import {Keyboard, Mouse, Touchscreen} from './Input.js'; import {CDPKeyboard, CDPMouse, CDPTouchscreen} from './Input.js';
import {WaitForSelectorOptions} from './IsolatedWorld.js'; import {WaitForSelectorOptions} from './IsolatedWorld.js';
import {MAIN_WORLD} from './IsolatedWorlds.js'; import {MAIN_WORLD} from './IsolatedWorlds.js';
import { import {
@ -131,10 +131,10 @@ export class CDPPage extends Page {
#closed = false; #closed = false;
#client: CDPSession; #client: CDPSession;
#target: Target; #target: Target;
#keyboard: Keyboard; #keyboard: CDPKeyboard;
#mouse: Mouse; #mouse: CDPMouse;
#timeoutSettings = new TimeoutSettings(); #timeoutSettings = new TimeoutSettings();
#touchscreen: Touchscreen; #touchscreen: CDPTouchscreen;
#accessibility: Accessibility; #accessibility: Accessibility;
#frameManager: FrameManager; #frameManager: FrameManager;
#emulationManager: EmulationManager; #emulationManager: EmulationManager;
@ -162,9 +162,9 @@ export class CDPPage extends Page {
super(); super();
this.#client = client; this.#client = client;
this.#target = target; this.#target = target;
this.#keyboard = new Keyboard(client); this.#keyboard = new CDPKeyboard(client);
this.#mouse = new Mouse(client, this.#keyboard); this.#mouse = new CDPMouse(client, this.#keyboard);
this.#touchscreen = new Touchscreen(client, this.#keyboard); this.#touchscreen = new CDPTouchscreen(client, this.#keyboard);
this.#accessibility = new Accessibility(client); this.#accessibility = new Accessibility(client);
this.#frameManager = new FrameManager( this.#frameManager = new FrameManager(
client, client,
@ -427,11 +427,11 @@ export class CDPPage extends Page {
return this.#frameManager.mainFrame(); return this.#frameManager.mainFrame();
} }
override get keyboard(): Keyboard { override get keyboard(): CDPKeyboard {
return this.#keyboard; return this.#keyboard;
} }
override get touchscreen(): Touchscreen { override get touchscreen(): CDPTouchscreen {
return this.#touchscreen; return this.#touchscreen;
} }
@ -1395,7 +1395,7 @@ export class CDPPage extends Page {
return this.#closed; return this.#closed;
} }
override get mouse(): Mouse { override get mouse(): CDPMouse {
return this.#mouse; return this.#mouse;
} }

View File

@ -16,7 +16,7 @@
import os from 'os'; import os from 'os';
import expect from 'expect'; import expect from 'expect';
import {MouseButton} from 'puppeteer-core'; import {MouseButton} from 'puppeteer-core/internal/api/Input.js';
import {Page} from 'puppeteer-core/internal/api/Page.js'; import {Page} from 'puppeteer-core/internal/api/Page.js';
import {KeyInput} from 'puppeteer-core/internal/common/USKeyboardLayout.js'; import {KeyInput} from 'puppeteer-core/internal/common/USKeyboardLayout.js';