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
fix(webview): dispatch key events in their own tasks (#41056)
Yury Semikhatskydc51ddbeb834
diff --git a/packages/injected/src/webview/webViewInput.ts b/packages/injected/src/webview/webViewInput.tsindex 4b293c0059..886eb30cd5 100644--- a/packages/injected/src/webview/webViewInput.ts+++ b/packages/injected/src/webview/webViewInput.ts@@ -117,6 +117,17 @@ export class WebViewInput {this._document = document;}+ // Real input events are each delivered in their own event-loop task; dispatch+ // a sequence the same way so handlers that schedule work between events behave+ // as they would on a real device. Timers come from the globals snapshot (taken+ // at bootstrap), so a page overriding setTimeout cannot break scheduling.+ private _nextTask(): Promise<void> {+ const builtins = (this._window as any).__pwSnapshotGlobals || this._window;+ // setImmediate avoids setTimeout's clamping, but WebKit does not implement it.+ const schedule = builtins.setImmediate || builtins.setTimeout;+ return new Promise(resolve => schedule.call(this._window, resolve));+ }+// Descend through open shadow roots so synthetic events land on the actual// element under the pointer rather than on the shadow host.private _deepElementFromPoint(x: number, y: number): Element | null {@@ -155,7 +166,7 @@ export class WebViewInput {}}- keydown(params: KeyEventParams) {+ keydown(params: KeyEventParams): void | Promise<void> {const target = this._deepActiveElement() || this._document.body;if (!target)return;@@ -175,17 +186,25 @@ export class WebViewInput {metaKey: params.metaKey,};const notPrevented = dispatchKeyEvent(target, 'keydown', init, params.keyCode, params.key);- if (params.text === undefined)+ // Non-text keys produce only keydown; a cancelled keydown also suppresses the+ // keypress and the default text insertion.+ if (params.text === undefined || !notPrevented)return;- const charCode = params.text.charCodeAt(0);+ return this._typeCharacter(target, init, params.text);+ }++ private async _typeCharacter(target: EventTarget, init: KeyboardEventInit, text: string) {+ await this._nextTask();+ const charCode = text.charCodeAt(0);const charNotPrevented = markAndDispatch(target, new KeyboardEvent('keypress', { ...init, charCode, keyCode: charCode, which: charCode }));- if (!notPrevented || !charNotPrevented)+ if (!charNotPrevented)return;+ await this._nextTask();// Real WebKit fires a `textInput` (TextEvent) whose default action performs// the insertion (and the subsequent beforeinput/input). Replicate it; the// event's default does the insertion, so we do not insert manually. Enter's// text is '\r' but the inserted/textInput data is a newline.- this._dispatchTextInput(target, params.text === '\r' ? '\n' : params.text);+ this._dispatchTextInput(target, text === '\r' ? '\n' : text);}private _dispatchTextInput(target: EventTarget, text: string) {diff --git a/packages/playwright-core/src/server/javascript.ts b/packages/playwright-core/src/server/javascript.tsindex 20b247e31a..970dfb5caa 100644--- a/packages/playwright-core/src/server/javascript.ts+++ b/packages/playwright-core/src/server/javascript.ts@@ -377,8 +377,14 @@ const snapshottedFunctionBuiltins = [// Non-callable globals (objects) — Prototype.js historically replaced JSON.const snapshottedObjectBuiltins = ['JSON', 'Math'];+// Timer builtins are routinely overridden by frameworks and fake-timer shims; the+// snapshot lets injected code schedule real tasks regardless. They are only added+// to the snapshot object below, not to the main-world `const` block, so they never+// shadow timers inside the injected bundle. (setImmediate is absent in most engines.)+const snapshottedTimerBuiltins = ['setTimeout', 'setImmediate'];+export const saveGlobalsSnapshotSource = `window.__pwSnapshotGlobals = {-${[...snapshottedFunctionBuiltins, ...snapshottedObjectBuiltins].map(n => ` ${n}: window.${n}`).join(',\n')}+${[...snapshottedFunctionBuiltins, ...snapshottedObjectBuiltins, ...snapshottedTimerBuiltins].map(n => ` ${n}: window.${n}`).join(',\n')}};`;export const mainWorldGlobalsSnapshotSource = `diff --git a/packages/playwright-core/src/server/webkit/webview/wvInput.ts b/packages/playwright-core/src/server/webkit/webview/wvInput.tsindex 526ba8e297..32ef4b46a8 100644--- a/packages/playwright-core/src/server/webkit/webview/wvInput.ts+++ b/packages/playwright-core/src/server/webkit/webview/wvInput.ts@@ -140,5 +140,17 @@ async function callWebViewInput(progress: Progress, session: WVSession | undefinif (!session)throw new Error('Page is not initialized');const expression = `window.__pwWebViewInput.${method}(${JSON.stringify(arg)})`;- await progress.race(session.send('Runtime.evaluate', { expression, returnByValue: true } as any));+ // Some dispatchers are async — they spread events across event-loop tasks the+ // way a real device does. Await the returned promise so the action only+ // resolves once every event has been delivered. Stock WebKit's Runtime.evaluate+ // has no awaitPromise option, so use the separate Runtime.awaitPromise command.+ const { result } = await progress.race(session.send('Runtime.evaluate', { expression, returnByValue: false }));+ // `result` is absent if evaluation failed (e.g. the frame navigated away).+ // Only promises carry an objectId here — every __pwWebViewInput method returns+ // void or a Promise — so this both awaits async dispatch and avoids leaking a+ // handle for the synchronous (void) case.+ if (result?.className === 'Promise' && result.objectId) {+ await progress.race(session.send('Runtime.awaitPromise', { promiseObjectId: result.objectId, returnByValue: true }));+ session.sendMayFail('Runtime.releaseObject', { objectId: result.objectId });+ }}diff --git a/tests/page/page-keyboard.spec.ts b/tests/page/page-keyboard.spec.tsindex 56f879afb2..8d29c64c96 100644--- a/tests/page/page-keyboard.spec.ts+++ b/tests/page/page-keyboard.spec.ts@@ -98,6 +98,23 @@ it('should emit keydown, keypress, textInput and input when typing a character',expect(await events.jsonValue()).toEqual(['keydown', 'keypress', 'textInput', 'input', 'keyup']);});+it('should dispatch key events in separate tasks', async ({ page, browserName }) => {+ it.skip(browserName === 'firefox', 'Firefox dispatches keydown and keypress in the same task');+ await page.setContent(`<input>`);+ const log = await page.evaluateHandle(() => {+ const log: string[] = [];+ const input = document.querySelector('input');+ for (const type of ['keydown', 'keypress'])+ input.addEventListener(type, () => { log.push(type); queueMicrotask(() => log.push('microtask-' + type)); });+ input.focus();+ return log;+ });+ await page.keyboard.press('a');+ // A microtask scheduled in the keydown handler must run before keypress,+ // proving each event is delivered in its own task rather than synchronously.+ expect(await log.jsonValue()).toEqual(['keydown', 'microtask-keydown', 'keypress', 'microtask-keypress']);+});+it('should report shiftKey', async ({ page, server, browserName, platform }) => {it.fail(browserName === 'firefox' && platform === 'darwin');