Skip to content

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

feat(api): Locator.highlight({ style }) (#40215)

Pavel Feldman15e92e12f114
diff --git a/docs/src/api/class-locator.md b/docs/src/api/class-locator.md
index 33171d0472..09157a48aa 100644
--- a/docs/src/api/class-locator.md
+++ b/docs/src/api/class-locator.md
@@ -1441,6 +1441,12 @@ Hide element highlight added with Highlight the corresponding element(s) on the
Highlight the corresponding element(s) on the screen. Useful for debugging, don't commit the code that uses [`method: Locator.highlight`].
+### option: Locator.highlight.style
+* since: v1.60
+- `style` <[string]>
+
+Additional inline CSS applied to the highlight overlay, e.g. `"outline: 2px dashed red"`.
+
## async method: Locator.hover
* since: v1.14
diff --git a/packages/injected/src/highlight.ts b/packages/injected/src/highlight.ts
index 6508bbca60..e1c927bc62 100644
--- a/packages/injected/src/highlight.ts
+++ b/packages/injected/src/highlight.ts
@@ -63,7 +63,7 @@ export class Highlight {
private _injectedScript: InjectedScript;
private _rafRequest: number | undefined;
private _language: Language = 'javascript';
- private _elementHighlightSelectors = new Map<string, ParsedSelector>();
+ private _elementHighlightSelectors = new Map<string, { selector: ParsedSelector, cssStyle?: string }>();
constructor(injectedScript: InjectedScript) {
this._injectedScript = injectedScript;
@@ -124,11 +124,9 @@ export class Highlight {
this._language = language;
}
- addElementHighlight(selector: ParsedSelector) {
+ addElementHighlight(selector: ParsedSelector, cssStyle?: string) {
const key = stringifySelector(selector);
- if (this._elementHighlightSelectors.has(key))
- return;
- this._elementHighlightSelectors.set(key, selector);
+ this._elementHighlightSelectors.set(key, { selector, cssStyle });
this._ensureElementHighlightRaf();
}
@@ -150,13 +148,13 @@ export class Highlight {
return;
const tick = () => {
const entries: HighlightEntry[] = [];
- for (const selector of this._elementHighlightSelectors.values()) {
+ for (const { selector, cssStyle } of this._elementHighlightSelectors.values()) {
const elements = this._injectedScript.querySelectorAll(selector, this._injectedScript.document.documentElement);
const locator = asLocator(this._language, stringifySelector(selector));
const color = elements.length > 1 ? '#f6b26b7f' : '#6fa8dc7f';
for (let i = 0; i < elements.length; ++i) {
const suffix = elements.length > 1 ? ` [${i + 1} of ${elements.length}]` : '';
- entries.push({ element: elements[i], color, tooltipText: locator + suffix });
+ entries.push({ element: elements[i], color, tooltipText: locator + suffix, cssStyle });
}
}
this.updateHighlight(entries);
@@ -412,6 +410,8 @@ export class Highlight {
return false;
if (entries[i].color !== this._renderedEntries[i].color)
return false;
+ if (entries[i].cssStyle !== this._renderedEntries[i].cssStyle)
+ return false;
const oldBox = this._renderedEntries[i].box;
if (!oldBox)
return false;
diff --git a/packages/injected/src/injectedScript.ts b/packages/injected/src/injectedScript.ts
index d3e7494e6e..58b2061938 100644
--- a/packages/injected/src/injectedScript.ts
+++ b/packages/injected/src/injectedScript.ts
@@ -1313,9 +1313,9 @@ export class InjectedScript {
return this._highlight;
}
- addHighlight(selector: ParsedSelector) {
+ addHighlight(selector: ParsedSelector, style?: string) {
const highlight = this._ensureHighlight();
- highlight.addElementHighlight(selector);
+ highlight.addElementHighlight(selector, style);
}
removeHighlight(selector: ParsedSelector) {
diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.ts
index 451fd0dced..eea0869050 100644
--- a/packages/playwright-client/types/types.d.ts
+++ b/packages/playwright-client/types/types.d.ts
@@ -12585,6 +12585,14 @@ export interface Locator {
elementHandle(options?: {
timeout?: number;
}): Promise<null|ElementHandle<SVGElement | HTMLElement>>;
+ /**
+ * Highlight the corresponding element(s) on the screen. Useful for debugging, don't commit the code that uses
+ * [locator.highlight([options])](https://playwright.dev/docs/api/class-locator#locator-highlight).
+ * @param options
+ */
+ highlight(options?: {
+ style?: string | { [key: string]: string | number };
+ }): Promise<Disposable>;
/**
* Returns a human-readable representation of the locator, using the
* [locator.description()](https://playwright.dev/docs/api/class-locator#locator-description) if one exists;
@@ -13814,16 +13822,11 @@ export interface Locator {
/**
* Hide element highlight added with Highlight the corresponding element(s) on the screen. Useful for debugging, don't
- * commit the code that uses [locator.highlight()](https://playwright.dev/docs/api/class-locator#locator-highlight).
+ * commit the code that uses
+ * [locator.highlight([options])](https://playwright.dev/docs/api/class-locator#locator-highlight).
*/
hideHighlight(): Promise<void>;
- /**
- * Highlight the corresponding element(s) on the screen. Useful for debugging, don't commit the code that uses
- * [locator.highlight()](https://playwright.dev/docs/api/class-locator#locator-highlight).
- */
- highlight(): Promise<Disposable>;
-
/**
* Hover over the matching element.
*
diff --git a/packages/playwright-core/src/client/frame.ts b/packages/playwright-core/src/client/frame.ts
index 30f490ee0c..c3220dcaa0 100644
--- a/packages/playwright-core/src/client/frame.ts
+++ b/packages/playwright-core/src/client/frame.ts
@@ -313,8 +313,8 @@ export class Frame extends ChannelOwner<channels.FrameChannel> implements api.Fr
return await this._channel.fill({ selector, value, ...options, timeout: this._timeout(options) });
}
- async _highlight(selector: string) {
- return await this._channel.highlight({ selector });
+ async _highlight(selector: string, style?: string) {
+ return await this._channel.highlight({ selector, style });
}
async _hideHighlight(selector: string) {
diff --git a/packages/playwright-core/src/client/locator.ts b/packages/playwright-core/src/client/locator.ts
index 8e93de4dab..08ba14ab73 100644
--- a/packages/playwright-core/src/client/locator.ts
+++ b/packages/playwright-core/src/client/locator.ts
@@ -151,8 +151,9 @@ export class Locator implements api.Locator {
return await this._frame._highlight(this._selector);
}
- async highlight() {
- await this._frame._highlight(this._selector);
+ async highlight(options: { style?: string | Record<string, string | number> } = {}) {
+ const style = typeof options.style === 'object' ? cssObjectToString(options.style) : options.style;
+ await this._frame._highlight(this._selector, style);
return new DisposableStub(() => this.hideHighlight());
}
@@ -482,3 +483,10 @@ export function testIdAttributeName(): string {
export function setTestIdAttribute(attributeName: string) {
_testIdAttributeName = attributeName;
}
+
+function cssObjectToString(style: Record<string, string | number>): string {
+ return Object.entries(style).map(([key, value]) => {
+ const property = key.startsWith('--') ? key : key.replace(/[A-Z]/g, m => '-' + m.toLowerCase());
+ return `${property}: ${value}`;
+ }).join('; ');
+}
diff --git a/packages/playwright-core/src/protocol/validator.ts b/packages/playwright-core/src/protocol/validator.ts
index ea409ad481..b25ef82721 100644
--- a/packages/playwright-core/src/protocol/validator.ts
+++ b/packages/playwright-core/src/protocol/validator.ts
@@ -1774,6 +1774,7 @@ scheme.FrameResolveSelectorResult = tObject({
});
scheme.FrameHighlightParams = tObject({
selector: tString,
+ style: tOptional(tString),
});
scheme.FrameHighlightResult = tOptional(tObject({}));
scheme.FrameHideHighlightParams = tObject({
diff --git a/packages/playwright-core/src/server/dispatchers/frameDispatcher.ts b/packages/playwright-core/src/server/dispatchers/frameDispatcher.ts
index 5b205e00c6..0d47671855 100644
--- a/packages/playwright-core/src/server/dispatchers/frameDispatcher.ts
+++ b/packages/playwright-core/src/server/dispatchers/frameDispatcher.ts
@@ -265,7 +265,7 @@ export class FrameDispatcher extends Dispatcher<Frame, channels.FrameChannel, Br
}
async highlight(params: channels.FrameHighlightParams, progress: Progress): Promise<void> {
- return await this._frame.addHighlight(progress, params.selector);
+ return await this._frame.addHighlight(progress, params.selector, params.style);
}
async hideHighlight(params: channels.FrameHideHighlightParams, progress: Progress): Promise<void> {
diff --git a/packages/playwright-core/src/server/frames.ts b/packages/playwright-core/src/server/frames.ts
index b64011e586..aef7d3d1d2 100644
--- a/packages/playwright-core/src/server/frames.ts
+++ b/packages/playwright-core/src/server/frames.ts
@@ -1319,13 +1319,13 @@ export class Frame extends SdkObject<FrameEventMap> {
}, undefined, options, scope);
}
- async addHighlight(progress: Progress, selector: string) {
+ async addHighlight(progress: Progress, selector: string, style?: string) {
const resolved = await progress.race(this.selectors.resolveInjectedForSelector(selector));
if (!resolved)
return;
- return await progress.race(resolved.injected.evaluate((injected, { info }) => {
- return injected.addHighlight(info.parsed);
- }, { info: resolved.info }));
+ return await progress.race(resolved.injected.evaluate((injected, { info, style }) => {
+ return injected.addHighlight(info.parsed, style);
+ }, { info: resolved.info, style }));
}
async removeHighlight(progress: Progress, selector: string) {
diff --git a/packages/playwright-core/src/tools/backend/devtools.ts b/packages/playwright-core/src/tools/backend/devtools.ts
index 1100e341c0..1858e64c70 100644
--- a/packages/playwright-core/src/tools/backend/devtools.ts
+++ b/packages/playwright-core/src/tools/backend/devtools.ts
@@ -91,13 +91,15 @@ const highlight = defineTabTool({
name: 'browser_highlight',
title: 'Highlight element',
description: 'Show a persistent highlight overlay around the element on the page.',
- inputSchema: elementSchema,
+ inputSchema: elementSchema.extend({
+ style: z.string().optional().describe('Additional inline CSS applied to the highlight overlay, e.g. "outline: 2px dashed red".'),
+ }),
type: 'readOnly',
},
handle: async (tab, params, response) => {
const { locator, resolved } = await tab.refLocator(params);
- await (await locator.normalize()).highlight();
+ await locator.highlight({ style: params.style });
response.addTextResult(`Highlighted ${resolved}`);
},
});
@@ -114,7 +116,7 @@ const hideHighlight = defineTabTool({
handle: async (tab, params, response) => {
const { locator, resolved } = await tab.refLocator(params);
- await (await locator.normalize()).hideHighlight();
+ await locator.hideHighlight();
response.addTextResult(`Hid highlight for ${resolved}`);
},
});
diff --git a/packages/playwright-core/src/tools/backend/snapshot.ts b/packages/playwright-core/src/tools/backend/snapshot.ts
index 39a75d8944..96db219f97 100644
--- a/packages/playwright-core/src/tools/backend/snapshot.ts
+++ b/packages/playwright-core/src/tools/backend/snapshot.ts
@@ -19,16 +19,19 @@ import { formatObject, formatObjectOrVoid } from '@isomorphic/stringUtils';
import { defineTabTool } from './tool';
+export const optionalElementSchema = z.object({
+ ref: z.string().optional().describe('Element reference from the previous page snapshot to capture a partial snapshot instead of the whole page'),
+ selector: z.string().optional().describe('Element selector of the root element to capture a partial snapshot instead of the whole page'),
+});
+
const snapshot = defineTabTool({
capability: 'core',
schema: {
name: 'browser_snapshot',
title: 'Page snapshot',
description: 'Capture accessibility snapshot of the current page, this is better than screenshot',
- inputSchema: z.object({
+ inputSchema: optionalElementSchema.extend({
filename: z.string().optional().describe('Save snapshot to markdown file instead of returning it in the response.'),
- ref: z.string().optional().describe('Element reference from the previous page snapshot to capture a partial snapshot instead of the whole page'),
- selector: z.string().optional().describe('Element selector of the root element to capture a partial snapshot instead of the whole page'),
depth: z.number().optional().describe('Limit the depth of the snapshot tree'),
}),
type: 'readOnly',
diff --git a/packages/playwright-core/src/tools/cli-daemon/commands.ts b/packages/playwright-core/src/tools/cli-daemon/commands.ts
index 5398be49d0..7a02b86c26 100644
--- a/packages/playwright-core/src/tools/cli-daemon/commands.ts
+++ b/packages/playwright-core/src/tools/cli-daemon/commands.ts
@@ -369,13 +369,14 @@ const highlight = declareCommand({
description: 'Show (or with --hide, remove) a highlight overlay for an element',
category: 'devtools',
args: z.object({
- target: z.string().describe('Exact target element reference from the page snapshot, or a unique element selector'),
+ element: z.string().describe('Exact target element reference from the page snapshot, or a unique element selector'),
}),
options: z.object({
hide: z.boolean().optional().describe('Hide a previously added highlight for this element'),
+ style: z.string().optional().describe('Additional inline CSS applied to the highlight overlay, e.g. "outline: 2px dashed red"'),
}),
toolName: ({ hide }) => hide ? 'browser_hide_highlight' : 'browser_highlight',
- toolParams: ({ target }) => ({ ...asRef(target) }),
+ toolParams: ({ element, style }) => ({ ...asRef(element), style }),
});
const evaluate = declareCommand({
diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.ts
index 451fd0dced..eea0869050 100644
--- a/packages/playwright-core/types/types.d.ts
+++ b/packages/playwright-core/types/types.d.ts
@@ -12585,6 +12585,14 @@ export interface Locator {
elementHandle(options?: {
timeout?: number;
}): Promise<null|ElementHandle<SVGElement | HTMLElement>>;
+ /**
+ * Highlight the corresponding element(s) on the screen. Useful for debugging, don't commit the code that uses
+ * [locator.highlight([options])](https://playwright.dev/docs/api/class-locator#locator-highlight).
+ * @param options
+ */
+ highlight(options?: {
+ style?: string | { [key: string]: string | number };
+ }): Promise<Disposable>;
/**
* Returns a human-readable representation of the locator, using the
* [locator.description()](https://playwright.dev/docs/api/class-locator#locator-description) if one exists;
@@ -13814,16 +13822,11 @@ export interface Locator {
/**
* Hide element highlight added with Highlight the corresponding element(s) on the screen. Useful for debugging, don't
- * commit the code that uses [locator.highlight()](https://playwright.dev/docs/api/class-locator#locator-highlight).
+ * commit the code that uses
+ * [locator.highlight([options])](https://playwright.dev/docs/api/class-locator#locator-highlight).
*/
hideHighlight(): Promise<void>;
- /**
- * Highlight the corresponding element(s) on the screen. Useful for debugging, don't commit the code that uses
- * [locator.highlight()](https://playwright.dev/docs/api/class-locator#locator-highlight).
- */
- highlight(): Promise<Disposable>;
-
/**
* Hover over the matching element.
*
diff --git a/packages/protocol/src/channels.d.ts b/packages/protocol/src/channels.d.ts
index 8ddedb1074..57b97c55bf 100644
--- a/packages/protocol/src/channels.d.ts
+++ b/packages/protocol/src/channels.d.ts
@@ -3107,9 +3107,10 @@ export type FrameResolveSelectorResult = {
};
export type FrameHighlightParams = {
selector: string,
+ style?: string,
};
export type FrameHighlightOptions = {
-
+ style?: string,
};
export type FrameHighlightResult = void;
export type FrameHideHighlightParams = {
diff --git a/packages/protocol/src/protocol.yml b/packages/protocol/src/protocol.yml
index 8769c9f3e5..9060ef4cf8 100644
--- a/packages/protocol/src/protocol.yml
+++ b/packages/protocol/src/protocol.yml
@@ -2528,6 +2528,7 @@ Frame:
internal: true
parameters:
selector: string
+ style: string?
hideHighlight:
internal: true
diff --git a/tests/library/locator-highlight.spec.ts b/tests/library/locator-highlight.spec.ts
new file mode 100644
index 0000000000..7cc7a33866
--- /dev/null
+++ b/tests/library/locator-highlight.spec.ts
@@ -0,0 +1,77 @@
+/**
+ * Copyright Microsoft Corporation. All rights reserved.
+ *
+ * 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 { expect, browserTest as test } from '../config/browserTest';
+
+test.skip(({ mode }) => mode !== 'default', 'Highlight overlay uses an open shadow root only in default mode');
+
+test('highlight should accept a CSS string style', async ({ browser, server }) => {
+ const context = await browser.newContext();
+ const page = await context.newPage();
+ await page.goto(server.PREFIX + '/input/button.html');
+
+ await page.getByRole('button').highlight({ style: 'outline: 3px solid rgb(255, 0, 0); background-color: rgba(0, 255, 0, 0.25)' });
+
+ const highlight = page.locator('x-pw-highlight');
+ await expect(highlight).toBeVisible();
+ const style = await highlight.evaluate((el: HTMLElement) => ({
+ outline: el.style.outline,
+ backgroundColor: el.style.backgroundColor,
+ }));
+ expect(style.outline).toBe('rgb(255, 0, 0) solid 3px');
+ expect(style.backgroundColor).toBe('rgba(0, 255, 0, 0.25)');
+
+ await context.close();
+});
+
+test('highlight should accept an object style (JS only)', async ({ browser, server }) => {
+ const context = await browser.newContext();
+ const page = await context.newPage();
+ await page.goto(server.PREFIX + '/input/button.html');
+
+ await page.getByRole('button').highlight({
+ style: {
+ outline: '2px dashed rgb(0, 0, 255)',
+ backgroundColor: 'rgba(255, 255, 0, 0.2)',
+ },
+ });
+
+ const highlight = page.locator('x-pw-highlight');
+ await expect(highlight).toBeVisible();
+ const style = await highlight.evaluate((el: HTMLElement) => ({
+ outline: el.style.outline,
+ backgroundColor: el.style.backgroundColor,
+ }));
+ expect(style.outline).toBe('rgb(0, 0, 255) dashed 2px');
+ expect(style.backgroundColor).toBe('rgba(255, 255, 0, 0.2)');
+
+ await context.close();
+});
+
+test('hideHighlight removes a styled highlight', async ({ browser, server }) => {
+ const context = await browser.newContext();
+ const page = await context.newPage();
+ await page.goto(server.PREFIX + '/input/button.html');
+
+ const button = page.getByRole('button');
+ await button.highlight({ style: 'outline: 2px solid red' });
+ await expect(page.locator('x-pw-highlight')).toBeVisible();
+
+ await button.hideHighlight();
+ await expect(page.locator('x-pw-highlight')).toHaveCount(0);
+
+ await context.close();
+});
diff --git a/tests/mcp/cli-devtools.spec.ts b/tests/mcp/cli-devtools.spec.ts
index 1d34ca7d4f..246bcee70e 100644
--- a/tests/mcp/cli-devtools.spec.ts
+++ b/tests/mcp/cli-devtools.spec.ts
@@ -196,7 +196,7 @@ test('highlight', async ({ cdpServer, cli, server }) => {
const highlight = page.locator('x-pw-highlight');
const tooltip = page.locator('x-pw-tooltip-line');
await expect(highlight).toBeVisible();
- await expect(tooltip).toHaveText(`getByRole('button', { name: 'Submit' })`);
+ await expect(tooltip).toHaveText(`locator('aria-ref=e2')`);
expect(await highlight.boundingBox()).toEqual(await page.getByRole('button', { name: 'Submit' }).boundingBox());
});
@@ -216,3 +216,25 @@ test('highlight --hide', async ({ cdpServer, cli, server }) => {
expect(output).toContain(`Hid highlight for getByRole('button', { name: 'Submit' })`);
await expect(page.locator('x-pw-highlight')).toHaveCount(0);
});
+
+test('highlight --style', async ({ cdpServer, cli, server }) => {
+ server.setContent('/', `<button>Submit</button>`, 'text/html');
+ const browserContext = await cdpServer.start();
+ const [page] = browserContext.pages();
+ await page.goto(server.PREFIX);
+
+ await cli('attach', `--cdp=${cdpServer.endpoint}`);
+ await cli('snapshot');
+
+ await cli('highlight', 'e2', '--style=outline: 3px solid rgb(255, 0, 0); background-color: rgba(0, 255, 0, 0.25)');
+
+ const highlight = page.locator('x-pw-highlight');
+ await expect(highlight).toBeVisible();
+ expect(await highlight.evaluate((el: HTMLElement) => ({
+ outline: el.style.outline,
+ backgroundColor: el.style.backgroundColor,
+ }))).toEqual({
+ outline: 'rgb(255, 0, 0) solid 3px',
+ backgroundColor: 'rgba(0, 255, 0, 0.25)',
+ });
+});
diff --git a/tests/mcp/devtools.spec.ts b/tests/mcp/devtools.spec.ts
index b7d37e35ed..51ab6c0c93 100644
--- a/tests/mcp/devtools.spec.ts
+++ b/tests/mcp/devtools.spec.ts
@@ -58,10 +58,41 @@ test('browser_highlight', async ({ cdpServer, startClient, server }) => {
const highlight = page.locator('x-pw-highlight');
const tooltip = page.locator('x-pw-tooltip-line');
await expect(highlight).toBeVisible();
- await expect(tooltip).toHaveText(`getByRole('button', { name: 'Submit' })`);
+ await expect(tooltip).toHaveText(`locator('aria-ref=e2')`);
expect(await highlight.boundingBox()).toEqual(await page.getByRole('button', { name: 'Submit' }).boundingBox());
});
+test('browser_highlight with style', async ({ cdpServer, startClient, server }) => {
+ server.setContent('/', `<button>Submit</button>`, 'text/html');
+ const browserContext = await cdpServer.start();
+ const [page] = browserContext.pages();
+ await page.goto(server.PREFIX);
+
+ const { client } = await startClient({ args: [`--cdp-endpoint=${cdpServer.endpoint}`] });
+ await client.callTool({ name: 'browser_snapshot' });
+
+ expect(await client.callTool({
+ name: 'browser_highlight',
+ arguments: {
+ element: 'Submit button',
+ ref: 'e2',
+ style: 'outline: 3px solid rgb(255, 0, 0); background-color: rgba(0, 255, 0, 0.25)',
+ },
+ })).toHaveResponse({
+ result: `Highlighted getByRole('button', { name: 'Submit' })`,
+ });
+
+ const highlight = page.locator('x-pw-highlight');
+ await expect(highlight).toBeVisible();
+ expect(await highlight.evaluate((el: HTMLElement) => ({
+ outline: el.style.outline,
+ backgroundColor: el.style.backgroundColor,
+ }))).toEqual({
+ outline: 'rgb(255, 0, 0) solid 3px',
+ backgroundColor: 'rgba(0, 255, 0, 0.25)',
+ });
+});
+
test('browser_hide_highlight', async ({ cdpServer, startClient, server }) => {
server.setContent('/', `<button>Submit</button>`, 'text/html');
const browserContext = await cdpServer.start();
diff --git a/utils/generate_types/overrides.d.ts b/utils/generate_types/overrides.d.ts
index 5a1b224213..f8e58cf26c 100644
--- a/utils/generate_types/overrides.d.ts
+++ b/utils/generate_types/overrides.d.ts
@@ -203,6 +203,9 @@ export interface Locator {
elementHandle(options?: {
timeout?: number;
}): Promise<null|ElementHandle<SVGElement | HTMLElement>>;
+ highlight(options?: {
+ style?: string | { [key: string]: string | number };
+ }): Promise<Disposable>;
toString(): string;
}