Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

Revert "chore: reduce scrolling during clicks (#36175)" (#36346)

Dmitry Gozman2576ce2917ab
diff --git a/packages/injected/src/injectedScript.ts b/packages/injected/src/injectedScript.ts
index b18251f836..bcc6be892e 100644
--- a/packages/injected/src/injectedScript.ts
+++ b/packages/injected/src/injectedScript.ts
@@ -53,9 +53,8 @@ export type ElementState = 'visible' | 'hidden' | 'enabled' | 'disabled' | 'edit
export type ElementStateWithoutStable = Exclude<ElementState, 'stable'>;
export type ElementStateQueryResult = { matches: boolean, received?: string | 'error:notconnected' };
-export type HitTargetError = { hitTargetDescription: string, hasPositionStickyOrFixed: boolean };
export type HitTargetInterceptionResult = {
- stop: () => 'done' | HitTargetError;
+ stop: () => 'done' | { hitTargetDescription: string };
};
interface WebKitLegacyDeviceOrientationEvent extends DeviceOrientationEvent {
@@ -923,7 +922,7 @@ export class InjectedScript {
input.dispatchEvent(new Event('change', { bubbles: true }));
}
- expectHitTarget(hitPoint: { x: number, y: number }, targetElement: Element): 'done' | HitTargetError {
+ expectHitTarget(hitPoint: { x: number, y: number }, targetElement: Element) {
const roots: (Document | ShadowRoot)[] = [];
// Get all component roots leading to the target element.
@@ -976,21 +975,14 @@ export class InjectedScript {
// Check whether hit target is the target or its descendant.
const hitParents: Element[] = [];
- const isHitParentPositionStickyOrFixed: boolean[] = [];
while (hitElement && hitElement !== targetElement) {
hitParents.push(hitElement);
- isHitParentPositionStickyOrFixed.push(['sticky', 'fixed'].includes(this.window.getComputedStyle(hitElement).position));
hitElement = parentElementOrShadowHost(hitElement);
}
if (hitElement === targetElement)
return 'done';
- // The description of the element that was hit instead of the target element.
const hitTargetDescription = this.previewNode(hitParents[0] || this.document.documentElement);
- // Whether any ancestor of the hit target has position: static. In this case, it could be
- // beneficial to scroll the target element into different positions to reveal it.
- let hasPositionStickyOrFixed = isHitParentPositionStickyOrFixed.some(x => x);
-
// Root is the topmost element in the hitTarget's chain that is not in the
// element's chain. For example, it might be a dialog element that overlays
// the target.
@@ -1001,14 +993,13 @@ export class InjectedScript {
if (index !== -1) {
if (index > 1)
rootHitTargetDescription = this.previewNode(hitParents[index - 1]);
- hasPositionStickyOrFixed = isHitParentPositionStickyOrFixed.slice(0, index).some(x => x);
break;
}
element = parentElementOrShadowHost(element);
}
if (rootHitTargetDescription)
- return { hitTargetDescription: `${hitTargetDescription} from ${rootHitTargetDescription} subtree`, hasPositionStickyOrFixed };
- return { hitTargetDescription, hasPositionStickyOrFixed };
+ return { hitTargetDescription: `${hitTargetDescription} from ${rootHitTargetDescription} subtree` };
+ return { hitTargetDescription };
}
// Life of a pointer action, for example click.
@@ -1041,7 +1032,7 @@ export class InjectedScript {
// 2k. (injected) Event interceptor is removed.
// 2l. All navigations triggered between 2g-2k are awaited to be either committed or canceled.
// 2m. If failed, wait for increasing amount of time before the next retry.
- setupHitTargetInterceptor(node: Node, action: 'hover' | 'tap' | 'mouse' | 'drag', hitPoint: { x: number, y: number } | undefined, blockAllEvents: boolean): HitTargetInterceptionResult | 'error:notconnected' | string /* JSON.stringify(hitTargetDescription) */ {
+ setupHitTargetInterceptor(node: Node, action: 'hover' | 'tap' | 'mouse' | 'drag', hitPoint: { x: number, y: number } | undefined, blockAllEvents: boolean): HitTargetInterceptionResult | 'error:notconnected' | string /* hitTargetDescription */ {
const element = this.retarget(node, 'button-link');
if (!element || !element.isConnected)
return 'error:notconnected';
@@ -1051,7 +1042,7 @@ export class InjectedScript {
// intercepting the action.
const preliminaryResult = this.expectHitTarget(hitPoint, element);
if (preliminaryResult !== 'done')
- return JSON.stringify(preliminaryResult);
+ return preliminaryResult.hitTargetDescription;
}
// When dropping, the "element that is being dragged" often stays under the cursor,
@@ -1066,7 +1057,7 @@ export class InjectedScript {
'tap': this._tapHitTargetInterceptorEvents,
'mouse': this._mouseHitTargetInterceptorEvents,
}[action];
- let result: 'done' | HitTargetError | undefined;
+ let result: 'done' | { hitTargetDescription: string } | undefined;
const listener = (event: PointerEvent | MouseEvent | TouchEvent) => {
// Ignore events that we do not expect to intercept.
diff --git a/packages/playwright-core/src/server/dom.ts b/packages/playwright-core/src/server/dom.ts
index 4697f19aa6..989c31fa38 100644
--- a/packages/playwright-core/src/server/dom.ts
+++ b/packages/playwright-core/src/server/dom.ts
@@ -24,7 +24,7 @@ import { isSessionClosedError } from './protocolError';
import * as rawInjectedScriptSource from '../generated/injectedScriptSource';
import type * as frames from './frames';
-import type { ElementState, HitTargetError, HitTargetInterceptionResult, InjectedScript, InjectedScriptOptions } from '@injected/injectedScript';
+import type { ElementState, HitTargetInterceptionResult, InjectedScript, InjectedScriptOptions } from '@injected/injectedScript';
import type { CallMetadata } from './instrumentation';
import type { Page } from './page';
import type { Progress } from './progress';
@@ -39,7 +39,7 @@ export type InputFilesItems = {
};
type ActionName = 'click' | 'hover' | 'dblclick' | 'tap' | 'move and up' | 'move and down';
-type PerformActionResult = 'error:notvisible' | 'error:notconnected' | 'error:notinviewport' | 'error:optionsnotfound' | { missingState: ElementState } | HitTargetError | 'done';
+type PerformActionResult = 'error:notvisible' | 'error:notconnected' | 'error:notinviewport' | 'error:optionsnotfound' | { missingState: ElementState } | { hitTargetDescription: string } | 'done';
export class NonRecoverableDOMError extends Error {
}
@@ -331,7 +331,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
};
}
- async _retryAction(progress: Progress, actionName: string, action: () => Promise<PerformActionResult>, options: { trial?: boolean, force?: boolean, skipActionPreChecks?: boolean }): Promise<'error:notconnected' | 'done'> {
+ async _retryAction(progress: Progress, actionName: string, action: (retry: number) => Promise<PerformActionResult>, options: { trial?: boolean, force?: boolean, skipActionPreChecks?: boolean }): Promise<'error:notconnected' | 'done'> {
let retry = 0;
// We progressively wait longer between retries, up to 500ms.
const waitTime = [0, 20, 100, 100, 500];
@@ -352,7 +352,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
}
if (!options.skipActionPreChecks && !options.force)
await this._frame._page.performActionPreChecks(progress);
- const result = await action();
+ const result = await action(retry);
++retry;
if (result === 'error:notvisible') {
if (options.force)
@@ -386,25 +386,19 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
options: Omit<{ waitAfter: boolean | 'disabled' } & types.PointerActionOptions & types.PointerActionWaitOptions, 'timeout'>): Promise<'error:notconnected' | 'done'> {
// Note: do not perform locator handlers checkpoint to avoid moving the mouse in the middle of a drag operation.
const skipActionPreChecks = actionName === 'move and up';
- // By default, we scroll with protocol method to reveal the action point.
- // However, that might not work to scroll from under position:sticky and position:fixed elements
- // that overlay the target element. To fight this, we cycle through different
- // scroll alignments. This works in most scenarios.
- const scrollOptions: (ScrollIntoViewOptions | undefined)[] = [
- undefined,
- { block: 'end', inline: 'end' },
- { block: 'center', inline: 'center' },
- { block: 'start', inline: 'start' },
- ];
- let scrollOptionIndex = 0;
- return await this._retryAction(progress, actionName, async () => {
- const forceScrollOptions = scrollOptions[scrollOptionIndex % scrollOptions.length];
- const result = await this._performPointerAction(progress, actionName, waitForEnabled, action, forceScrollOptions, options);
- if (typeof result === 'object' && 'hasPositionStickyOrFixed' in result && result.hasPositionStickyOrFixed)
- ++scrollOptionIndex;
- else
- scrollOptionIndex = 0;
- return result;
+ return await this._retryAction(progress, actionName, async retry => {
+ // By default, we scroll with protocol method to reveal the action point.
+ // However, that might not work to scroll from under position:sticky elements
+ // that overlay the target element. To fight this, we cycle through different
+ // scroll alignments. This works in most scenarios.
+ const scrollOptions: (ScrollIntoViewOptions | undefined)[] = [
+ undefined,
+ { block: 'end', inline: 'end' },
+ { block: 'center', inline: 'center' },
+ { block: 'start', inline: 'start' },
+ ];
+ const forceScrollOptions = scrollOptions[retry % scrollOptions.length];
+ return await this._performPointerAction(progress, actionName, waitForEnabled, action, forceScrollOptions, options);
}, { ...options, skipActionPreChecks });
}
@@ -487,7 +481,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
const error = handle.rawValue() as string;
if (error === 'error:notconnected')
return error;
- return JSON.parse(error) as HitTargetError; // It is safe to parse, because we evaluated in utility.
+ return { hitTargetDescription: error };
}
hitTargetInterceptionHandle = handle as any;
progress.cleanupWhenAborted(() => {
@@ -911,7 +905,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
return this;
}
- async _checkFrameIsHitTarget(point: types.Point): Promise<{ framePoint: types.Point | undefined } | 'error:notconnected' | HitTargetError> {
+ async _checkFrameIsHitTarget(point: types.Point): Promise<{ framePoint: types.Point | undefined } | 'error:notconnected' | { hitTargetDescription: string }> {
let frame = this._frame;
const data: { frame: frames.Frame, frameElement: ElementHandle<Element> | null, pointInFrame: types.Point }[] = [];
while (frame.parentFrame()) {
diff --git a/tests/page/page-click.spec.ts b/tests/page/page-click.spec.ts
index 9a023ade59..b206480740 100644
--- a/tests/page/page-click.spec.ts
+++ b/tests/page/page-click.spec.ts
@@ -419,6 +419,54 @@ it('should click the button behind sticky header', async ({ page }) => {
expect(await page.evaluate(() => window['__clicked'])).toBe(true);
});
+it('should click the button behind position:absolute header', {
+ annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/36339' },
+}, async ({ page }) => {
+ await page.setViewportSize({ width: 500, height: 240 });
+ await page.setContent(`
+ <style>
+ * {
+ padding: 0;
+ margin: 0;
+ }
+ li {
+ height: 80px;
+ border: 1px solid black;
+ }
+ ol {
+ height: 100vh;
+ overflow: scroll;
+ padding-top: 160px;
+ }
+ body {
+ position: relative;
+ }
+ div.fixed {
+ position: absolute;
+ top: 0;
+ z-index: 1001;
+ width: 100%;
+ background: red;
+ height: 160px;
+ }
+ </style>
+
+ <ol>
+ <li>hi1</li><li>hi2</li><li>hi3</li><li>hi4</li><li>hi5</li><li>hi6</li><li>hi7</li><li>hi8</li>
+ <li id=target onclick="window.__clicked = true">hi9</li>
+ <li>hi10</li><li>hi11</li><li>hi12</li><li>hi13</li><li id=li14>hi14</li>
+ </ol>
+
+ <div class=fixed>Overlay</div>
+ `);
+ await page.$eval('ol', e => {
+ const target = document.querySelector('#target') as HTMLElement;
+ e.scrollTo({ top: target.offsetTop, behavior: 'instant' });
+ });
+ await page.click('#target');
+ expect(await page.evaluate(() => window['__clicked'])).toBe(true);
+});
+
it('should click the button with px border with offset', async ({ page, server, browserName }) => {
await page.goto(server.PREFIX + '/input/button.html');
await page.$eval('button', button => button.style.borderWidth = '8px');