Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
feat(keyboard): add array overload to pressSequentially (#40748)
Sebastien Tardif7f1340670a5d
diff --git a/docs/src/api/class-keyboard.md b/docs/src/api/class-keyboard.mdindex 0bcaf6a59f..77c561ce3c 100644--- a/docs/src/api/class-keyboard.md+++ b/docs/src/api/class-keyboard.md@@ -308,6 +308,8 @@ In most cases, you should use [`method: Locator.fill`] instead. You only need toSends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text.+When [`option: namedKeys`] is `true`, anything inside `{}` is treated as a key name (same format as [`method: Keyboard.press`]).+To press a special key, like `Control` or `ArrowDown`, use [`method: Keyboard.press`].**Usage**@@ -315,6 +317,9 @@ To press a special key, like `Control` or `ArrowDown`, use [`method: Keyboard.pr```jsawait page.keyboard.type('Hello'); // Types instantlyawait page.keyboard.type('World', { delay: 100 }); // Types slower, like a user++// Mix text and special keys+await page.keyboard.type('Hello{Enter}World', { namedKeys: true });``````java@@ -322,21 +327,33 @@ await page.keyboard.type('World', { delay: 100 }); // Types slower, like a userpage.keyboard().type("Hello");// Types slower, like a userpage.keyboard().type("World", new Keyboard.TypeOptions().setDelay(100));++// Mix text and special keys+page.keyboard().type("Hello{Enter}World", new Keyboard.TypeOptions().setNamedKeys(true));``````python asyncawait page.keyboard.type("Hello") # types instantlyawait page.keyboard.type("World", delay=100) # types slower, like a user++# Mix text and special keys+await page.keyboard.type("Hello{Enter}World", named_keys=True)``````python syncpage.keyboard.type("Hello") # types instantlypage.keyboard.type("World", delay=100) # types slower, like a user++# Mix text and special keys+page.keyboard.type("Hello{Enter}World", named_keys=True)``````csharpawait page.Keyboard.TypeAsync("Hello"); // types instantlyawait page.Keyboard.TypeAsync("World", new() { Delay = 100 }); // types slower, like a user++// Mix text and special keys+await page.Keyboard.TypeAsync("Hello{Enter}World", new() { NamedKeys = true });```:::note@@ -359,6 +376,13 @@ A text to type into a focused element.Time to wait between key presses in milliseconds. Defaults to 0.+### option: Keyboard.type.namedKeys+* since: v1.61+- `namedKeys` <[boolean]>++When [`option: namedKeys`] is `true`, anything inside `{}` is treated as a key name (same format as [`method: Keyboard.press`]).+Use `{{` to type a literal brace character. Defaults to `false`.+## async method: Keyboard.up* since: v1.8diff --git a/docs/src/api/class-locator.md b/docs/src/api/class-locator.mdindex 59a98671ae..f2004c3318 100644--- a/docs/src/api/class-locator.md+++ b/docs/src/api/class-locator.md@@ -2103,6 +2103,8 @@ In most cases, you should use [`method: Locator.fill`] instead. You only need toFocuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text.+When [`option: namedKeys`] is `true`, anything inside `{}` is treated as a key name (same format as [`method: Locator.press`]).+To press a special key, like `Control` or `ArrowDown`, use [`method: Locator.press`].**Usage**@@ -2110,26 +2112,43 @@ To press a special key, like `Control` or `ArrowDown`, use [`method: Locator.pre```jsawait locator.pressSequentially('Hello'); // Types instantlyawait locator.pressSequentially('World', { delay: 100 }); // Types slower, like a user++// Mix characters and named keys+await locator.pressSequentially('Hello{Enter}World', { namedKeys: true });+// Use modifier combos+await locator.pressSequentially('{Control+A}{Delete}Hello', { namedKeys: true });``````javalocator.pressSequentially("Hello"); // Types instantlylocator.pressSequentially("World", new Locator.pressSequentiallyOptions().setDelay(100)); // Types slower, like a user++// Mix characters and named keys+locator.pressSequentially("Hello{Enter}World", new Locator.pressSequentiallyOptions().setNamedKeys(true));``````python asyncawait locator.press_sequentially("hello") # types instantlyawait locator.press_sequentially("world", delay=100) # types slower, like a user++# Mix characters and named keys+await locator.press_sequentially("Hello{Enter}World", named_keys=True)``````python synclocator.press_sequentially("hello") # types instantlylocator.press_sequentially("world", delay=100) # types slower, like a user++# Mix characters and named keys+locator.press_sequentially("Hello{Enter}World", named_keys=True)``````csharpawait locator.PressSequentiallyAsync("Hello"); // Types instantlyawait locator.PressSequentiallyAsync("World", new() { Delay = 100 }); // Types slower, like a user++// Mix characters and named keys+await locator.PressSequentiallyAsync("Hello{Enter}World", new() { NamedKeys = true });```An example of typing into a text field and then submitting the form:@@ -2168,7 +2187,7 @@ await locator.PressAsync("Enter");* since: v1.38- `text` <[string]>-String of characters to sequentially press into a focused element.+String of characters to sequentially press into a focused element. When [`option: namedKeys`] is `true`, anything inside `{}` is treated as a key name (same format as [`method: Locator.press`]).### option: Locator.pressSequentially.delay* since: v1.38@@ -2176,6 +2195,13 @@ String of characters to sequentially press into a focused element.Time to wait between key presses in milliseconds. Defaults to 0.+### option: Locator.pressSequentially.namedKeys+* since: v1.61+- `namedKeys` <[boolean]>++When [`option: namedKeys`] is `true`, anything inside `{}` is treated as a key name (same format as [`method: Locator.press`]).+Use `{{` to type a literal brace character. Defaults to `false`.+### option: Locator.pressSequentially.noWaitAfter = %%-input-no-wait-after-removed-%%* since: v1.38diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.tsindex 6939caf9d4..cde7893fa4 100644--- a/packages/playwright-client/types/types.d.ts+++ b/packages/playwright-client/types/types.d.ts@@ -14731,6 +14731,10 @@ export interface Locator {* Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the* text.*+ * When [`namedKeys`](https://playwright.dev/docs/api/class-locator#locator-press-sequentially-option-named-keys) is+ * `true`, anything inside `{}` is treated as a key name (same format as+ * [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press)).+ ** To press a special key, like `Control` or `ArrowDown`, use* [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press).*@@ -14739,6 +14743,11 @@ export interface Locator {* ```js* await locator.pressSequentially('Hello'); // Types instantly* await locator.pressSequentially('World', { delay: 100 }); // Types slower, like a user+ *+ * // Mix characters and named keys+ * await locator.pressSequentially('Hello{Enter}World', { namedKeys: true });+ * // Use modifier combos+ * await locator.pressSequentially('{Control+A}{Delete}Hello', { namedKeys: true });* ```** An example of typing into a text field and then submitting the form:@@ -14749,7 +14758,10 @@ export interface Locator {* await locator.press('Enter');* ```*- * @param text String of characters to sequentially press into a focused element.+ * @param text String of characters to sequentially press into a focused element. When+ * [`namedKeys`](https://playwright.dev/docs/api/class-locator#locator-press-sequentially-option-named-keys) is+ * `true`, anything inside `{}` is treated as a key name (same format as+ * [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press)).* @param options*/pressSequentially(text: string, options?: {@@ -14758,6 +14770,14 @@ export interface Locator {*/delay?: number;+ /**+ * When [`namedKeys`](https://playwright.dev/docs/api/class-locator#locator-press-sequentially-option-named-keys) is+ * `true`, anything inside `{}` is treated as a key name (same format as+ * [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press)). Use `{{` to type a+ * literal brace character. Defaults to `false`.+ */+ namedKeys?: boolean;+/*** This option has no effect.* @deprecated This option has no effect.@@ -20337,6 +20357,10 @@ export interface Keyboard {** Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text.*+ * When [`namedKeys`](https://playwright.dev/docs/api/class-keyboard#keyboard-type-option-named-keys) is `true`,+ * anything inside `{}` is treated as a key name (same format as+ * [keyboard.press(key[, options])](https://playwright.dev/docs/api/class-keyboard#keyboard-press)).+ ** To press a special key, like `Control` or `ArrowDown`, use* [keyboard.press(key[, options])](https://playwright.dev/docs/api/class-keyboard#keyboard-press).*@@ -20345,6 +20369,9 @@ export interface Keyboard {* ```js* await page.keyboard.type('Hello'); // Types instantly* await page.keyboard.type('World', { delay: 100 }); // Types slower, like a user+ *+ * // Mix text and special keys+ * await page.keyboard.type('Hello{Enter}World', { namedKeys: true });* ```** **NOTE** Modifier keys DO NOT effect `keyboard.type`. Holding down `Shift` will not type the text in upper case.@@ -20359,6 +20386,14 @@ export interface Keyboard {* Time to wait between key presses in milliseconds. Defaults to 0.*/delay?: number;++ /**+ * When [`namedKeys`](https://playwright.dev/docs/api/class-keyboard#keyboard-type-option-named-keys) is `true`,+ * anything inside `{}` is treated as a key name (same format as+ * [keyboard.press(key[, options])](https://playwright.dev/docs/api/class-keyboard#keyboard-press)). Use `{{` to type+ * a literal brace character. Defaults to `false`.+ */+ namedKeys?: boolean;}): Promise<void>;/**diff --git a/packages/playwright-core/src/protocol/validator.ts b/packages/playwright-core/src/protocol/validator.tsindex ccfddb497a..a7f4ffd992 100644--- a/packages/playwright-core/src/protocol/validator.ts+++ b/packages/playwright-core/src/protocol/validator.ts@@ -1600,6 +1600,7 @@ scheme.FrameTypeParams = tObject({strict: tOptional(tBoolean),text: tString,delay: tOptional(tFloat),+ namedKeys: tOptional(tBoolean),timeout: tFloat,});scheme.FrameTypeResult = tOptional(tObject({}));@@ -2482,6 +2483,7 @@ scheme.PageKeyboardInsertTextResult = tOptional(tObject({}));scheme.PageKeyboardTypeParams = tObject({text: tString,delay: tOptional(tFloat),+ namedKeys: tOptional(tBoolean),});scheme.PageKeyboardTypeResult = tOptional(tObject({}));scheme.PageKeyboardPressParams = tObject({diff --git a/packages/playwright-core/src/server/dom.ts b/packages/playwright-core/src/server/dom.tsindex f290aec392..bd0f24e8cc 100644--- a/packages/playwright-core/src/server/dom.ts+++ b/packages/playwright-core/src/server/dom.ts@@ -772,13 +772,13 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {return await progress.race(this.evaluateInUtility(([injected, node]) => injected.blurNode(node), {}));}- async type(progress: Progress, text: string, options: { delay?: number } & types.StrictOptions): Promise<void> {+ async type(progress: Progress, text: string, options: { delay?: number, namedKeys?: boolean } & types.StrictOptions): Promise<void> {await this._markAsTargetElement(progress);const result = await this._type(progress, text, options);return assertDone(throwRetargetableDOMError(result));}- async _type(progress: Progress, text: string, options: { delay?: number } & types.StrictOptions): Promise<'error:notconnected' | 'done'> {+ async _type(progress: Progress, text: string, options: { delay?: number, namedKeys?: boolean } & types.StrictOptions): Promise<'error:notconnected' | 'done'> {progress.log(`elementHandle.type("${text}")`);await progress.race(this.instrumentation.onBeforeInputAction(this, progress.metadata));const result = await this._focus(progress, true /* resetSelectionIfNotFocused */);diff --git a/packages/playwright-core/src/server/frames.ts b/packages/playwright-core/src/server/frames.tsindex a80da1d858..4afb08a9d0 100644--- a/packages/playwright-core/src/server/frames.ts+++ b/packages/playwright-core/src/server/frames.ts@@ -1430,7 +1430,7 @@ export class Frame extends SdkObject<FrameEventMap> {dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options, (progress, handle) => handle._drop(progress, inputFileItems, data, options)));}- async type(progress: Progress, selector: string, text: string, options: { delay?: number, noAutoWaiting?: boolean } & types.StrictOptions) {+ async type(progress: Progress, selector: string, text: string, options: { delay?: number, namedKeys?: boolean, noAutoWaiting?: boolean } & types.StrictOptions) {return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options, (progress, handle) => handle._type(progress, text, options)));}diff --git a/packages/playwright-core/src/server/input.ts b/packages/playwright-core/src/server/input.tsindex 74bde697bf..cd69223d0d 100644--- a/packages/playwright-core/src/server/input.ts+++ b/packages/playwright-core/src/server/input.ts@@ -103,20 +103,24 @@ export class Keyboard {await this._raw.sendText(progress, text);}- async apiType(progress: Progress, text: string, options?: { delay?: number }) {+ async apiType(progress: Progress, text: string, options?: { delay?: number, namedKeys?: boolean }) {await progress.race(this._page.instrumentation.onBeforeInputAction(this._page, progress.metadata));await this.type(progress, text, options);}- async type(progress: Progress, text: string, options?: { delay?: number }) {+ async type(progress: Progress, text: string, options?: { delay?: number, namedKeys?: boolean }) {const delay = (options && options.delay) || undefined;- for (const char of text) {- if (usKeyboardLayout.has(char)) {- await this.press(progress, char, { delay });+ for (const token of parseNamedKeys(text, !!options?.namedKeys)) {+ if (token.type === 'key') {+ await this.press(progress, token.value, { delay });} else {- if (delay)- await progress.wait(delay);- await this.insertText(progress, char);+ if (usKeyboardLayout.has(token.value)) {+ await this.press(progress, token.value, { delay });+ } else {+ if (delay)+ await progress.wait(delay);+ await this.insertText(progress, token.value);+ }}}}@@ -354,6 +358,34 @@ function buildLayoutClosure(layout: keyboardLayout.KeyboardLayout): Map<string,return result;}+function parseNamedKeys(text: string, namedKeys: boolean): Array<{ type: 'key' | 'char', value: string }> {+ if (!namedKeys)+ return [...text].map(value => ({ type: 'char' as const, value }));+ const result: Array<{ type: 'key' | 'char', value: string }> = [];+ let i = 0;+ while (i < text.length) {+ if (text[i] === '{') {+ if (i + 1 < text.length && text[i + 1] === '{') {+ result.push({ type: 'char', value: '{' });+ i += 2;+ } else {+ const end = text.indexOf('}', i + 1);+ if (end === -1) {+ result.push({ type: 'char', value: '{' });+ i += 1;+ } else {+ result.push({ type: 'key', value: text.substring(i + 1, end) });+ i = end + 1;+ }+ }+ } else {+ result.push({ type: 'char', value: text[i] });+ i += 1;+ }+ }+ return result;+}+export interface RawTouchscreen {tap(progress: Progress, x: number, y: number, modifiers: Set<types.KeyboardModifier>): Promise<void>;}diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.tsindex 6939caf9d4..cde7893fa4 100644--- a/packages/playwright-core/types/types.d.ts+++ b/packages/playwright-core/types/types.d.ts@@ -14731,6 +14731,10 @@ export interface Locator {* Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the* text.*+ * When [`namedKeys`](https://playwright.dev/docs/api/class-locator#locator-press-sequentially-option-named-keys) is+ * `true`, anything inside `{}` is treated as a key name (same format as+ * [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press)).+ ** To press a special key, like `Control` or `ArrowDown`, use* [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press).*@@ -14739,6 +14743,11 @@ export interface Locator {* ```js* await locator.pressSequentially('Hello'); // Types instantly* await locator.pressSequentially('World', { delay: 100 }); // Types slower, like a user+ *+ * // Mix characters and named keys+ * await locator.pressSequentially('Hello{Enter}World', { namedKeys: true });+ * // Use modifier combos+ * await locator.pressSequentially('{Control+A}{Delete}Hello', { namedKeys: true });* ```** An example of typing into a text field and then submitting the form:@@ -14749,7 +14758,10 @@ export interface Locator {* await locator.press('Enter');* ```*- * @param text String of characters to sequentially press into a focused element.+ * @param text String of characters to sequentially press into a focused element. When+ * [`namedKeys`](https://playwright.dev/docs/api/class-locator#locator-press-sequentially-option-named-keys) is+ * `true`, anything inside `{}` is treated as a key name (same format as+ * [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press)).* @param options*/pressSequentially(text: string, options?: {@@ -14758,6 +14770,14 @@ export interface Locator {*/delay?: number;+ /**+ * When [`namedKeys`](https://playwright.dev/docs/api/class-locator#locator-press-sequentially-option-named-keys) is+ * `true`, anything inside `{}` is treated as a key name (same format as+ * [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press)). Use `{{` to type a+ * literal brace character. Defaults to `false`.+ */+ namedKeys?: boolean;+/*** This option has no effect.* @deprecated This option has no effect.@@ -20337,6 +20357,10 @@ export interface Keyboard {** Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text.*+ * When [`namedKeys`](https://playwright.dev/docs/api/class-keyboard#keyboard-type-option-named-keys) is `true`,+ * anything inside `{}` is treated as a key name (same format as+ * [keyboard.press(key[, options])](https://playwright.dev/docs/api/class-keyboard#keyboard-press)).+ ** To press a special key, like `Control` or `ArrowDown`, use* [keyboard.press(key[, options])](https://playwright.dev/docs/api/class-keyboard#keyboard-press).*@@ -20345,6 +20369,9 @@ export interface Keyboard {* ```js* await page.keyboard.type('Hello'); // Types instantly* await page.keyboard.type('World', { delay: 100 }); // Types slower, like a user+ *+ * // Mix text and special keys+ * await page.keyboard.type('Hello{Enter}World', { namedKeys: true });* ```** **NOTE** Modifier keys DO NOT effect `keyboard.type`. Holding down `Shift` will not type the text in upper case.@@ -20359,6 +20386,14 @@ export interface Keyboard {* Time to wait between key presses in milliseconds. Defaults to 0.*/delay?: number;++ /**+ * When [`namedKeys`](https://playwright.dev/docs/api/class-keyboard#keyboard-type-option-named-keys) is `true`,+ * anything inside `{}` is treated as a key name (same format as+ * [keyboard.press(key[, options])](https://playwright.dev/docs/api/class-keyboard#keyboard-press)). Use `{{` to type+ * a literal brace character. Defaults to `false`.+ */+ namedKeys?: boolean;}): Promise<void>;/**diff --git a/packages/protocol/spec/frame.yml b/packages/protocol/spec/frame.ymlindex e4c8ef0ffd..4c92922cdf 100644--- a/packages/protocol/spec/frame.yml+++ b/packages/protocol/spec/frame.yml@@ -681,6 +681,7 @@ Frame:strict: boolean?text: stringdelay: float?+ namedKeys: boolean?timeout: floatflags:slowMo: truediff --git a/packages/protocol/spec/page.yml b/packages/protocol/spec/page.ymlindex 77c0d94d64..c1b077c04b 100644--- a/packages/protocol/spec/page.yml+++ b/packages/protocol/spec/page.yml@@ -303,6 +303,7 @@ Page:parameters:text: stringdelay: float?+ namedKeys: boolean?flags:slowMo: truesnapshot: truediff --git a/packages/protocol/src/channels.d.ts b/packages/protocol/src/channels.d.tsindex 6729812696..f1e8d0c685 100644--- a/packages/protocol/src/channels.d.ts+++ b/packages/protocol/src/channels.d.ts@@ -2933,11 +2933,13 @@ export type FrameTypeParams = {strict?: boolean,text: string,delay?: number,+ namedKeys?: boolean,timeout: number,};export type FrameTypeOptions = {strict?: boolean,delay?: number,+ namedKeys?: boolean,};export type FrameTypeResult = void;export type FrameUncheckParams = {@@ -4415,9 +4417,11 @@ export type PageKeyboardInsertTextResult = void;export type PageKeyboardTypeParams = {text: string,delay?: number,+ namedKeys?: boolean,};export type PageKeyboardTypeOptions = {delay?: number,+ namedKeys?: boolean,};export type PageKeyboardTypeResult = void;export type PageKeyboardPressParams = {diff --git a/tests/page/page-keyboard.spec.ts b/tests/page/page-keyboard.spec.tsindex bcef21205a..954b590c51 100644--- a/tests/page/page-keyboard.spec.ts+++ b/tests/page/page-keyboard.spec.ts@@ -757,3 +757,19 @@ it('should close dialog on Escape key press in contenteditable', {await expect(dialog).toHaveJSProperty('open', false);await expect(widget).not.toBeVisible();});++it('should type with namedKeys', async ({ page }) => {+ await page.evaluate(() => {+ const textarea = document.createElement('textarea');+ document.body.appendChild(textarea);+ textarea.focus();+ });+ await page.keyboard.type('He{{ll}o{Enter}Wor{ld', { namedKeys: true });+ expect(await page.evaluate(() => document.querySelector('textarea')!.value)).toBe('He{ll}o\nWor{ld');+});++it('locator should pressSequentially with namedKeys', async ({ page }) => {+ await page.setContent(`<textarea></textarea>`);+ await page.locator('textarea').pressSequentially('Hello{Enter}World', { namedKeys: true });+ expect(await page.$eval('textarea', el => el.value)).toBe('Hello\nWorld');+});