Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 87 additions & 26 deletions bin/lib/core.js
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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');
Expand All @@ -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) {
Expand Down
74 changes: 74 additions & 0 deletions bin/lib/frames.js
Original file line number Diff line number Diff line change
@@ -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 };
49 changes: 26 additions & 23 deletions bin/lib/handlers.js
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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);
Expand All @@ -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)
});

Expand All @@ -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);
}

Expand All @@ -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 };
}
}
Expand Down
4 changes: 4 additions & 0 deletions docs/guide/core-concepts.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
17 changes: 11 additions & 6 deletions src/Frame/Frame.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -71,23 +72,23 @@ 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)));
}

/**
* @param array<string, mixed> $options
*/
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)));
}

/**
* @param array<string, mixed> $options
*/
public function getByPlaceholder(string $text, array $options = []): LocatorInterface
{
return $this->locator(\sprintf('[placeholder="%s"]', $text));
return $this->locator(\sprintf('[placeholder=%s]', LiteralSelector::css($text)));
}

/**
Expand All @@ -109,23 +110,23 @@ 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)));
}

/**
* @param array<string, mixed> $options
*/
public function getByText(string $text, array $options = []): LocatorInterface
{
return $this->locator(\sprintf('text="%s"', $text));
return $this->locator('internal:text='.LiteralSelector::text($text).'s');
}

/**
* @param array<string, mixed> $options
*/
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
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading