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(selectors): support entering frames while piercing (#42031)
Dmitry Gozmand0c1b736b053
diff --git a/packages/isomorphic/selectorParser.ts b/packages/isomorphic/selectorParser.tsindex 17f1edced4..74818985bc 100644--- a/packages/isomorphic/selectorParser.ts+++ b/packages/isomorphic/selectorParser.ts@@ -92,8 +92,8 @@ export function parseSelector(selector: string): ParsedSelector {}// Splits a selector into per-frame chunks separated by "enter-frame" boundaries. When the selector-// starts with the "pierce-frames" token, `pierce` is set globally and no "enter-frame" boundaries-// are allowed (piercing already searches every descendant frame), so `chunks` holds a single chunk.+// starts with the "pierce-frames" token, `pierce` is set globally and "enter-frame" tokens are+// preserved, so `chunks` holds a single chunk.export function splitSelectorByFrame(selectorText: string): { pierce: boolean, chunks: ParsedSelector[] } {const selector = parseSelector(selectorText);const chunks: ParsedSelector[] = [];@@ -113,10 +113,13 @@ export function splitSelectorByFrame(selectorText: string): { pierce: boolean, ccontinue;}if (part.name === 'internal:control' && part.body === 'enter-frame') {- if (pierce)- throw new InvalidSelectorError(`Entering frames is not allowed while piercing frames, while parsing selector ${selectorText}`);- if (!chunk.parts.length)+ const lastPart = chunk.parts[chunk.parts.length - 1];+ if (!lastPart || (lastPart.name === 'internal:control' && lastPart.body === 'enter-frame'))throw new InvalidSelectorError('Selector cannot start with entering frame, select the iframe first');+ if (pierce) {+ chunk.parts.push(part);+ continue;+ }chunks.push(chunk);chunk = { parts: [] };chunkStartIndex = i + 1;@@ -131,6 +134,9 @@ export function splitSelectorByFrame(selectorText: string): { pierce: boolean, cthrow 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}`);}+ const lastPart = chunk.parts[chunk.parts.length - 1];+ if (lastPart.name === 'internal:control' && lastPart.body === 'enter-frame')+ 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-core/src/client/locator.ts b/packages/playwright-core/src/client/locator.tsindex dd58b18101..fe48cab8bd 100644--- a/packages/playwright-core/src/client/locator.ts+++ b/packages/playwright-core/src/client/locator.ts@@ -207,8 +207,6 @@ 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);}@@ -485,8 +483,6 @@ export class FrameLocator implements api.FrameLocator {}frameLocator(selector: string): FrameLocator {- if (selectorPiercesFrames(this._frameSelector))- throw new Error(`Entering frames is not allowed while piercing frames.`);return new FrameLocator(this._frame, this._childSelector(selector));}diff --git a/packages/playwright-core/src/server/frameSelectors.ts b/packages/playwright-core/src/server/frameSelectors.tsindex 7233ac85a7..14397b88e8 100644--- a/packages/playwright-core/src/server/frameSelectors.ts+++ b/packages/playwright-core/src/server/frameSelectors.ts@@ -136,7 +136,7 @@ export class FrameSelectors {}if (pierce) {- const parsed = chunks[0]; // Only one chunk is allowed with pierce.+ const parsed = chunks[0]; // Only one chunk is allowed with pierce, it may contain enter-frame parts.if (parsed.parts.some((part, index) => part.name === 'nth' && index !== parsed.parts.length - 1)) {const locator = asLocator(this.frame._page.browserContext._browser.sdkLanguage(), selector);throw new InvalidSelectorError(`nth can only be the last locator when piercing frames, while querying "${locator}"`);@@ -186,6 +186,9 @@ export class FrameSelectors {for (const [frame, startIndexes] of candidates) {for (const startIndex of startIndexes) {const suffix = infos.slice(startIndex);+ // A leftover "enter-frame" token means we are not going to match anything in this frame.+ if (suffix.some(info => isEnterFramePart(info.parsed.parts[0])))+ continue;const partialInfo: SelectorInfo = {parsed: { parts: suffix.map(info => info.parsed.parts[0]) },world: suffix.some(info => info.world === 'main') ? 'main' : 'utility',@@ -225,8 +228,17 @@ export class FrameSelectors {for (const element of all)next.add(element);}+ const nextPart = index + 1 < infos.length ? infos[index + 1].parsed.parts[0] : undefined;+ if (nextPart && nextPart.name === 'internal:control' && nextPart.body === 'enter-frame') {+ // We must enter the iframe now, so stop matching any further.+ for (const { frameElement, nextIndexes } of result) {+ if (next.has(frameElement))+ nextIndexes.push(index + 2);+ }+ break;+ }roots = [...next];- if (index + 1 < infos.length && !['nth', 'visible'].includes(infos[index + 1].parsed.parts[0].name)) {+ if (nextPart && !['nth', 'visible'].includes(nextPart.name)) {for (const { frameElement, nextIndexes } of result) {if (roots.some(root => injected.utils.isInsideScope(root, frameElement)))nextIndexes.push(index + 1);@@ -342,6 +354,10 @@ export class FrameSelectors {}}+function isEnterFramePart(part: ParsedSelector['parts'][0]): boolean {+ return part.name === 'internal:control' && part.body === 'enter-frame';+}+async function adoptIfNeeded<T extends Node>(handle: ElementHandle<T>, context: FrameExecutionContext): Promise<ElementHandle<T>> {if (handle._context === context)return handle;diff --git a/tests/page/locator-pierce-frames.spec.ts b/tests/page/locator-pierce-frames.spec.tsindex 5ad3bd4a5b..7939a48b38 100644--- a/tests/page/locator-pierce-frames.spec.ts+++ b/tests/page/locator-pierce-frames.spec.ts@@ -299,27 +299,121 @@ it('should pierce only frames inside the starting frame', async ({ page, serverawait expect(middleFrame.pierceFrames().locator('button')).toHaveText('deep');});+it('should enter a frame found in a nested frame', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe><button>main</button>`);+ await routePage(page, 'a.html', `<iframe id="target" src="b.html"></iframe><button>decoy</button>`);+ await routePage(page, 'b.html', `<button>inside</button>`);+ await page.goto(server.EMPTY_PAGE);+ await expect(page.pierceFrames().frameLocator('#target').locator('button')).toHaveText('inside');+});++it('should click inside an entered frame', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<iframe id="target" src="b.html"></iframe><button>Click me</button>`);+ await routePage(page, 'b.html', `<button onclick="window.__clicked = true">Click me</button>`);+ await page.goto(server.EMPTY_PAGE);+ await page.pierceFrames().frameLocator('#target').getByRole('button', { name: 'Click me' }).click();+ const frame = page.frames().find(f => f.url().includes('b.html'))!;+ expect(await frame.evaluate(() => (window as any).__clicked)).toBe(true);+});++it('should pierce frames inside the entered frame', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe id="target" src="a.html"></iframe><button>main</button>`);+ await routePage(page, 'a.html', `<iframe src="b.html"></iframe>`);+ await routePage(page, 'b.html', `<button>deep</button>`);+ await page.goto(server.EMPTY_PAGE);+ await expect(page.pierceFrames().frameLocator('#target').locator('button')).toHaveText('deep');+});++it('should support two frameLocators while piercing', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<iframe id="x" src="b.html"></iframe>`);+ await routePage(page, 'b.html', `<iframe id="y" src="c.html"></iframe><button>decoy</button>`);+ await routePage(page, 'c.html', `<button>bottom</button>`);+ await page.goto(server.EMPTY_PAGE);+ await expect(page.pierceFrames().frameLocator('#x').frameLocator('#y').locator('button')).toHaveText('bottom');+});++it('should support locator before frameLocator while piercing', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<section><iframe src="b.html"></iframe></section><iframe src="c.html"></iframe>`);+ await routePage(page, 'b.html', `<button>in-section</button>`);+ await routePage(page, 'c.html', `<button>outside</button>`);+ await page.goto(server.EMPTY_PAGE);+ await expect(page.pierceFrames().locator('section').frameLocator('iframe').locator('button')).toHaveText('in-section');+});++it('should support owner of a frameLocator while piercing', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<iframe id="target" src="b.html"></iframe>`);+ await routePage(page, 'b.html', `<button>inside</button>`);+ await page.goto(server.EMPTY_PAGE);+ expect(await page.pierceFrames().frameLocator('#target').owner().getAttribute('id')).toBe('target');+});++it('should wait for the frame to enter to appear', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<div>Nothing yet</div>`);+ await routePage(page, 'b.html', `<button>late</button>`);+ await page.goto(server.EMPTY_PAGE);+ await expect.poll(() => page.frames().length).toBe(2);+ await page.frames()[1].evaluate(() => {+ window.builtins.setTimeout(() => {+ const iframe = document.createElement('iframe');+ iframe.id = 'late';+ iframe.src = 'b.html';+ document.body.appendChild(iframe);+ }, 3000);+ });+ await expect(page.pierceFrames().frameLocator('#late').locator('button')).toHaveText('late');+});++it('should fail when the frame to enter matches 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', `<iframe class="inner" src="c.html"></iframe>`);+ await routePage(page, 'b.html', `<iframe class="inner" src="c.html"></iframe>`);+ await routePage(page, 'c.html', `<button>Click me</button>`);+ await page.goto(server.EMPTY_PAGE);+ await expect.poll(() => page.frames().length).toBe(5);+ for (const frame of page.frames()) {+ if (frame.url().includes('c.html'))+ await frame.waitForSelector('button', { state: 'attached' });+ }+ const error = await page.pierceFrames().frameLocator('.inner').locator('button').click({ timeout: 3000 }).catch(e => e);+ expect(error.message).toContain('Pierce-frame mode matched elements from multiple frames');+});++it('should support contentFrame while piercing', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<iframe src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<iframe id="target" src="b.html"></iframe><button>decoy</button>`);+ await routePage(page, 'b.html', `<button>inside</button>`);+ await page.goto(server.EMPTY_PAGE);+ await expect(page.pierceFrames().locator('#target').contentFrame().locator('button')).toHaveText('inside');+});++it('should enter only the frame element when the selector matches other elements too', async ({ page, server }) => {+ await routePage(page, 'empty.html', `<div class="foo">not a frame</div><iframe class="foo" src="a.html"></iframe>`);+ await routePage(page, 'a.html', `<iframe src="b.html"></iframe>`);+ await routePage(page, 'b.html', `<div id="target">found</div>`);+ await page.goto(server.EMPTY_PAGE);+ await expect(page.pierceFrames().locator('.foo').contentFrame().locator('#target')).toHaveText('found');+});++it('should render frameLocator while piercing in the locator description', async ({ page }) => {+ expect(String(page.pierceFrames().frameLocator('#x').locator('button'))).toBe(`pierceFrames().locator('#x').contentFrame().locator('button')`);+ expect(String(page.pierceFrames().locator('section').frameLocator('iframe').getByText('foo'))).toBe(`pierceFrames().locator('section').locator('iframe').contentFrame().getByText('foo')`);+});+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');+ expect(() => page.pierceFrames().frameLocator('#x').first()).toThrow('Selecting the nth frame is not allowed while piercing frames');});it('should not allow composite locators', async ({ page }) => {diff --git a/tests/page/selectors-frame.spec.ts b/tests/page/selectors-frame.spec.tsindex 8a305157bb..c12a6c38ff 100644--- a/tests/page/selectors-frame.spec.ts+++ b/tests/page/selectors-frame.spec.ts@@ -388,9 +388,20 @@ it('should not allow pierce-frames in the middle of a selector', async ({ page,expect(error.message).toContain('"pierce-frames" is only allowed as the first selector token');});-it('should not allow entering frames while piercing', async ({ page, server }) => {+it('should allow entering frames while piercing', async ({ page, server }) => {await routeIframe(page);await page.goto(server.EMPTY_PAGE);- const error = await page.locator('internal:control=pierce-frames >> iframe >> internal:control=enter-frame >> div').waitFor().catch(e => e);- expect(error.message).toContain('Entering frames is not allowed while piercing frames');+ const button = page.locator('internal:control=pierce-frames >> iframe[src="iframe-2.html"] >> internal:control=enter-frame >> button');+ await button.waitFor();+ expect(await button.innerText()).toBe('Hello nested iframe');+});++it('should not allow pierce-frames after entering a frame', async ({ page }) => {+ const error = await page.locator('iframe >> internal:control=enter-frame >> internal:control=pierce-frames >> button').count().catch(e => e);+ expect(error.message).toContain('"pierce-frames" is only allowed as the first selector token');+});++it('should not allow dangling enter-frame while piercing', async ({ page }) => {+ const error = await page.locator('internal:control=pierce-frames >> iframe >> internal:control=enter-frame').count().catch(e => e);+ expect(error.message).toContain('Selector cannot end with entering frame');});