diff --git a/bin/lib/core.js b/bin/lib/core.js index ae07dff..193de69 100644 --- a/bin/lib/core.js +++ b/bin/lib/core.js @@ -1,5 +1,6 @@ const fs = require('fs'); const path = require('path'); +const { NativeFrames } = require('./frames'); const DEBUG = process.env.PLAYWRIGHT_DEBUG === 'true'; const DEBUG_LEVEL = process.env.PLAYWRIGHT_DEBUG_LEVEL || 'info'; @@ -257,12 +258,37 @@ class PromiseUtils { class FrameUtils { static resolve(page, chain) { if (!chain || chain === ':root') return page; - const parts = String(chain).split(' >> ').filter(Boolean); - let fl = page; + const reference = NativeFrames.resolve(page, chain); + const parts = this.parts(reference ? reference.remainder : chain); + let fl = reference ? reference.frame : page; + + if (parts[0] === ':root') parts.shift(); + + if (reference && /^nth=-?\d+$/.test(parts[0])) { + const index = Number(parts.shift().slice(4)); + + if (index !== 0 && index !== -1) fl = reference.frame.frameLocator('iframe:not(*)'); + } + for (const part of parts) fl = fl.frameLocator(part); return fl; } + static parts(chain) { + const parts = []; + + for (const part of String(chain).split(' >> ').filter(Boolean)) { + if (/^nth=-?\d+$/.test(part) && parts.length) { + parts[parts.length - 1] += ' >> ' + part; + continue; + } + + parts.push(part); + } + + return parts; + } + static async evaluateInFrame(page, frameLocator, isMainFrame, expression, arg) { if (isMainFrame) return await page.evaluate(expression, arg); const loc = frameLocator.locator('html'); @@ -278,43 +304,78 @@ class FrameUtils { } static async resolveNativeFrame(page, chain) { - const mainFrame = page.mainFrame(); - if (!chain || chain === ':root') return mainFrame; + if (!chain || chain === ':root') return page.mainFrame(); - for (const frame of page.frames()) { - if (frame === mainFrame) continue; - try { - if (await this.selectorForNativeFrame(frame, mainFrame) === chain) return frame; - } catch { - // A detached frame cannot be addressed by the PHP selector anymore. - } - } + const reference = NativeFrames.resolve(page, chain); + + if (reference && !reference.remainder.trim()) return reference.frame; + + const locator = this.resolve(page, chain).owner(); + const elements = await locator.elementHandles(); + + try { + if (elements.length !== 1) throw new Error(`Frame selector must match one frame: ${chain}`); + + const frame = await elements[0].contentFrame(); + + if (!frame) throw new Error(`Frame not found for selector: ${chain}`); - throw new Error(`Frame not found for selector: ${chain}`); + return frame; + } finally { + await Promise.all(elements.map(element => element.dispose())); + } } + /** Page code can replace DOM helpers, so read attributes through Playwright. */ static async selectorForNativeFrame(frame, mainFrame) { + if (frame === mainFrame) return ':root'; + const chain = []; let current = frame; while (current && current !== mainFrame) { const element = await current.frameElement(); - const selector = await element.evaluate((node) => { - const escape = (value) => (typeof CSS !== 'undefined' && CSS.escape) - ? CSS.escape(value) - : String(value).replace(/[^a-zA-Z0-9_-]/g, (match) => `\\${match}`); - if (node.id) return `iframe#${escape(node.id)}`; - const name = node.getAttribute('name'); - if (name) return `iframe[name="${name}"]`; - const src = node.getAttribute('src'); - if (src) return `iframe[src="${src}"]`; - const iframes = Array.from(node.ownerDocument.querySelectorAll('iframe')); - return `iframe >> nth=${iframes.indexOf(node)}`; - }); + let selector; + + try { + const id = await element.getAttribute('id'); + const name = await element.getAttribute('name'); + const src = await element.getAttribute('src'); + selector = await this.selectorForElement(current.parentFrame(), element, { id, name, src }); + } finally { + await element.dispose(); + } + chain.unshift(selector); current = current.parentFrame(); } - return chain.join(' >> '); + return NativeFrames.bind(frame, chain.join(' >> ')); + } + + static escapeAttribute(value) { + return value.replace(/[^a-zA-Z0-9_-]/gu, character => `\\${character.codePointAt(0).toString(16)} `); + } + + static async selectorForElement(parent, element, { id, name, src }) { + if (id && /^[a-zA-Z_][-_a-zA-Z0-9]*$/.test(id) && id !== '-') return `iframe#${id}`; + + if (id && !id.includes('\0')) return `iframe[id="${this.escapeAttribute(id)}"]`; + + if (name && !name.includes('\0')) return `iframe[name="${this.escapeAttribute(name)}"]`; + + if (src && !src.includes('\0')) return `iframe[src="${this.escapeAttribute(src)}"]`; + + const index = await parent.locator('iframe').evaluateAll((elements, target) => { + for (let index = 0; index < elements.length; index++) { + if (elements[index] === target) return index; + } + + return -1; + }, element); + + if (index < 0) throw new Error('Frame element has been detached.'); + + return `iframe >> nth=${index}`; } static async waitForReadyState(evalInFrame, state, timeoutMs) { diff --git a/bin/lib/frames.js b/bin/lib/frames.js new file mode 100644 index 0000000..8880c52 --- /dev/null +++ b/bin/lib/frames.js @@ -0,0 +1,74 @@ +const { randomUUID } = require('node:crypto'); + +class NativeFrames { + static #pages = new WeakMap(); + + static bind(frame, selector) { + const page = frame.page(); + + if (page.isClosed() || frame.isDetached()) throw new Error('Frame has been detached.'); + + let references = this.#pages.get(page); + + if (!references) { + references = new Map(); + this.#pages.set(page, references); + page.once('close', () => references.clear()); + page.on('framedetached', detached => { + references.delete(references.get(detached)); + references.delete(detached); + }); + } + + let id = references.get(frame); + + if (!id) { + id = randomUUID(); + references.set(frame, id); + references.set(id, { frame, selector: `${selector} >> css=:scope/*pw-frame:${id}*/` }); + } + + return references.get(id).selector; + } + + static detached(page, selector) { + const reference = this.#reference(selector); + + if (!reference) return null; + + const record = this.#pages.get(page)?.get(reference.id); + + if (!record) return true; + + if (!String(selector).startsWith(record.selector)) return null; + + return record.frame.isDetached(); + } + + static resolve(page, selector) { + const reference = this.#reference(selector); + + if (!reference) return null; + + const record = this.#pages.get(page)?.get(reference.id); + + if (!record) throw new Error('Frame reference has expired.'); + + if (!String(selector).startsWith(record.selector)) return null; + + return { frame: record.frame, remainder: String(selector).slice(record.selector.length) }; + } + + /** Reference-shaped text in CSS literals and comments must remain data. */ + static #reference(selector) { + const tokens = String(selector).matchAll(/\\[\s\S]|"(?:\\(?:[\s\S]|$)|[^"\\])*(?:"|$)|'(?:\\(?:[\s\S]|$)|[^'\\])*(?:'|$)|\/\*[\s\S]*?(?:\*\/|$)|(?:^| >> )css=:scope\/\*pw-frame:([\s\S]*?)(?:\*\/|$)/g); + + for (const token of tokens) { + if (token[1] !== undefined) return { id: token[1] }; + } + + return null; + } +} + +module.exports = { NativeFrames }; diff --git a/bin/lib/handlers.js b/bin/lib/handlers.js index 7f05b18..28f095d 100644 --- a/bin/lib/handlers.js +++ b/bin/lib/handlers.js @@ -1,6 +1,7 @@ const fs = require('fs/promises'); const { logger, ErrorHandler, CommandRegistry, BaseHandler, PromiseUtils, FrameUtils, RouteUtils } = require('./core'); const { globalCoordinator } = require('./coordination'); +const { NativeFrames } = require('./frames'); const { PopupCoordinator } = require('./popup-coordinator'); // Runs Playwright's own toHaveScreenshot machinery: the loop until two @@ -1045,6 +1046,9 @@ class InteractionHandler extends BaseHandler { class FrameHandler extends BaseHandler { async handle(command, method) { const page = this.validateResource(this.pages, command.pageId, 'Page'); + + if (method === 'isDetached') return this.checkDetached(page, command.frameSelector); + const isMainFrame = !command.frameSelector || command.frameSelector === ':root'; const frameLocator = isMainFrame ? null : FrameUtils.resolve(page, command.frameSelector); const evalInFrame = (expression) => FrameUtils.evaluateInFrame(page, frameLocator, isMainFrame, expression); @@ -1066,9 +1070,8 @@ class FrameHandler extends BaseHandler { frameElement: () => this.frameElement(nativeFrame), title: () => evalInFrame(() => document.title).then(v => this.createValueResult(v ?? '')), url: () => evalInFrame(() => document.location.href).then(v => this.createValueResult(v ?? '')), - isDetached: () => this.checkDetached(isMainFrame, frameLocator), waitForLoadState: () => isMainFrame ? page.waitForLoadState(command.state || 'load', command.options) : this.waitForLoadState(page, frameLocator, isMainFrame, command), - parent: () => this.getParent(isMainFrame, command.frameSelector), + parent: () => this.getParent(page, isMainFrame, command.frameSelector), children: () => this.getChildren(page, frameLocator, isMainFrame, command.frameSelector) }); @@ -1095,9 +1098,15 @@ class FrameHandler extends BaseHandler { return this.storeHandle(await frame.frameElement()); } - async checkDetached(isMainFrame, frameLocator) { - if (isMainFrame) return this.createValueResult(false); - const count = await frameLocator.locator('html').count(); + async checkDetached(page, frameSelector) { + if (!frameSelector || frameSelector === ':root') return this.createValueResult(false); + + const detached = NativeFrames.detached(page, frameSelector); + + if (detached !== null) return this.createValueResult(detached); + + const scope = FrameUtils.resolve(page, frameSelector); + const count = await scope.locator('html').count(); return this.createValueResult(count === 0); } @@ -1113,28 +1122,22 @@ class FrameHandler extends BaseHandler { return { success: true }; } - getParent(isMainFrame, frameSelector) { + async getParent(page, isMainFrame, frameSelector) { if (isMainFrame) return { selector: null }; - const parts = String(frameSelector).split(' >> ').filter(Boolean); - parts.pop(); - const parentSelector = parts.length ? parts.join(' >> ') : ':root'; - return { selector: parentSelector }; + + const frame = await FrameUtils.resolveNativeFrame(page, frameSelector); + const parent = frame.parentFrame(); + + if (!parent || parent === page.mainFrame()) return { selector: ':root' }; + + return { selector: await FrameUtils.selectorForNativeFrame(parent, page.mainFrame()) }; } async getChildren(page, frameLocator, isMainFrame, frameSelector) { - const selectorBuilder = (root) => { - const esc = (s) => (typeof CSS !== 'undefined' && CSS.escape) ? CSS.escape(s) : String(s).replace(/[^a-zA-Z0-9_-]/g, (m) => `\\${m}`); - return Array.from(root.ownerDocument.querySelectorAll('iframe')).map((node, idx) => { - if (node.id) return `iframe#${esc(node.id)}`; - if (node.getAttribute('name')) return `iframe[name="${node.getAttribute('name')}"]`; - if (node.getAttribute('src')) return `iframe[src="${node.getAttribute('src')}"]`; - return `iframe >> nth=${idx}`; - }); - }; - - const childSelectors = isMainFrame ? await page.evaluate(selectorBuilder) : await frameLocator.locator('html').evaluate(selectorBuilder) || []; - const prefix = isMainFrame ? '' : (String(frameSelector) + ' >> '); - const frames = childSelectors.map(sel => ({ selector: prefix + sel })); + const parent = isMainFrame ? page.mainFrame() : await FrameUtils.resolveNativeFrame(page, frameSelector); + const frames = await Promise.all(parent.childFrames().map(async frame => ({ + selector: await FrameUtils.selectorForNativeFrame(frame, page.mainFrame()) + }))); return { frames }; } } diff --git a/docs/guide/core-concepts.md b/docs/guide/core-concepts.md index afa1ac0..ccae62f 100644 --- a/docs/guide/core-concepts.md +++ b/docs/guide/core-concepts.md @@ -94,3 +94,7 @@ $signInButton->click(); By understanding and using these four core concepts, you can build powerful, reliable, and maintainable browser automation scripts and tests. + +## Frame identity + +URL-selected frames retain their native identity as iframe attributes change. Frame references expire when the frame detaches or its page closes. diff --git a/src/Frame/Frame.php b/src/Frame/Frame.php index 5d5f5a7..6eb139d 100644 --- a/src/Frame/Frame.php +++ b/src/Frame/Frame.php @@ -19,6 +19,7 @@ use Playwright\Exception\RuntimeException; use Playwright\JSHandle\JSHandle; use Playwright\JSHandle\JSHandleInterface; +use Playwright\Locator\LiteralSelector; use Playwright\Locator\Locator; use Playwright\Locator\LocatorInterface; use Playwright\Locator\RoleSelectorBuilder; @@ -71,7 +72,7 @@ public function locator(string $selector): LocatorInterface */ public function getByAltText(string $text, array $options = []): LocatorInterface { - return $this->locator(\sprintf('[alt="%s"]', $text)); + return $this->locator(\sprintf('[alt=%s]', LiteralSelector::css($text))); } /** @@ -79,7 +80,7 @@ public function getByAltText(string $text, array $options = []): LocatorInterfac */ public function getByLabel(string $text, array $options = []): LocatorInterface { - return $this->locator(\sprintf('label:text-is("%s") >> nth=0', $text)); + return $this->locator(\sprintf('label:text-is(%s) >> nth=0', LiteralSelector::css($text))); } /** @@ -87,7 +88,7 @@ public function getByLabel(string $text, array $options = []): LocatorInterface */ public function getByPlaceholder(string $text, array $options = []): LocatorInterface { - return $this->locator(\sprintf('[placeholder="%s"]', $text)); + return $this->locator(\sprintf('[placeholder=%s]', LiteralSelector::css($text))); } /** @@ -109,7 +110,7 @@ public function getByRole(string $role, array $options = []): LocatorInterface public function getByTestId(string $testId): LocatorInterface { - return $this->locator(\sprintf('[data-testid="%s"]', $testId)); + return $this->locator(\sprintf('[data-testid=%s]', LiteralSelector::css($testId))); } /** @@ -117,7 +118,7 @@ public function getByTestId(string $testId): LocatorInterface */ public function getByText(string $text, array $options = []): LocatorInterface { - return $this->locator(\sprintf('text="%s"', $text)); + return $this->locator('internal:text='.LiteralSelector::text($text).'s'); } /** @@ -125,7 +126,7 @@ public function getByText(string $text, array $options = []): LocatorInterface */ public function getByTitle(string $text, array $options = []): LocatorInterface { - return $this->locator(\sprintf('[title="%s"]', $text)); + return $this->locator(\sprintf('[title=%s]', LiteralSelector::css($text))); } public function frameLocator(string $selector): FrameLocatorInterface @@ -325,6 +326,10 @@ public function url(): string public function isDetached(): bool { + if ($this->page?->isClosed()) { + return true; + } + $response = $this->sendCommand('frame.isDetached'); return true === ($response['value'] ?? false); diff --git a/src/Frame/FrameLocator.php b/src/Frame/FrameLocator.php index e11dc6c..115a7cb 100644 --- a/src/Frame/FrameLocator.php +++ b/src/Frame/FrameLocator.php @@ -14,6 +14,7 @@ namespace Playwright\Frame; +use Playwright\Locator\LiteralSelector; use Playwright\Locator\Locator; use Playwright\Locator\LocatorInterface; use Playwright\Locator\RoleSelectorBuilder; @@ -51,7 +52,7 @@ public function locator(string $selector): LocatorInterface */ public function getByAltText(string $text, array $options = []): LocatorInterface { - return $this->locator(\sprintf('[alt="%s"]', $text)); + return $this->locator(\sprintf('[alt=%s]', LiteralSelector::css($text))); } /** @@ -59,7 +60,7 @@ public function getByAltText(string $text, array $options = []): LocatorInterfac */ public function getByLabel(string $text, array $options = []): LocatorInterface { - return $this->locator(\sprintf('label:text-is("%s") >> nth=0', $text)); + return $this->locator(\sprintf('label:text-is(%s) >> nth=0', LiteralSelector::css($text))); } /** @@ -67,7 +68,7 @@ public function getByLabel(string $text, array $options = []): LocatorInterface */ public function getByPlaceholder(string $text, array $options = []): LocatorInterface { - return $this->locator(\sprintf('[placeholder="%s"]', $text)); + return $this->locator(\sprintf('[placeholder=%s]', LiteralSelector::css($text))); } /** @@ -89,7 +90,7 @@ public function getByRole(string $role, array $options = []): LocatorInterface public function getByTestId(string $testId): LocatorInterface { - return $this->locator(\sprintf('[data-testid="%s"]', $testId)); + return $this->locator(\sprintf('[data-testid=%s]', LiteralSelector::css($testId))); } /** @@ -97,7 +98,7 @@ public function getByTestId(string $testId): LocatorInterface */ public function getByText(string $text, array $options = []): LocatorInterface { - return $this->locator(\sprintf('text="%s"', $text)); + return $this->locator('internal:text='.LiteralSelector::text($text).'s'); } /** @@ -105,7 +106,7 @@ public function getByText(string $text, array $options = []): LocatorInterface */ public function getByTitle(string $text, array $options = []): LocatorInterface { - return $this->locator(\sprintf('[title="%s"]', $text)); + return $this->locator(\sprintf('[title=%s]', LiteralSelector::css($text))); } public function first(): self diff --git a/src/Locator/LiteralSelector.php b/src/Locator/LiteralSelector.php new file mode 100644 index 0000000..d091919 --- /dev/null +++ b/src/Locator/LiteralSelector.php @@ -0,0 +1,37 @@ +locator(\sprintf('[alt="%s"]', $text)); + return $this->locator(\sprintf('[alt=%s]', LiteralSelector::css($text))); } /** @@ -405,7 +405,7 @@ public function getByLabel(string $text, array|GetByOptions $options = []): self { $options = GetByOptions::from($options); - return $this->locator(\sprintf('label:text-is("%s") >> nth=0', $text)); + return $this->locator(\sprintf('label:text-is(%s) >> nth=0', LiteralSelector::css($text))); } /** @@ -415,7 +415,7 @@ public function getByPlaceholder(string $text, array|GetByOptions $options = []) { $options = GetByOptions::from($options); - return $this->locator(\sprintf('[placeholder="%s"]', $text)); + return $this->locator(\sprintf('[placeholder=%s]', LiteralSelector::css($text))); } /** @@ -431,7 +431,7 @@ public function getByRole(string $role, array|GetByRoleOptions $options = []): s public function getByTestId(string $testId): self { - return $this->locator(\sprintf('[data-testid="%s"]', $testId)); + return $this->locator(\sprintf('[data-testid=%s]', LiteralSelector::css($testId))); } /** @@ -441,7 +441,7 @@ public function getByText(string $text, array|GetByOptions $options = []): self { $options = GetByOptions::from($options); - return $this->locator(\sprintf('text="%s"', $text)); + return $this->locator('internal:text='.LiteralSelector::text($text).'s'); } /** @@ -451,7 +451,7 @@ public function getByTitle(string $text, array|GetByOptions $options = []): self { $options = GetByOptions::from($options); - return $this->locator(\sprintf('[title="%s"]', $text)); + return $this->locator(\sprintf('[title=%s]', LiteralSelector::css($text))); } /** @@ -977,19 +977,19 @@ public function filter(array|FilterOptions $options = []): self $chain = clone $this->selectorChain; if (null !== $options->hasText) { - $chain->addFilter(\sprintf(':has-text("%s")', $options->hasText)); + $chain->append('internal:has-text='.LiteralSelector::text($options->hasText).'i'); } if (null !== $options->hasNotText) { - $chain->addFilter(\sprintf(':not(:has-text("%s"))', $options->hasNotText)); + $chain->append('internal:has-not-text='.LiteralSelector::text($options->hasNotText).'i'); } if (null !== $options->has) { - $chain->addFilter(\sprintf(':has(%s)', $options->has->getSelector())); + $chain->append('internal:has='.LiteralSelector::text($options->has->getSelector())); } if (null !== $options->hasNot) { - $chain->addFilter(\sprintf(':not(:has(%s))', $options->hasNot->getSelector())); + $chain->append('internal:has-not='.LiteralSelector::text($options->hasNot->getSelector())); } return new self($this->transport, $this->pageId, $chain, $this->frameSelector, $this->logger, [], $this->page); diff --git a/src/Page/Page.php b/src/Page/Page.php index 136e098..1967347 100644 --- a/src/Page/Page.php +++ b/src/Page/Page.php @@ -43,6 +43,7 @@ use Playwright\Input\TouchscreenInterface; use Playwright\JSHandle\JSHandle; use Playwright\JSHandle\JSHandleInterface; +use Playwright\Locator\LiteralSelector; use Playwright\Locator\Locator; use Playwright\Locator\LocatorInterface; use Playwright\Locator\Options\AriaSnapshotOptions; @@ -335,7 +336,7 @@ public function getByRole(string $role, array|GetByRoleOptions $options = []): L */ public function getByTestId(string $testId, array|LocatorOptions $options = []): LocatorInterface { - return $this->locator(\sprintf('[data-testid="%s"]', $testId), $options); + return $this->locator(\sprintf('[data-testid=%s]', LiteralSelector::css($testId)), $options); } /** @@ -1558,11 +1559,7 @@ private static function buildTextSelector(string|Regex $text, bool $exact): stri return \sprintf('internal:text=%s', $text->pattern); } - if ($exact) { - return \sprintf('internal:text="%s"', addcslashes($text, '\\"')); - } - - return \sprintf('internal:text=/%s/i', preg_quote($text, '/')); + return 'internal:text='.LiteralSelector::text($text).($exact ? 's' : 'i'); } private static function buildAttrSelector(string $attr, string|Regex $text, bool $exact): string diff --git a/tests/Integration/Bridge/SelectorsBridgeTest.php b/tests/Integration/Bridge/SelectorsBridgeTest.php new file mode 100644 index 0000000..f07dd15 --- /dev/null +++ b/tests/Integration/Bridge/SelectorsBridgeTest.php @@ -0,0 +1,32 @@ +setTimeout(30); + $process->run(); + + $this->assertSame(0, $process->getExitCode(), $process->getOutput().$process->getErrorOutput()); + } +} diff --git a/tests/Integration/Bridge/selectors.test.cjs b/tests/Integration/Bridge/selectors.test.cjs new file mode 100644 index 0000000..fcedc84 --- /dev/null +++ b/tests/Integration/Bridge/selectors.test.cjs @@ -0,0 +1,25 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { EventEmitter } = require('node:events'); + +test('native frame references expire on detachment and page closure', () => { + const { NativeFrames } = require('../../../bin/lib/frames'); + const page = new EventEmitter(); + page.isClosed = () => false; + const frame = { page: () => page, isDetached: () => false }; + const reference = NativeFrames.bind(frame, 'iframe'); + assert.equal(NativeFrames.bind(frame, 'iframe'), reference); + assert.equal(NativeFrames.resolve(page, reference).frame, frame); + assert.equal(NativeFrames.bind(frame, 'iframe[name="changed"]'), reference); + assert.equal(NativeFrames.resolve(page, `iframe[name=${JSON.stringify(reference)}]`), null); + assert.equal(NativeFrames.resolve(page, `iframe/* ${reference} */`), null); + assert.equal(NativeFrames.resolve(page, `iframe[name="${reference}\\`), null); + assert.equal(NativeFrames.resolve(page, reference + ' >> iframe').remainder, ' >> iframe'); + page.emit('framedetached', frame); + assert.equal(NativeFrames.detached(page, reference), true); + assert.throws(() => NativeFrames.resolve(page, reference), /expired/); + const other = { page: () => page, isDetached: () => false }; + const next = NativeFrames.bind(other, 'iframe#other'); + page.emit('close'); + assert.throws(() => NativeFrames.resolve(page, next), /expired/); +}); diff --git a/tests/Integration/Browser/LiteralSelectorBoundaryTest.php b/tests/Integration/Browser/LiteralSelectorBoundaryTest.php new file mode 100644 index 0000000..fea54d6 --- /dev/null +++ b/tests/Integration/Browser/LiteralSelectorBoundaryTest.php @@ -0,0 +1,147 @@ +setUpPlaywright(); + $this->page->route('https://private.example/**', static function (RouteInterface $route): void { + $route->fulfill(['contentType' => 'text/html', 'headers' => ['access-control-allow-origin' => 'https://private.example'], 'body' => '

private-content

']); + }); + } + + protected function tearDown(): void + { + $this->tearDownPlaywright(); + } + + #[DataProvider('frameNames')] + public function testQuotedFrameNamesKeepOperationsInTheSelectedFrame(string $name): void + { + $this->page->setContent(''); + $this->page->evaluate('() => { CSS.escape = value => value; Element.prototype.getAttribute = () => "attacker"; }'); + $frame = $this->page->frame(['url' => 'https://private.example/frame']); + $this->assertNotNull($frame); + $frame->locator('#password')->fill('frame-value'); + $this->assertSame('frame-value', $frame->locator('#password')->inputValue()); + $this->assertSame('', $this->page->frameLocator('#attacker')->locator('#password')->inputValue()); + } + + public function testUrlSelectedFramesKeepTheirIdentityAfterAttributesChange(): void + { + $this->page->setContent(''); + $frame = $this->page->frame(['url' => 'https://private.example/frame']); + $this->assertNotNull($frame); + $this->page->evaluate('() => { document.querySelector("iframe").name = "renamed"; document.querySelector("#attacker").name = "trusted"; }'); + $frame->locator('#password')->fill('original-frame'); + $this->assertSame('original-frame', $frame->locator('#password')->inputValue()); + $this->assertSame('', $this->page->frameLocator('#attacker')->locator('#password')->inputValue()); + $this->assertNotNull($frame->parentFrame()); + $frame->owner()->contentFrame()->first()->locator('#password')->fill('original-owner'); + $this->assertSame('original-owner', $frame->locator('#password')->inputValue()); + $this->page->setDefaultTimeout(100); + $this->assertSame(0, $frame->owner()->contentFrame()->nth(1)->locator('#password')->count()); + } + + public function testNativeFrameReferencesCanReportDetachment(): void + { + $this->page->setContent(''); + $frame = $this->page->frame(['name' => 'target']); + $this->assertNotNull($frame); + $this->assertFalse($frame->isDetached()); + $this->page->evaluate('() => document.querySelector("iframe").remove()'); + $this->assertTrue($frame->isDetached()); + } + + #[DataProvider('literalValues')] + public function testLiteralLocatorsAndFiltersKeepTheirScope(string $value): void + { + $escaped = htmlspecialchars($value, ENT_QUOTES); + $markup = '
'.$escaped.'

'.$escaped.'

outside

'; + $this->page->setContent($markup.''); + $frame = $this->page->frame(['name' => 'literal']); + $this->assertNotNull($frame); + $scopes = [$this->page, $this->page->locator('section'), $frame, $this->page->frameLocator('#literal')]; + + foreach ($scopes as $scope) { + $this->assertSame(1, $scope->getByTestId($value)->count()); + $this->assertSame(1, $scope->getByAltText($value)->count()); + $this->assertSame(1, $scope->getByPlaceholder($value)->count()); + $this->assertSame(1, $scope->getByTitle($value)->count()); + $this->assertSame(1, $scope->getByText($value)->count()); + } + + $this->assertSame(1, $this->page->locator('section p')->filter(['hasText' => $value])->count()); + $this->assertSame(0, $this->page->locator('section p')->filter(['hasNotText' => $value])->count()); + $this->assertSame(0, $this->page->locator('section p')->filter(['hasText' => '"), #unrelated, :has-text("missing'])->count()); + } + + /** @return iterable */ + public static function frameNames(): iterable + { + yield 'selector list' => ['"], iframe#attacker, iframe[name="']; + yield 'chain delimiter' => ['frame >> quoted " value']; + } + + /** @return iterable */ + public static function literalValues(): iterable + { + yield 'selector list' => ['"), #unrelated, :has-text("']; + yield 'whitespace and escapes' => ["quoted\\ value\n >> café"]; + } + + public function testNestedAnonymousFramesKeepTheirNativeParent(): void + { + $inner = ''; + $outer = ''; + $this->page->setContent(''); + $frame = $this->page->frame(['name' => 'target']); + $this->assertNotNull($frame); + $frame->locator('#nested')->fill('nested-value'); + $this->assertSame('nested-value', $frame->locator('#nested')->inputValue()); + $this->assertCount(1, $this->page->mainFrame()->childFrames()[0]->childFrames()); + } + + #[DataProvider('frameIds')] + public function testNonIdentifierFrameIdsRemainAddressable(string $id): void + { + $inner = ''; + $this->page->setContent(''); + $frame = $this->page->frame(['name' => 'target']); + $this->assertNotNull($frame); + $frame->locator('#target')->fill('id-value'); + $this->assertSame('id-value', $frame->locator('#target')->inputValue()); + } + + /** @return iterable */ + public static function frameIds(): iterable + { + yield 'hyphen digit' => ['-1']; + yield 'hyphen digit word' => ['-9foo']; + yield 'leading digit' => ['1frame']; + yield 'quoted delimiter' => ['id >> quoted " value']; + } +} diff --git a/tests/Unit/Frame/FrameLocatorTest.php b/tests/Unit/Frame/FrameLocatorTest.php index 9bc339f..c5ff97e 100644 --- a/tests/Unit/Frame/FrameLocatorTest.php +++ b/tests/Unit/Frame/FrameLocatorTest.php @@ -170,7 +170,7 @@ public function testGetByText(): void { $locator = $this->frameLocator->getByText('Hello'); $this->assertInstanceOf(LocatorInterface::class, $locator); - $this->assertSame('text="Hello"', $locator->getSelector()); + $this->assertSame('internal:text="Hello"s', $locator->getSelector()); } public function testGetByRole(): void diff --git a/tests/Unit/Frame/FrameTest.php b/tests/Unit/Frame/FrameTest.php index 310ac2c..0e5abf2 100644 --- a/tests/Unit/Frame/FrameTest.php +++ b/tests/Unit/Frame/FrameTest.php @@ -351,7 +351,7 @@ public function testGetByText(): void $frame = new Frame($this->transport, $this->pageId, 'iframe#auth', $this->logger); $locator = $frame->getByText('Hello'); $this->assertInstanceOf(LocatorInterface::class, $locator); - $this->assertSame('text="Hello"', $locator->getSelector()); + $this->assertSame('internal:text="Hello"s', $locator->getSelector()); } public function testGetByRole(): void diff --git a/tests/Unit/Locator/LiteralSelectorTest.php b/tests/Unit/Locator/LiteralSelectorTest.php new file mode 100644 index 0000000..b90c3e9 --- /dev/null +++ b/tests/Unit/Locator/LiteralSelectorTest.php @@ -0,0 +1,29 @@ +expectException(\InvalidArgumentException::class); + LiteralSelector::css("value\0suffix"); + } +} diff --git a/tests/Unit/Locator/LocatorTest.php b/tests/Unit/Locator/LocatorTest.php index 7abe50d..b480a69 100644 --- a/tests/Unit/Locator/LocatorTest.php +++ b/tests/Unit/Locator/LocatorTest.php @@ -648,7 +648,7 @@ public function testGetByText(): void { $result = $this->locator->getByText('Hello'); $this->assertInstanceOf(Locator::class, $result); - $this->assertSame('Locator(selector=".element >> text="Hello"")', (string) $result); + $this->assertSame('Locator(selector=".element >> internal:text="Hello"s")', (string) $result); } public function testGetByRole(): void @@ -897,7 +897,7 @@ public function testFilterWithHasText(): void $filtered = $this->locator->filter(['hasText' => 'foo']); $this->assertInstanceOf(Locator::class, $filtered); - $this->assertSame('Locator(selector=".items:has-text("foo")")', (string) $filtered); + $this->assertSame('Locator(selector=".items >> internal:has-text="foo"i")', (string) $filtered); } public function testFilterWithHas(): void @@ -908,7 +908,7 @@ public function testFilterWithHas(): void $filtered = $this->locator->filter(['has' => $inner]); $this->assertInstanceOf(Locator::class, $filtered); - $this->assertSame('Locator(selector=".items:has(.inner)")', (string) $filtered); + $this->assertSame('Locator(selector=".items >> internal:has=".inner"")', (string) $filtered); } public function testFilterWithHasNotText(): void @@ -918,7 +918,7 @@ public function testFilterWithHasNotText(): void $filtered = $this->locator->filter(['hasNotText' => 'bar']); $this->assertInstanceOf(Locator::class, $filtered); - $this->assertSame('Locator(selector=".items:not(:has-text("bar"))")', (string) $filtered); + $this->assertSame('Locator(selector=".items >> internal:has-not-text="bar"i")', (string) $filtered); } public function testFilterWithHasNot(): void @@ -929,7 +929,7 @@ public function testFilterWithHasNot(): void $filtered = $this->locator->filter(['hasNot' => $inner]); $this->assertInstanceOf(Locator::class, $filtered); - $this->assertSame('Locator(selector=".items:not(:has(.inner))")', (string) $filtered); + $this->assertSame('Locator(selector=".items >> internal:has-not=".inner"")', (string) $filtered); } public function testAnd(): void @@ -994,8 +994,8 @@ public function testFilterWithBothOptions(): void ]); $this->assertInstanceOf(Locator::class, $filtered); - $this->assertStringContainsString(':has-text("foo")', (string) $filtered); - $this->assertStringContainsString(':has(.inner)', (string) $filtered); + $this->assertStringContainsString('internal:has-text="foo"i', (string) $filtered); + $this->assertStringContainsString('internal:has=".inner"', (string) $filtered); } public function testNormalizesReturnBodyToFunctionWithElement(): void diff --git a/tests/Unit/Page/PageTest.php b/tests/Unit/Page/PageTest.php index 0923497..f2f1a9f 100644 --- a/tests/Unit/Page/PageTest.php +++ b/tests/Unit/Page/PageTest.php @@ -264,7 +264,7 @@ public function testGetByTextBuildsCaseInsensitiveSelector(): void $locator = $this->page->getByText('Hello World'); $this->assertInstanceOf(Locator::class, $locator); - $this->assertSame('internal:text=/Hello World/i', $locator->getSelector()); + $this->assertSame('internal:text="Hello World"i', $locator->getSelector()); } public function testGetByTextBuildsExactSelector(): void @@ -272,7 +272,7 @@ public function testGetByTextBuildsExactSelector(): void $locator = $this->page->getByText('Hello World', ['exact' => true]); $this->assertInstanceOf(Locator::class, $locator); - $this->assertSame('internal:text="Hello World"', $locator->getSelector()); + $this->assertSame('internal:text="Hello World"s', $locator->getSelector()); } public function testGetByPlaceholderBuildsCaseInsensitiveSelector(): void