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: add pierceFrames() locator API (#41963)
Dmitry Gozman7ffedf3c1f6a
diff --git a/docs/src/api/class-frame.md b/docs/src/api/class-frame.mdindex 6a12420848..5295065f84 100644--- a/docs/src/api/class-frame.md+++ b/docs/src/api/class-frame.md@@ -1439,6 +1439,46 @@ Returns the page containing this frame.Parent frame, if any. Detached frames and main frames return `null`.+## method: Frame.pierceFrames+* since: v1.63+- returns: <[FrameLocator]>++When working with iframes, you can create a frame locator that will search for elements in the main frame+and in all iframes on the page, so that you don't need to locate each iframe first.++Note that all elements matching the locator must belong to a single frame. For example, if the page contains+two iframes, each with a `Submit` button, piercing frames and locating a button will throw an error+because it matches elements from multiple frames.++**Usage**++Following snippet locates a button, either in the main frame or in one of the iframes:++```js+const locator = frame.pierceFrames().getByRole('button');+await locator.click();+```++```java+Locator locator = frame.pierceFrames().getByRole(AriaRole.BUTTON);+locator.click();+```++```python async+locator = frame.pierce_frames.get_by_role("button")+await locator.click()+```++```python sync+locator = frame.pierce_frames.get_by_role("button")+locator.click()+```++```csharp+var locator = frame.PierceFrames.GetByRole(AriaRole.Button);+await locator.ClickAsync();+```+## async method: Frame.press* since: v1.8* discouraged: Use locator-based [`method: Locator.press`] instead. Read more about [locators](../locators.md).diff --git a/docs/src/api/class-page.md b/docs/src/api/class-page.mdindex 7771df0eef..bb0b594f61 100644--- a/docs/src/api/class-page.md+++ b/docs/src/api/class-page.md@@ -2358,7 +2358,7 @@ last redirect. If cannot go back, returns `null`.Navigate to the previous page in history.:::warning-**Testing Back/Forward Cache (BFCache) is not supported.**+**Testing Back/Forward Cache (BFCache) is not supported.**By default, Playwright disables the Back/Forward Cache across all browsers. Even if explicitly enabled, Playwright's internal state relies on network-level navigation events. Because BFCache restores unfreeze the DOM without firing these events, using `page.goBack()` or `page.goForward()` to trigger a BFCache restore will result in timeouts and a desynchronized `Page` state.:::@@ -2383,7 +2383,7 @@ last redirect. If cannot go forward, returns `null`.Navigate to the next page in history.:::warning-**Testing Back/Forward Cache (BFCache) is not supported.**+**Testing Back/Forward Cache (BFCache) is not supported.**By default, Playwright disables the Back/Forward Cache across all browsers. Even if explicitly enabled, Playwright's internal state relies on network-level navigation events. Because BFCache restores unfreeze the DOM without firing these events, using `page.goBack()` or `page.goForward()` to trigger a BFCache restore will result in timeouts and a desynchronized `Page` state.:::@@ -3162,6 +3162,46 @@ var locator = await page.PickLocatorAsync();Console.WriteLine(locator);```+## method: Page.pierceFrames+* since: v1.63+- returns: <[FrameLocator]>++When working with iframes, you can create a frame locator that will search for elements in the main frame+and in all iframes on the page, so that you don't need to locate each iframe first.++Note that all elements matching the locator must belong to a single frame. For example, if the page contains+two iframes, each with a `Submit` button, piercing frames and locating a button will throw an error+because it matches elements from multiple frames.++**Usage**++Following snippet locates a button, either in the main frame or in one of the iframes:++```js+const locator = page.pierceFrames().getByRole('button');+await locator.click();+```++```java+Locator locator = page.pierceFrames().getByRole(AriaRole.BUTTON);+locator.click();+```++```python async+locator = page.pierce_frames.get_by_role("button")+await locator.click()+```++```python sync+locator = page.pierce_frames.get_by_role("button")+locator.click()+```++```csharp+var locator = page.PierceFrames.GetByRole(AriaRole.Button);+await locator.ClickAsync();+```+## async method: Page.press* since: v1.8* discouraged: Use locator-based [`method: Locator.press`] instead. Read more about [locators](../locators.md).diff --git a/packages/isomorphic/locatorGenerators.ts b/packages/isomorphic/locatorGenerators.tsindex 744b7a69cc..9bb9d31814 100644--- a/packages/isomorphic/locatorGenerators.ts+++ b/packages/isomorphic/locatorGenerators.ts@@ -21,7 +21,7 @@ import type { NestedSelectorBody } from './selectorParser';import type { ParsedSelector } from './selectorParser';export type Language = 'javascript' | 'python' | 'java' | 'csharp' | 'jsonl';-export type LocatorType = 'default' | 'role' | 'text' | 'label' | 'placeholder' | 'alt' | 'title' | 'test-id' | 'nth' | 'first' | 'last' | 'visible' | 'has-text' | 'has-not-text' | 'has' | 'hasNot' | 'frame' | 'frame-locator' | 'and' | 'or' | 'chain';+export type LocatorType = 'default' | 'role' | 'text' | 'label' | 'placeholder' | 'alt' | 'title' | 'test-id' | 'nth' | 'first' | 'last' | 'visible' | 'has-text' | 'has-not-text' | 'has' | 'hasNot' | 'frame' | 'frame-locator' | 'pierce-frames' | 'and' | 'or' | 'chain';export type LocatorBase = 'page' | 'locator' | 'frame-locator';export type Quote = '\'' | '"' | '`';@@ -205,6 +205,11 @@ function innerAsLocators(factory: LocatorFactory, parsed: ParsedSelector, isFramcontinue;}}+ if (part.name === 'internal:control' && (part.body as string) === 'pierce-frames') {+ tokens.push([factory.generateLocator(base, 'pierce-frames', '')]);+ nextBase = 'frame-locator';+ continue;+ }if (part.name === 'internal:control' && (part.body as string) === 'enter-frame') {// transform last tokens from `${selector}` into `${selector}.contentFrame()` and `frameLocator(${selector})`const lastTokens = tokens[tokens.length - 1];@@ -315,6 +320,8 @@ export class JavaScriptLocatorFactory implements LocatorFactory {return `frameLocator(${this.quote(body as string)})`;case 'frame':return `contentFrame()`;+ case 'pierce-frames':+ return `pierceFrames()`;case 'nth':return `nth(${body})`;case 'first':@@ -414,6 +421,8 @@ export class PythonLocatorFactory implements LocatorFactory {return `frame_locator(${this.quote(body as string)})`;case 'frame':return `content_frame`;+ case 'pierce-frames':+ return `pierce_frames`;case 'nth':return `nth(${body})`;case 'first':@@ -526,6 +535,8 @@ export class JavaLocatorFactory implements LocatorFactory {return `frameLocator(${this.quote(body as string)})`;case 'frame':return `contentFrame()`;+ case 'pierce-frames':+ return `pierceFrames()`;case 'nth':return `nth(${body})`;case 'first':@@ -628,6 +639,8 @@ export class CSharpLocatorFactory implements LocatorFactory {return `FrameLocator(${this.quote(body as string)})`;case 'frame':return `ContentFrame`;+ case 'pierce-frames':+ return `PierceFrames`;case 'nth':return `Nth(${body})`;case 'first':diff --git a/packages/isomorphic/locatorParser.ts b/packages/isomorphic/locatorParser.tsindex 35212cc571..fcb417b556 100644--- a/packages/isomorphic/locatorParser.ts+++ b/packages/isomorphic/locatorParser.ts@@ -78,6 +78,7 @@ function parseLocator(locator: string, testIdAttributeName: string): { selector:.replace(/has_not/g, 'hasnot').replace(/frame_locator/g, 'framelocator').replace(/content_frame/g, 'contentframe')+ .replace(/pierce_frames/g, 'pierceframes').replace(/[{}\s]/g, '').replace(/new\(\)/g, '').replace(/new[\w]+\.[\w]+options\(\)/g, '')@@ -159,6 +160,7 @@ function transform(template: string, params: TemplateParams, testIdAttributeName.replace(/\,set([\w]+)\(([^)]+)\)/g, (_, group1, group2) => ',' + group1.toLowerCase() + '=' + group2.toLowerCase()).replace(/framelocator\(([^)]+)\)/g, '$1.internal:control=enter-frame').replace(/contentframe(\(\))?/g, 'internal:control=enter-frame')+ .replace(/pierceframes(\(\))?/g, 'internal:control=pierce-frames').replace(/locator\(([^)]+),hastext=([^),]+)\)/g, 'locator($1).internal:has-text=$2').replace(/locator\(([^)]+),hasnottext=([^),]+)\)/g, 'locator($1).internal:has-not-text=$2').replace(/locator\(([^)]+),hastext=([^),]+)\)/g, 'locator($1).internal:has-text=$2')diff --git a/packages/isomorphic/selectorParser.ts b/packages/isomorphic/selectorParser.tsindex 0e084733c5..17f1edced4 100644--- a/packages/isomorphic/selectorParser.ts+++ b/packages/isomorphic/selectorParser.ts@@ -126,8 +126,11 @@ export function splitSelectorByFrame(selectorText: string): { pierce: boolean, cchunk.capture = i - chunkStartIndex;chunk.parts.push(part);}- if (!chunk.parts.length)+ if (!chunk.parts.length) {+ if (pierce)+ throw new InvalidSelectorError(`Selector cannot be empty when piercing frames, while parsing selector ${selectorText}`);throw new InvalidSelectorError(`Selector cannot end with entering frame, while parsing selector ${selectorText}`);+ }chunks.push(chunk);if (typeof selector.capture === 'number' && typeof chunks[chunks.length - 1].capture !== 'number')throw new InvalidSelectorError(`Can not capture the selector before diving into the frame. Only use * after the last frame has been selected`);diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.tsindex 101f50fe29..eaa024a641 100644--- a/packages/playwright-client/types/types.d.ts+++ b/packages/playwright-client/types/types.d.ts@@ -3293,7 +3293,7 @@ export interface Page {** Navigate to the previous page in history.*- * **NOTE** **Testing Back/Forward Cache (BFCache) is not supported.** By default, Playwright disables the+ * **NOTE** **Testing Back/Forward Cache (BFCache) is not supported.** By default, Playwright disables the* Back/Forward Cache across all browsers. Even if explicitly enabled, Playwright's internal state relies on* network-level navigation events. Because BFCache restores unfreeze the DOM without firing these events, using* `page.goBack()` or `page.goForward()` to trigger a BFCache restore will result in timeouts and a desynchronized@@ -3341,7 +3341,7 @@ export interface Page {** Navigate to the next page in history.*- * **NOTE** **Testing Back/Forward Cache (BFCache) is not supported.** By default, Playwright disables the+ * **NOTE** **Testing Back/Forward Cache (BFCache) is not supported.** By default, Playwright disables the* Back/Forward Cache across all browsers. Even if explicitly enabled, Playwright's internal state relies on* network-level navigation events. Because BFCache restores unfreeze the DOM without firing these events, using* `page.goBack()` or `page.goForward()` to trigger a BFCache restore will result in timeouts and a desynchronized@@ -4132,6 +4132,26 @@ export interface Page {*/pickLocator(): Promise<Locator>;+ /**+ * When working with iframes, you can create a frame locator that will search for elements in the main frame and in+ * all iframes on the page, so that you don't need to locate each iframe first.+ *+ * Note that all elements matching the locator must belong to a single frame. For example, if the page contains two+ * iframes, each with a `Submit` button, piercing frames and locating a button will throw an error because it matches+ * elements from multiple frames.+ *+ * **Usage**+ *+ * Following snippet locates a button, either in the main frame or in one of the iframes:+ *+ * ```js+ * const locator = page.pierceFrames().getByRole('button');+ * await locator.click();+ * ```+ *+ */+ pierceFrames(): FrameLocator;+/*** **NOTE** Use locator-based [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press)* instead. Read more about [locators](https://playwright.dev/docs/locators).@@ -8145,6 +8165,26 @@ export interface Frame {*/parentFrame(): null|Frame;+ /**+ * When working with iframes, you can create a frame locator that will search for elements in the main frame and in+ * all iframes on the page, so that you don't need to locate each iframe first.+ *+ * Note that all elements matching the locator must belong to a single frame. For example, if the page contains two+ * iframes, each with a `Submit` button, piercing frames and locating a button will throw an error because it matches+ * elements from multiple frames.+ *+ * **Usage**+ *+ * Following snippet locates a button, either in the main frame or in one of the iframes:+ *+ * ```js+ * const locator = frame.pierceFrames().getByRole('button');+ * await locator.click();+ * ```+ *+ */+ pierceFrames(): FrameLocator;+/*** **NOTE** Use locator-based [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press)* instead. Read more about [locators](https://playwright.dev/docs/locators).diff --git a/packages/playwright-core/src/client/frame.ts b/packages/playwright-core/src/client/frame.tsindex 2b315dd685..7bec0b1290 100644--- a/packages/playwright-core/src/client/frame.ts+++ b/packages/playwright-core/src/client/frame.ts@@ -28,7 +28,7 @@ import { ElementHandle, convertInputFiles, convertSelectOptionValues } from './eimport { AbortError, PlaywrightError } from './errors';import { Events } from './events';import { JSHandle, assertEvaluateOptions, assertMaxArguments, parseResult, serializeArgument, serializeArgumentWithCallbacks } from './jsHandle';-import { FrameLocator, Locator, testIdAttributeName } from './locator';+import { FrameLocator, kPierceFramesSelector, Locator, testIdAttributeName } from './locator';import * as network from './network';import { kLifecycleEvents } from './types';import { Waiter } from './waiter';@@ -397,6 +397,10 @@ export class Frame extends ChannelOwner<channels.FrameChannel> implements api.Frreturn new FrameLocator(this, selector);}+ pierceFrames(): FrameLocator {+ return new FrameLocator(this, kPierceFramesSelector);+ }+async focus(selector: string, options: channels.FrameFocusOptions & TimeoutOptions = {}) {await this._channel.focus({ selector, ...options }, this._timeout(options));}diff --git a/packages/playwright-core/src/client/locator.ts b/packages/playwright-core/src/client/locator.tsindex 078234fd9f..dd58b18101 100644--- a/packages/playwright-core/src/client/locator.ts+++ b/packages/playwright-core/src/client/locator.ts@@ -207,6 +207,8 @@ export class Locator implements api.Locator {}frameLocator(selector: string): FrameLocator {+ if (selectorPiercesFrames(this._selector))+ throw new Error(`Entering frames is not allowed while piercing frames.`);return new FrameLocator(this._frame, this._selector + ' >> ' + selector);}@@ -421,6 +423,12 @@ export class Locator implements api.Locator {}}+export const kPierceFramesSelector = 'internal:control=pierce-frames';++function selectorPiercesFrames(selector: string): boolean {+ return selector === kPierceFramesSelector || selector.startsWith(kPierceFramesSelector + ' >> ');+}+export class FrameLocator implements api.FrameLocator {private _frame: Frame;private _frameSelector: string;@@ -430,12 +438,18 @@ export class FrameLocator implements api.FrameLocator {this._frameSelector = selector;}+ private _childSelector(selector: string): string {+ if (this._frameSelector === kPierceFramesSelector)+ return this._frameSelector + ' >> ' + selector;+ return this._frameSelector + ' >> internal:control=enter-frame >> ' + selector;+ }+locator(selectorOrLocator: string | Locator, options?: LocatorOptions): Locator {if (isString(selectorOrLocator))- return new Locator(this._frame, this._frameSelector + ' >> internal:control=enter-frame >> ' + selectorOrLocator, options);+ return new Locator(this._frame, this._childSelector(selectorOrLocator), options);if (selectorOrLocator._frame !== this._frame)throw new Error(`Locators must belong to the same frame.`);- return new Locator(this._frame, this._frameSelector + ' >> internal:control=enter-frame >> ' + selectorOrLocator._selector, options);+ return new Locator(this._frame, this._childSelector(selectorOrLocator._selector), options);}getByTestId(testId: string | RegExp): Locator {@@ -471,19 +485,27 @@ export class FrameLocator implements api.FrameLocator {}frameLocator(selector: string): FrameLocator {- return new FrameLocator(this._frame, this._frameSelector + ' >> internal:control=enter-frame >> ' + selector);+ if (selectorPiercesFrames(this._frameSelector))+ throw new Error(`Entering frames is not allowed while piercing frames.`);+ return new FrameLocator(this._frame, this._childSelector(selector));+ }++ private _nthSelector(nth: string): string {+ if (selectorPiercesFrames(this._frameSelector))+ throw new Error(`Selecting the nth frame is not allowed while piercing frames.`);+ return this._frameSelector + ` >> nth=${nth}`;}first(): FrameLocator {- return new FrameLocator(this._frame, this._frameSelector + ' >> nth=0');+ return new FrameLocator(this._frame, this._nthSelector('0'));}last(): FrameLocator {- return new FrameLocator(this._frame, this._frameSelector + ` >> nth=-1`);+ return new FrameLocator(this._frame, this._nthSelector('-1'));}nth(index: number): FrameLocator {- return new FrameLocator(this._frame, this._frameSelector + ` >> nth=${index}`);+ return new FrameLocator(this._frame, this._nthSelector(String(index)));}}diff --git a/packages/playwright-core/src/client/page.ts b/packages/playwright-core/src/client/page.tsindex 1227ce1c53..957507a151 100644--- a/packages/playwright-core/src/client/page.ts+++ b/packages/playwright-core/src/client/page.ts@@ -782,6 +782,10 @@ export class Page extends ChannelOwner<channels.PageChannel> implements api.Pagereturn this.mainFrame().frameLocator(selector);}+ pierceFrames(): FrameLocator {+ return this.mainFrame().pierceFrames();+ }+async focus(selector: string, options?: channels.FrameFocusOptions & TimeoutOptions) {return await this._mainFrame.focus(selector, options);}diff --git a/packages/playwright-core/src/server/dialog.ts b/packages/playwright-core/src/server/dialog.tsindex 5afce865e1..e25db0f648 100644--- a/packages/playwright-core/src/server/dialog.ts+++ b/packages/playwright-core/src/server/dialog.ts@@ -16,6 +16,7 @@*/import { assert } from '@isomorphic/assert';+import { EvaluationStalledError } from './errors';import { SdkObject } from './instrumentation';import type { Instrumentation } from './instrumentation';@@ -101,7 +102,7 @@ export class DialogManager {dialogDidOpen(dialog: Dialog) {// Any ongoing evaluations will be stalled until the dialog is closed.for (const frame of dialog.page().frameManager.frames())- frame.invalidateNonStallingEvaluations(new Error('JavaScript dialog interrupted evaluation'));+ frame.invalidateNonStallingEvaluations(new EvaluationStalledError('JavaScript dialog interrupted evaluation'));this._openedDialogs.add(dialog);this._instrumentation.onDialog(dialog);diff --git a/packages/playwright-core/src/server/errors.ts b/packages/playwright-core/src/server/errors.tsindex 6d18b4ddcb..e30e3be9e1 100644--- a/packages/playwright-core/src/server/errors.ts+++ b/packages/playwright-core/src/server/errors.ts@@ -28,6 +28,8 @@ class CustomError extends Error {export class TimeoutError extends CustomError {}+export class EvaluationStalledError extends CustomError {}+export class TargetClosedError extends CustomError {constructor(cause: string | undefined, logs?: string) {super((cause || 'Target page, context or browser has been closed') + (logs || ''));diff --git a/packages/playwright-core/src/server/frameSelectors.ts b/packages/playwright-core/src/server/frameSelectors.tsindex 039e318fdc..27f6d7b554 100644--- a/packages/playwright-core/src/server/frameSelectors.ts+++ b/packages/playwright-core/src/server/frameSelectors.ts@@ -18,6 +18,7 @@ import { InvalidSelectorError, splitSelectorByFrame, stringifySelector, visitAlimport { asLocator } from '@isomorphic/locatorGenerators';import { NonRecoverableDOMError } from './dom';+import { EvaluationStalledError } from './errors';import type { ElementHandle, FrameExecutionContext } from './dom';import type { Frame } from './frames';@@ -306,7 +307,11 @@ export class FrameSelectors {}return { result: evalResult as R | SmartHandle<R> };};- const maybeResult = noStall ? await frame.raceAgainstEvaluationStallingEvents(getResult).catch(() => undefined) : await getResult();+ const maybeResult = noStall ? await frame.raceAgainstEvaluationStallingEvents(getResult).catch(e => {+ if (e instanceof EvaluationStalledError)+ return;+ throw e;+ }) : await getResult();if (!maybeResult)continue;if (aggregatedResult)diff --git a/packages/playwright-core/src/server/frames.ts b/packages/playwright-core/src/server/frames.tsindex ff51799805..c629a81301 100644--- a/packages/playwright-core/src/server/frames.ts+++ b/packages/playwright-core/src/server/frames.ts@@ -28,7 +28,7 @@ import { makeWaitForNextTask } from '@utils/task';import { createGuid } from '@utils/crypto';import { BrowserContext } from './browserContext';import * as dom from './dom';-import { TimeoutError, isTargetClosedError } from './errors';+import { EvaluationStalledError, TimeoutError, isTargetClosedError } from './errors';import { prepareFilesForUpload } from './fileUploadUtils';import { FrameSelectors } from './frameSelectors';import { helper } from './helper';@@ -585,7 +585,7 @@ export class Frame extends SdkObject<FrameEventMap> {_setPendingDocument(documentInfo: DocumentInfo | undefined) {this._pendingDocument = documentInfo;if (documentInfo)- this.invalidateNonStallingEvaluations(new Error('Navigation interrupted the evaluation'));+ this.invalidateNonStallingEvaluations(new EvaluationStalledError('Navigation interrupted the evaluation'));}pendingDocument(): DocumentInfo | undefined {@@ -601,9 +601,9 @@ export class Frame extends SdkObject<FrameEventMap> {async raceAgainstEvaluationStallingEvents<T>(cb: () => Promise<T>): Promise<T> {if (this._pendingDocument)- throw new Error('Frame is currently attempting a navigation');+ throw new EvaluationStalledError('Frame is currently attempting a navigation');if (this._page.browserContext.dialogManager.hasOpenDialogsForPage(this._page))- throw new Error('Open JavaScript dialog prevents evaluation');+ throw new EvaluationStalledError('Open JavaScript dialog prevents evaluation');const promise = new ManualPromise<T>();this._raceAgainstEvaluationStallingEventsPromises.add(promise);@@ -1535,7 +1535,7 @@ export class Frame extends SdkObject<FrameEventMap> {});} catch (e) {const details: ExpectErrorDetails = {};- if (isInvalidSelectorError(e)) {+ if (isInvalidSelectorError(e) || dom.isNonRecoverableDOMError(e)) {details.customErrorMessage = e.message;} else if (js.isJavaScriptErrorInEvaluate(e)) {details.customErrorMessage = e.message.startsWith('Error: ') ? e.message.substring('Error: '.length) : e.message;diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.tsindex 101f50fe29..eaa024a641 100644--- a/packages/playwright-core/types/types.d.ts+++ b/packages/playwright-core/types/types.d.ts@@ -3293,7 +3293,7 @@ export interface Page {** Navigate to the previous page in history.*- * **NOTE** **Testing Back/Forward Cache (BFCache) is not supported.** By default, Playwright disables the+ * **NOTE** **Testing Back/Forward Cache (BFCache) is not supported.** By default, Playwright disables the* Back/Forward Cache across all browsers. Even if explicitly enabled, Playwright's internal state relies on* network-level navigation events. Because BFCache restores unfreeze the DOM without firing these events, using* `page.goBack()` or `page.goForward()` to trigger a BFCache restore will result in timeouts and a desynchronized@@ -3341,7 +3341,7 @@ export interface Page {** Navigate to the next page in history.*- * **NOTE** **Testing Back/Forward Cache (BFCache) is not supported.** By default, Playwright disables the+ * **NOTE** **Testing Back/Forward Cache (BFCache) is not supported.** By default, Playwright disables the* Back/Forward Cache across all browsers. Even if explicitly enabled, Playwright's internal state relies on* network-level navigation events. Because BFCache restores unfreeze the DOM without firing these events, using* `page.goBack()` or `page.goForward()` to trigger a BFCache restore will result in timeouts and a desynchronized@@ -4132,6 +4132,26 @@ export interface Page {*/pickLocator(): Promise<Locator>;+ /**+ * When working with iframes, you can create a frame locator that will search for elements in the main frame and in+ * all iframes on the page, so that you don't need to locate each iframe first.+ *+ * Note that all elements matching the locator must belong to a single frame. For example, if the page contains two+ * iframes, each with a `Submit` button, piercing frames and locating a button will throw an error because it matches+ * elements from multiple frames.+ *+ * **Usage**+ *+ * Following snippet locates a button, either in the main frame or in one of the iframes:+ *+ * ```js+ * const locator = page.pierceFrames().getByRole('button');+ * await locator.click();+ * ```+ *+ */+ pierceFrames(): FrameLocator;+/*** **NOTE** Use locator-based [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press)* instead. Read more about [locators](https://playwright.dev/docs/locators).@@ -8145,6 +8165,26 @@ export interface Frame {*/parentFrame(): null|Frame;+ /**+ * When working with iframes, you can create a frame locator that will search for elements in the main frame and in+ * all iframes on the page, so that you don't need to locate each iframe first.+ *+ * Note that all elements matching the locator must belong to a single frame. For example, if the page contains two+ * iframes, each with a `Submit` button, piercing frames and locating a button will throw an error because it matches+ * elements from multiple frames.+ *+ * **Usage**+ *+ * Following snippet locates a button, either in the main frame or in one of the iframes:+ *+ * ```js+ * const locator = frame.pierceFrames().getByRole('button');+ * await locator.click();+ * ```+ *+ */+ pierceFrames(): FrameLocator;+/*** **NOTE** Use locator-based [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press)* instead. Read more about [locators](https://playwright.dev/docs/locators).diff --git a/tests/library/locator-generator.spec.ts b/tests/library/locator-generator.spec.tsindex fa9a863592..8cc0aec6b6 100644--- a/tests/library/locator-generator.spec.ts+++ b/tests/library/locator-generator.spec.ts@@ -442,6 +442,22 @@ it('reverse engineer frameLocator', async ({ page }) => {expect.soft(asLocator('javascript', selector)).toBe(`locator('div').locator('iframe').contentFrame().locator('span')`);});+it('reverse engineer pierceFrames', async ({ page }) => {+ expect.soft(generate(page.pierceFrames().getByText('foo').locator('span'))).toEqual({+ csharp: `PierceFrames.GetByText("foo").Locator("span")`,+ java: `pierceFrames().getByText("foo").locator("span")`,+ javascript: `pierceFrames().getByText('foo').locator('span')`,+ python: `pierce_frames.get_by_text("foo").locator("span")`,+ });++ // Note that bare `pierce_frames` and `PierceFrames` are not restored back,+ // because they are indistinguishable from a css selector.+ expect.soft(asLocator('javascript', 'internal:control=pierce-frames')).toBe(`pierceFrames()`);+ expect.soft(asLocator('python', 'internal:control=pierce-frames')).toBe(`pierce_frames`);+ expect.soft(asLocator('java', 'internal:control=pierce-frames')).toBe(`pierceFrames()`);+ expect.soft(asLocator('csharp', 'internal:control=pierce-frames')).toBe(`PierceFrames`);+});+it('generate multiple locators', async ({ page }) => {const selector = (page.locator('div', { hasText: 'foo' }).nth(0).filter({ has: page.locator('span', { hasNotText: 'bar' }).nth(-1) }) as any)._selector;const locators = {diff --git a/tests/page/locator-pierce-frames.spec.ts b/tests/page/locator-pierce-frames.spec.tsnew file mode 100644index 0000000000..08dcba0493--- /dev/null+++ b/tests/page/locator-pierce-frames.spec.ts@@ -0,0 +1,305 @@+/**+ * Copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { Page } from 'playwright-core';+import { test as it, expect } from './pageTest';++function routePage(page: Page, url: string, body: string) {+ return page.route('**/' + url, route => {+ route.fulfill({ body, contentType: 'text/html' }).catch(() => {});+ });+}++async function waitForAllFrames(page: Page, frameCount: number, selector: string) {+ // Wait for all child frames to load their content, so that piercing+ // deterministically sees elements in all of them.+ await expect.poll(() => page.frames().length).toBe(frameCount);+ for (const frame of page.frames()) {+ if (frame !== page.mainFrame())+ await frame.waitForSelector(selector, { state: 'attached' });+ }+}++it('should click a button inside an iframe', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<button onclick="window.__clicked = true">Click me</button>`);+ await page.goto(server.EMPTY_PAGE);+ await page.pierceFrames().getByRole('button', { name: 'Click me' }).click();+ expect(await page.frames()[1].evaluate(() => (window as any).__clicked)).toBe(true);+});++it('should click a button in the main frame', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe><button onclick="window.__clicked = true">Click me</button>`);+ await routePage(page, 'a.html', `<div>No buttons here</div>`);+ await page.goto(server.EMPTY_PAGE);+ await page.pierceFrames().locator('button').click();+ expect(await page.evaluate(() => (window as any).__clicked)).toBe(true);+});++it('should fail click when elements match in multiple frames', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe><iframe src="b.html"></iframe>`);+ await routePage(page, 'a.html', `<button>one</button>`);+ await routePage(page, 'b.html', `<button>two</button>`);+ await page.goto(server.EMPTY_PAGE);+ await waitForAllFrames(page, 3, 'button');+ const error = await page.pierceFrames().locator('button').click({ timeout: 3000 }).catch(e => e);+ expect(error.message).toContain('Pierce-frame mode matched elements from multiple frames');+ expect(error.message).toContain(`waiting for pierceFrames().locator('button')`);+});++it('should fail click upon strict mode violation inside a single frame', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<button>one</button><button>two</button>`);+ await page.goto(server.EMPTY_PAGE);+ await waitForAllFrames(page, 2, 'button');+ const error = await page.pierceFrames().locator('button').click({ timeout: 3000 }).catch(e => e);+ expect(error.message).toContain('strict mode violation');+ expect(error.message).toContain(`waiting for pierceFrames().locator('button')`);+});++it('should time out on click when there are no matches', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<div>Nothing here</div>`);+ await page.goto(server.EMPTY_PAGE);+ const error = await page.pierceFrames().locator('button').click({ timeout: 1000 }).catch(e => e);+ expect(error.message).toContain('Timeout 1000ms exceeded');+ expect(error.message).toContain(`waiting for pierceFrames().locator('button')`);+});++it('should count elements in a single frame', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<div>1</div><div>2</div><div>3</div>`);+ await page.goto(server.EMPTY_PAGE);+ await waitForAllFrames(page, 2, 'div');+ expect(await page.pierceFrames().locator('div').count()).toBe(3);+ expect(await page.pierceFrames().locator('button').count()).toBe(0);+});++it('should fail count when elements match in multiple frames', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<div>main</div><iframe src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<div>child</div>`);+ await page.goto(server.EMPTY_PAGE);+ await waitForAllFrames(page, 2, 'div');+ const error = await page.pierceFrames().locator('div').count().catch(e => e);+ expect(error.message).toContain('Pierce-frame mode matched elements from multiple frames');+});++it('should support toHaveCount', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<span>one</span><span>two</span>`);+ await page.goto(server.EMPTY_PAGE);+ await expect(page.pierceFrames().locator('span')).toHaveCount(2);+ await expect(page.pierceFrames().locator('button')).toHaveCount(0);+});++it('should wait for a frame to appear with toHaveCount', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<div>No frames yet</div>`);+ await routePage(page, 'a.html', `<span>one</span><span>two</span>`);+ await page.goto(server.EMPTY_PAGE);+ await page.evaluate(() => {+ window.builtins.setTimeout(() => {+ const iframe = document.createElement('iframe');+ iframe.src = 'a.html';+ document.body.appendChild(iframe);+ }, 500);+ });+ await expect(page.pierceFrames().locator('span')).toHaveCount(2);+});++it('should fail toHaveCount when elements match in multiple frames', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe><iframe src="b.html"></iframe>`);+ await routePage(page, 'a.html', `<span>one</span>`);+ await routePage(page, 'b.html', `<span>two</span>`);+ await page.goto(server.EMPTY_PAGE);+ await waitForAllFrames(page, 3, 'span');+ const error = await expect(page.pierceFrames().locator('span')).toHaveCount(2, { timeout: 3000 }).catch(e => e);+ expect(error.message).toContain('Pierce-frame mode matched elements from multiple frames');+ expect(error.message).toContain(`Locator: pierceFrames().locator('span')`);+});++it('should support toHaveText', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<div>Hello iframe</div>`);+ await page.goto(server.EMPTY_PAGE);+ await expect(page.pierceFrames().locator('div')).toHaveText('Hello iframe');+});++it('should support toHaveText with an array', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<span>one</span><span>two</span>`);+ await page.goto(server.EMPTY_PAGE);+ await expect(page.pierceFrames().locator('span')).toHaveText(['one', 'two']);+});++it('should fail toHaveText when elements match in multiple frames', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe><iframe src="b.html"></iframe>`);+ await routePage(page, 'a.html', `<div>one</div>`);+ await routePage(page, 'b.html', `<div>two</div>`);+ await page.goto(server.EMPTY_PAGE);+ await waitForAllFrames(page, 3, 'div');+ const error = await expect(page.pierceFrames().locator('div')).toHaveText('one', { timeout: 3000 }).catch(e => e);+ expect(error.message).toContain('Pierce-frame mode matched elements from multiple frames');+ expect(error.message).toContain(`Locator: pierceFrames().locator('div')`);+});++it('should fail toHaveText with an array when elements match in multiple frames', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe><iframe src="b.html"></iframe>`);+ await routePage(page, 'a.html', `<span>one</span>`);+ await routePage(page, 'b.html', `<span>two</span>`);+ await page.goto(server.EMPTY_PAGE);+ await waitForAllFrames(page, 3, 'span');+ const error = await expect(page.pierceFrames().locator('span')).toHaveText(['one', 'two'], { timeout: 3000 }).catch(e => e);+ expect(error.message).toContain('Pierce-frame mode matched elements from multiple frames');+});++it('should fail toHaveText upon strict mode violation inside a single frame', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<div>one</div><div>two</div>`);+ await page.goto(server.EMPTY_PAGE);+ await waitForAllFrames(page, 2, 'div');+ const error = await expect(page.pierceFrames().locator('div')).toHaveText('one', { timeout: 3000 }).catch(e => e);+ expect(error.message).toContain('strict mode violation');+ expect(error.message).toContain(`Locator: pierceFrames().locator('div')`);+});++it('should support evaluate', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<div data-foo="bar">Hello</div>`);+ await page.goto(server.EMPTY_PAGE);+ expect(await page.pierceFrames().locator('div').evaluate(e => e.getAttribute('data-foo'))).toBe('bar');+});++it('should fail evaluate when elements match in multiple frames', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe><iframe src="b.html"></iframe>`);+ await routePage(page, 'a.html', `<div>one</div>`);+ await routePage(page, 'b.html', `<div>two</div>`);+ await page.goto(server.EMPTY_PAGE);+ await waitForAllFrames(page, 3, 'div');+ const error = await page.pierceFrames().locator('div').evaluate(e => e.textContent, undefined, { timeout: 3000 }).catch(e => e);+ expect(error.message).toContain('Pierce-frame mode matched elements from multiple frames');+});++it('should time out on evaluate when there are no matches', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<div>Nothing here</div>`);+ await page.goto(server.EMPTY_PAGE);+ const error = await page.pierceFrames().locator('button').evaluate(e => e.textContent, undefined, { timeout: 1000 }).catch(e => e);+ expect(error.message).toContain('Timeout 1000ms exceeded');+ expect(error.message).toContain(`waiting for pierceFrames().locator('button')`);+});++it('should support evaluateAll', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<span>one</span><span>two</span>`);+ await page.goto(server.EMPTY_PAGE);+ await waitForAllFrames(page, 2, 'span');+ expect(await page.pierceFrames().locator('span').evaluateAll(els => els.map(e => e.textContent))).toEqual(['one', 'two']);+ expect(await page.pierceFrames().locator('button').evaluateAll(els => els.length)).toBe(0);+});++it('should fail evaluateAll when elements match in multiple frames', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe><iframe src="b.html"></iframe>`);+ await routePage(page, 'a.html', `<span>one</span>`);+ await routePage(page, 'b.html', `<span>two</span>`);+ await page.goto(server.EMPTY_PAGE);+ await waitForAllFrames(page, 3, 'span');+ const error = await page.pierceFrames().locator('span').evaluateAll(els => els.length).catch(e => e);+ expect(error.message).toContain('Pierce-frame mode matched elements from multiple frames');+});++it('should support hasText filter', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<div>foo</div><div>bar</div>`);+ await page.goto(server.EMPTY_PAGE);+ await expect(page.pierceFrames().locator('div', { hasText: 'bar' })).toHaveText('bar');+});++it('should support first/last/nth as the last operation', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<span>one</span><span>two</span><span>three</span>`);+ await page.goto(server.EMPTY_PAGE);+ await waitForAllFrames(page, 2, 'span');+ await expect(page.pierceFrames().locator('span').first()).toHaveText('one');+ await expect(page.pierceFrames().locator('span').last()).toHaveText('three');+ await expect(page.pierceFrames().locator('span').nth(1)).toHaveText('two');+});++it('should not allow nth in the middle', async ({ page }) => {+ const error = await page.pierceFrames().locator('div').first().locator('span').count().catch(e => e);+ expect(error.message).toContain(`nth can only be the last locator when piercing frames, while querying "pierceFrames().locator('div').first().locator('span')"`);+});++it('should not allow frameLocator after pierceFrames', async ({ page }) => {+ expect(() => page.pierceFrames().frameLocator('iframe')).toThrow('Entering frames is not allowed while piercing frames');+ expect(() => page.pierceFrames().locator('div').frameLocator('iframe')).toThrow('Entering frames is not allowed while piercing frames');+});++it('should not allow first/last/nth after pierceFrames', async ({ page }) => {+ expect(() => page.pierceFrames().first()).toThrow('Selecting the nth frame is not allowed while piercing frames');+ expect(() => page.pierceFrames().last()).toThrow('Selecting the nth frame is not allowed while piercing frames');+ expect(() => page.pierceFrames().nth(1)).toThrow('Selecting the nth frame is not allowed while piercing frames');+});++it('should not allow chaining pierce-frames and enter-frame selectors', async ({ page }) => {+ const error1 = await page.locator('internal:control=pierce-frames >> iframe >> internal:control=enter-frame >> button').count().catch(e => e);+ expect(error1.message).toContain('Entering frames is not allowed while piercing frames');+ const error2 = await page.locator('iframe >> internal:control=enter-frame >> internal:control=pierce-frames >> button').count().catch(e => e);+ expect(error2.message).toContain('"pierce-frames" is only allowed as the first selector token');+});++it('should not allow composite locators', async ({ page }) => {+ const error = await page.pierceFrames().locator('div', { has: page.locator('span') }).count().catch(e => e);+ expect(error.message).toContain(`Composite locators are not supported with piercing frames, while querying "pierceFrames().locator('div').filter({ has: locator('span') })"`);+});++it('should not allow owner', async ({ page }) => {+ const error = await page.pierceFrames().owner().count().catch(e => e);+ expect(error.message).toContain('Selector cannot be empty when piercing frames');+});++it('should render pierceFrames in the locator description', async ({ page }) => {+ expect(String(page.pierceFrames().locator('button'))).toBe(`pierceFrames().locator('button')`);+ expect(String(page.pierceFrames().getByText('foo'))).toBe(`pierceFrames().getByText('foo')`);+});++it('should click while another iframe is stalled', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe><iframe src="stall.html"></iframe>`);+ await routePage(page, 'a.html', `<button onclick="window.__clicked = true">Click me</button>`);+ await page.route('**/stall.html', () => {});+ await page.goto(server.EMPTY_PAGE, { waitUntil: 'domcontentloaded' });+ await expect.poll(() => page.frames().length).toBe(3);+ await page.pierceFrames().locator('button').click();+ const frame = page.frames().find(f => f.url().includes('a.html'))!;+ expect(await frame.evaluate(() => (window as any).__clicked)).toBe(true);+});++it('should support toBeVisible while another iframe is stalled', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe><iframe src="stall.html"></iframe>`);+ await routePage(page, 'a.html', `<button>Click me</button>`);+ await page.route('**/stall.html', () => {});+ await page.goto(server.EMPTY_PAGE, { waitUntil: 'domcontentloaded' });+ await expect.poll(() => page.frames().length).toBe(3);+ await expect(page.pierceFrames().locator('button')).toBeVisible();+});++it('should support toHaveCount while another iframe is stalled', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe><iframe src="stall.html"></iframe>`);+ await routePage(page, 'a.html', `<button>Click me</button>`);+ await page.route('**/stall.html', () => {});+ await page.goto(server.EMPTY_PAGE, { waitUntil: 'domcontentloaded' });+ await expect.poll(() => page.frames().length).toBe(3);+ await expect(page.pierceFrames().locator('button')).toHaveCount(1);+});