Skip to content

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

fix(overlay): refactor overlay and annotation APIs (#39834)

Pavel Feldman91f8a679b817
diff --git a/docs/src/api/class-overlay.md b/docs/src/api/class-overlay.md
index a0b1c1453d..9d25704439 100644
--- a/docs/src/api/class-overlay.md
+++ b/docs/src/api/class-overlay.md
@@ -3,53 +3,54 @@
Interface for managing page overlays that display persistent visual indicators on top of the page.
-## async method: Overlay.add
+## async method: Overlay.show
* since: v1.59
- returns: <[Disposable]>
Adds an overlay with the given HTML content. The overlay is displayed on top of the page until removed. Returns a disposable that removes the overlay when disposed.
-### param: Overlay.add.html
+### param: Overlay.show.html
* since: v1.59
- `html` <[string]>
HTML content for the overlay.
-### option: Overlay.add.timeout
+### option: Overlay.show.duration
* since: v1.59
-- `timeout` <[int]>
+- `duration` <[float]>
-Optional timeout to remove the decoration after. Decoration stays until dismissed if not provided.
+Duration in milliseconds after which the overlay is automatically removed. Overlay stays until dismissed if not provided.
-## async method: Overlay.configure
+## async method: Overlay.chapter
* since: v1.59
-Configures overlay behavior.
+Shows a chapter overlay with a title and optional description, centered on the page with a blurred backdrop. Useful for narrating video recordings. The overlay is removed after the specified duration, or 2000ms.
-### option: Overlay.configure.actionDelay
+### param: Overlay.chapter.title
* since: v1.59
-- `actionDelay` <[int]>
+- `title` <[string]>
-Delay in milliseconds between actions when overlay is active.
+Title text displayed prominently in the overlay.
-### option: Overlay.configure.actionStyle
+### option: Overlay.chapter.description
* since: v1.59
-- `actionStyle` <[string]>
+- `description` <[string]>
-CSS style string applied to the action title element displayed during actions.
+Optional description text displayed below the title.
-### option: Overlay.configure.locatorStyle
+### option: Overlay.chapter.duration
* since: v1.59
-- `locatorStyle` <[string]>
+- `duration` <[float]>
-CSS style string applied to the locator highlight element displayed during actions.
+Duration in milliseconds after which the overlay is automatically removed. Defaults to `2000`.
-## async method: Overlay.hide
+## async method: Overlay.setVisible
* since: v1.59
-Hides all overlays without removing them. Overlays can be shown again with [`method: Overlay.show`].
+Sets visibility of all overlays without removing them.
-## async method: Overlay.show
+### param: Overlay.setVisible.visible
* since: v1.59
+- `visible` <[boolean]>
-Shows previously hidden overlays.
+Whether overlays should be visible.
diff --git a/docs/src/api/class-screencast.md b/docs/src/api/class-screencast.md
index 095c800f88..a99ff8216a 100644
--- a/docs/src/api/class-screencast.md
+++ b/docs/src/api/class-screencast.md
@@ -42,6 +42,15 @@ If a screencast is already active (e.g. started by tracing or video recording),
Defaults to 800×800.
+### option: Screencast.start.annotate
+* since: v1.59
+- `annotate` ?<[Object]>
+ - `duration` ?<[float]> How long each annotation is displayed in milliseconds. Defaults to `500`.
+ - `position` ?<[AnnotatePosition]<"top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right">> Position of the action title overlay. Defaults to `"top-right"`.
+ - `fontSize` ?<[int]> Font size of the action title in pixels. Defaults to `24`.
+
+If specified, enables visual annotations on interacted elements during screencast. Interacted elements are highlighted with a semi-transparent blue box and click points are shown as red circles.
+
## async method: Screencast.stop
* since: v1.59
* langs: js
diff --git a/docs/src/api/class-video.md b/docs/src/api/class-video.md
index 945419c3f6..6d5c11ed7d 100644
--- a/docs/src/api/class-video.md
+++ b/docs/src/api/class-video.md
@@ -144,6 +144,15 @@ Path where the video should be saved when the recording is stopped.
Optional dimensions of the recorded video. If not specified the size will be equal to page viewport scaled down to fit into 800x800. Actual picture of the page will be scaled down if necessary to fit the specified size.
+### option: Video.start.annotate
+* since: v1.59
+- `annotate` ?<[Object]>
+ - `duration` ?<[float]> How long each annotation is displayed in milliseconds. Defaults to `500`.
+ - `position` ?<[AnnotatePosition]<"top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right">> Position of the action title overlay. Defaults to `"top-right"`.
+ - `fontSize` ?<[int]> Font size of the action title in pixels. Defaults to `24`.
+
+If specified, enables visual annotations on interacted elements during video recording. Interacted elements are highlighted with a semi-transparent blue box and click points are shown as red circles.
+
## async method: Video.stop
* since: v1.59
diff --git a/docs/src/api/params.md b/docs/src/api/params.md
index 14ab34518b..4b678f2f96 100644
--- a/docs/src/api/params.md
+++ b/docs/src/api/params.md
@@ -810,6 +810,10 @@ When set to `minimal`, only record information necessary for routing from HAR. T
Actual picture of each page will be scaled down if necessary to fit the specified size.
- `width` <[int]> Video frame width.
- `height` <[int]> Video frame height.
+ - `annotate` ?<[Object]> If specified, enables visual annotations on interacted elements during video recording.
+ - `duration` ?<[float]> How long each annotation is displayed in milliseconds. Defaults to `500`.
+ - `position` ?<[AnnotatePosition]<"top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right">> Position of the action title overlay. Defaults to `"top-right"`.
+ - `fontSize` ?<[int]> Font size of the action title in pixels. Defaults to `24`.
Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded. Make
sure to await [`method: BrowserContext.close`] for videos to be saved.
diff --git a/docs/src/test-api/class-testoptions.md b/docs/src/test-api/class-testoptions.md
index caf88422a8..922db3bb9f 100644
--- a/docs/src/test-api/class-testoptions.md
+++ b/docs/src/test-api/class-testoptions.md
@@ -627,9 +627,13 @@ export default defineConfig({
- `height` <[int]>
- `annotate` ?<[Object]> If specified, visually annotates the video with test information and action highlights.
- `action` ?<[Object]> Controls visual annotations on interacted elements.
- - `delay` ?<[int]> How long each annotation is displayed in milliseconds. Defaults to `500`.
+ - `duration` ?<[float]> How long each annotation is displayed in milliseconds. Defaults to `500`.
+ - `position` ?<[AnnotatePosition]<"top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right">> Position of the action title overlay. Defaults to `"top-right"`.
+ - `fontSize` ?<[int]> Font size of the action title in pixels. Defaults to `24`.
- `test` ?<[Object]> Controls test information displayed as a status overlay in the video.
- `level` ?<[TestAnnotationLevel]<"file"|"test"|"step">> Level of the detail to include about the current test.
+ - `position` ?<[AnnotatePosition]<"top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right">> Position of the test information overlay. Defaults to `"top-left"`.
+ - `fontSize` ?<[int]> Font size of the test information in pixels. Defaults to `14`.
Whether to record video for each test. Defaults to `'off'`.
* `'off'`: Do not record video.
diff --git a/docs/src/videos.md b/docs/src/videos.md
index d0351435de..6d1a59f9e7 100644
--- a/docs/src/videos.md
+++ b/docs/src/videos.md
@@ -38,9 +38,9 @@ await context.close();
You can also specify video size and annotation. The video size defaults to the viewport size scaled down to fit 800x800. The video of the viewport is placed in the top-left corner of the output video, scaled down to fit if necessary. You may need to set the viewport size to match your desired video size.
-When `action` is specified, each action can be visually highlighted in the video with the element outline and action title subtitle, and test information can be shown as a status overlay. The `action` sub-option controls element highlights with an optional `delay` (defaults to `500`ms). The `test` sub-option controls which test information components are displayed.
+When `annotate` is specified, each action will be visually highlighted in the video with the element outline and action title subtitle. The optional `duration` property controls how long each annotation is displayed (defaults to `500`ms).
-```js tab=js-test title="playwright.config.ts"
+```js title="playwright.config.ts"
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
@@ -48,23 +48,22 @@ export default defineConfig({
mode: 'on-first-retry',
size: { width: 640, height: 480 },
annotate: {
- action: { delay: 500 },
- test: { level: 'step' },
+ action: {
+ duration: 500,
+ position: 'top-right',
+ fontSize: 14,
+ },
+ test: {
+ level: 'step',
+ position: 'top-left',
+ fontSize: 12,
+ }
},
},
},
});
```
-```js tab=js-library
-const context = await browser.newContext({
- recordVideo: {
- dir: 'videos/',
- size: { width: 640, height: 480 },
- }
-});
-```
-
For multi-page scenarios, you can access the video file associated with the page via the
[`method: Page.video`].
diff --git a/examples/todomvc/playwright.config.ts b/examples/todomvc/playwright.config.ts
index 069f00fdda..2f6bdc9d4a 100644
--- a/examples/todomvc/playwright.config.ts
+++ b/examples/todomvc/playwright.config.ts
@@ -47,7 +47,13 @@ export default defineConfig({
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry',
- video: { mode: 'on', annotate: { action: { delay: 500 }, test: { level: 'step' } } },
+ video: {
+ mode: 'on',
+ annotate: {
+ action: {},
+ test: {}
+ }
+ },
},
/* Configure projects for major browsers */
diff --git a/packages/injected/src/highlight.ts b/packages/injected/src/highlight.ts
index 6f5f9b9c53..f0356ec5a7 100644
--- a/packages/injected/src/highlight.ts
+++ b/packages/injected/src/highlight.ts
@@ -156,7 +156,7 @@ export class Highlight {
this._actionPointElement.hidden = true;
}
- showActionTitle(text: string, fadeDuration: number, cssStyle?: string) {
+ showActionTitle(text: string, fadeDuration: number, position?: string, fontSize?: number) {
this._titleElement.textContent = text;
this._titleElement.hidden = false;
if (fadeDuration) {
@@ -165,8 +165,46 @@ export class Highlight {
} else {
this._titleElement.style.animation = '';
}
- if (cssStyle)
- this._titleElement.style.cssText += ';' + cssStyle;
+
+ // Reset positioning
+ this._titleElement.style.top = '';
+ this._titleElement.style.bottom = '';
+ this._titleElement.style.left = '';
+ this._titleElement.style.right = '';
+ this._titleElement.style.transform = '';
+
+ switch (position) {
+ case 'top-left':
+ this._titleElement.style.top = '6px';
+ this._titleElement.style.left = '6px';
+ break;
+ case 'top':
+ this._titleElement.style.top = '6px';
+ this._titleElement.style.left = '50%';
+ this._titleElement.style.transform = 'translateX(-50%)';
+ break;
+ case 'bottom-left':
+ this._titleElement.style.bottom = '6px';
+ this._titleElement.style.left = '6px';
+ break;
+ case 'bottom':
+ this._titleElement.style.bottom = '6px';
+ this._titleElement.style.left = '50%';
+ this._titleElement.style.transform = 'translateX(-50%)';
+ break;
+ case 'bottom-right':
+ this._titleElement.style.bottom = '6px';
+ this._titleElement.style.right = '6px';
+ break;
+ case 'top-right':
+ default:
+ this._titleElement.style.top = '6px';
+ this._titleElement.style.right = '6px';
+ break;
+ }
+
+ if (fontSize)
+ this._titleElement.style.fontSize = fontSize + 'px';
}
hideActionTitle() {
@@ -192,6 +230,10 @@ export class Highlight {
return id;
}
+ getUserOverlay(id: string): HTMLElement | undefined {
+ return this._userOverlays.get(id);
+ }
+
removeUserOverlay(id: string) {
const element = this._userOverlays.get(id);
if (element) {
@@ -202,15 +244,9 @@ export class Highlight {
this._userOverlayContainer.hidden = true;
}
- hideUserOverlays() {
- this._userOverlayHidden = true;
- this._userOverlayContainer.hidden = true;
- }
-
- showUserOverlays() {
- this._userOverlayHidden = false;
- if (this._userOverlays.size > 0)
- this._userOverlayContainer.hidden = false;
+ setUserOverlaysVisible(visible: boolean) {
+ this._userOverlayHidden = !visible;
+ this._userOverlayContainer.hidden = !visible || this._userOverlays.size === 0;
}
clearHighlight() {
diff --git a/packages/injected/src/injectedScript.ts b/packages/injected/src/injectedScript.ts
index 1bb25c5a5e..a0882d2b05 100644
--- a/packages/injected/src/injectedScript.ts
+++ b/packages/injected/src/injectedScript.ts
@@ -1321,7 +1321,7 @@ export class InjectedScript {
this._highlight.runHighlightOnRaf(selector);
}
- setScreencastAnnotation(annotation: { point?: channels.Point, box?: channels.Rect, actionTitle?: string, delay?: number, actionStyle?: string, locatorStyle?: string } | null) {
+ setScreencastAnnotation(annotation: { point?: channels.Point, box?: channels.Rect, actionTitle?: string, duration?: number, position?: string, fontSize?: number } | null) {
const highlight = this._ensureHighlight();
if (!annotation) {
highlight.updateHighlight([]);
@@ -1329,7 +1329,7 @@ export class InjectedScript {
highlight.hideActionTitle();
return;
}
- const fadeDuration = annotation.delay ?? 500;
+ const fadeDuration = annotation.duration ?? 500;
if (annotation.box) {
highlight.updateHighlight([{
@@ -1337,13 +1337,12 @@ export class InjectedScript {
color: 'rgba(0, 128, 255, 0.15)',
borderColor: 'rgba(0, 128, 255, 0.6)',
fadeDuration,
- cssStyle: annotation.locatorStyle,
}]);
}
if (annotation.point)
highlight.showActionPoint(annotation.point.x, annotation.point.y, fadeDuration);
if (annotation.actionTitle)
- highlight.showActionTitle(annotation.actionTitle, fadeDuration, annotation.actionStyle);
+ highlight.showActionTitle(annotation.actionTitle, fadeDuration, annotation.position, annotation.fontSize);
}
addUserOverlay(id: string, html: string) {
@@ -1351,19 +1350,19 @@ export class InjectedScript {
highlight.addUserOverlay(id, html);
}
- removeUserOverlay(id: string) {
+ getUserOverlay(id: string): HTMLElement | undefined {
const highlight = this._ensureHighlight();
- highlight.removeUserOverlay(id);
+ return highlight.getUserOverlay(id);
}
- hideUserOverlays() {
+ removeUserOverlay(id: string) {
const highlight = this._ensureHighlight();
- highlight.hideUserOverlays();
+ highlight.removeUserOverlay(id);
}
- showUserOverlays() {
+ setUserOverlaysVisible(visible: boolean) {
const highlight = this._ensureHighlight();
- highlight.showUserOverlays();
+ highlight.setUserOverlaysVisible(visible);
}
hideHighlight() {
diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.ts
index 83b7f3ae26..c9122c015d 100644
--- a/packages/playwright-client/types/types.d.ts
+++ b/packages/playwright-client/types/types.d.ts
@@ -10196,6 +10196,26 @@ export interface Browser {
*/
height: number;
};
+
+ /**
+ * If specified, enables visual annotations on interacted elements during video recording.
+ */
+ annotate?: {
+ /**
+ * How long each annotation is displayed in milliseconds. Defaults to `500`.
+ */
+ duration?: number;
+
+ /**
+ * Position of the action title overlay. Defaults to `"top-right"`.
+ */
+ position?: "top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right";
+
+ /**
+ * Font size of the action title in pixels. Defaults to `24`.
+ */
+ fontSize?: number;
+ };
};
/**
@@ -15469,6 +15489,26 @@ export interface BrowserType<Unused = {}> {
*/
height: number;
};
+
+ /**
+ * If specified, enables visual annotations on interacted elements during video recording.
+ */
+ annotate?: {
+ /**
+ * How long each annotation is displayed in milliseconds. Defaults to `500`.
+ */
+ duration?: number;
+
+ /**
+ * Position of the action title overlay. Defaults to `"top-right"`.
+ */
+ position?: "top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right";
+
+ /**
+ * Font size of the action title in pixels. Defaults to `24`.
+ */
+ fontSize?: number;
+ };
};
/**
@@ -16162,6 +16202,11 @@ export interface Screencast {
width: number;
height: number;
};
+ annotate?: {
+ duration?: number;
+ position?: 'top-left' | 'top' | 'top-right' | 'bottom-left' | 'bottom' | 'bottom-right';
+ fontSize?: number;
+ };
}): Promise<Disposable>;
/**
* Stops the screencast started with
@@ -17332,6 +17377,26 @@ export interface AndroidDevice {
*/
height: number;
};
+
+ /**
+ * If specified, enables visual annotations on interacted elements during video recording.
+ */
+ annotate?: {
+ /**
+ * How long each annotation is displayed in milliseconds. Defaults to `500`.
+ */
+ duration?: number;
+
+ /**
+ * Position of the action title overlay. Defaults to `"top-right"`.
+ */
+ position?: "top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right";
+
+ /**
+ * Font size of the action title in pixels. Defaults to `24`.
+ */
+ fontSize?: number;
+ };
};
/**
@@ -19912,6 +19977,26 @@ export interface Electron {
*/
height: number;
};
+
+ /**
+ * If specified, enables visual annotations on interacted elements during video recording.
+ */
+ annotate?: {
+ /**
+ * How long each annotation is displayed in milliseconds. Defaults to `500`.
+ */
+ duration?: number;
+
+ /**
+ * Position of the action title overlay. Defaults to `"top-right"`.
+ */
+ position?: "top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right";
+
+ /**
+ * Font size of the action title in pixels. Defaults to `24`.
+ */
+ fontSize?: number;
+ };
};
/**
@@ -20830,49 +20915,42 @@ export interface Mouse {
*/
export interface Overlay {
/**
- * Adds an overlay with the given HTML content. The overlay is displayed on top of the page until removed. Returns a
- * disposable that removes the overlay when disposed.
- * @param html HTML content for the overlay.
- * @param options
- */
- add(html: string, options?: {
- /**
- * Optional timeout to remove the decoration after. Decoration stays until dismissed if not provided.
- */
- timeout?: number;
- }): Promise<Disposable>;
-
- /**
- * Configures overlay behavior.
+ * Shows a chapter overlay with a title and optional description, centered on the page with a blurred backdrop. Useful
+ * for narrating video recordings. The overlay is removed after the specified duration, or 2000ms.
+ * @param title Title text displayed prominently in the overlay.
* @param options
*/
- configure(options?: {
+ chapter(title: string, options?: {
/**
- * Delay in milliseconds between actions when overlay is active.
+ * Optional description text displayed below the title.
*/
- actionDelay?: number;
+ description?: string;
/**
- * CSS style string applied to the action title element displayed during actions.
+ * Duration in milliseconds after which the overlay is automatically removed. Defaults to `2000`.
*/
- actionStyle?: string;
-
- /**
- * CSS style string applied to the locator highlight element displayed during actions.
- */
- locatorStyle?: string;
+ duration?: number;
}): Promise<void>;
/**
- * Hides all overlays without removing them. Overlays can be shown again with
- * [overlay.show()](https://playwright.dev/docs/api/class-overlay#overlay-show).
+ * Sets visibility of all overlays without removing them.
+ * @param visible Whether overlays should be visible.
*/
- hide(): Promise<void>;
+ setVisible(visible: boolean): Promise<void>;
/**
- * Shows previously hidden overlays.
+ * Adds an overlay with the given HTML content. The overlay is displayed on top of the page until removed. Returns a
+ * disposable that removes the overlay when disposed.
+ * @param html HTML content for the overlay.
+ * @param options
*/
- show(): Promise<void>;
+ show(html: string, options?: {
+ /**
+ * Duration in milliseconds after which the overlay is automatically removed. Overlay stays until dismissed if not
+ * provided.
+ */
+ duration?: number;
+ }): Promise<Disposable>;
}
/**
@@ -22061,6 +22139,27 @@ export interface Video {
* @param options
*/
start(options?: {
+ /**
+ * If specified, enables visual annotations on interacted elements during video recording. Interacted elements are
+ * highlighted with a semi-transparent blue box and click points are shown as red circles.
+ */
+ annotate?: {
+ /**
+ * How long each annotation is displayed in milliseconds. Defaults to `500`.
+ */
+ duration?: number;
+
+ /**
+ * Position of the action title overlay. Defaults to `"top-right"`.
+ */
+ position?: "top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right";
+
+ /**
+ * Font size of the action title in pixels. Defaults to `24`.
+ */
+ fontSize?: number;
+ };
+
/**
* Path where the video should be saved when the recording is stopped.
*/
@@ -22966,6 +23065,26 @@ export interface BrowserContextOptions {
*/
height: number;
};
+
+ /**
+ * If specified, enables visual annotations on interacted elements during video recording.
+ */
+ annotate?: {
+ /**
+ * How long each annotation is displayed in milliseconds. Defaults to `500`.
+ */
+ duration?: number;
+
+ /**
+ * Position of the action title overlay. Defaults to `"top-right"`.
+ */
+ position?: "top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right";
+
+ /**
+ * Font size of the action title in pixels. Defaults to `24`.
+ */
+ fontSize?: number;
+ };
};
/**
diff --git a/packages/playwright-core/src/client/overlay.ts b/packages/playwright-core/src/client/overlay.ts
index 9c720c3148..533117bcfb 100644
--- a/packages/playwright-core/src/client/overlay.ts
+++ b/packages/playwright-core/src/client/overlay.ts
@@ -26,20 +26,16 @@ export class Overlay implements api.Overlay {
this._page = page;
}
- async add(html: string, options?: { timeout?: number }): Promise<DisposableStub> {
- const { id } = await this._page._channel.overlayAdd({ html, timeout: options?.timeout });
+ async show(html: string, options?: { duration?: number }): Promise<DisposableStub> {
+ const { id } = await this._page._channel.overlayShow({ html, duration: options?.duration });
return new DisposableStub(() => this._page._channel.overlayRemove({ id }));
}
- async hide(): Promise<void> {
- await this._page._channel.overlayHide();
+ async chapter(title: string, options?: { description?: string, duration?: number }): Promise<void> {
+ await this._page._channel.overlayChapter({ title, ...options });
}
- async show(): Promise<void> {
- await this._page._channel.overlayShow();
- }
-
- async configure(options: { actionDelay?: number; actionStyle?: string; locatorStyle?: string } = {}): Promise<void> {
- await this._page._channel.overlayConfigure(options);
+ async setVisible(visible: boolean): Promise<void> {
+ await this._page._channel.overlaySetVisible({ visible });
}
}
diff --git a/packages/playwright-core/src/client/screencast.ts b/packages/playwright-core/src/client/screencast.ts
index 335b9046ca..2f3e92a86e 100644
--- a/packages/playwright-core/src/client/screencast.ts
+++ b/packages/playwright-core/src/client/screencast.ts
@@ -16,6 +16,7 @@
import { DisposableStub } from './disposable';
+import type { AnnotateOptions } from './types';
import type * as api from '../../types/types';
import type { Page } from './page';
@@ -30,7 +31,7 @@ export class Screencast implements api.Screencast {
});
}
- async start(onFrame: (frame: { data: Buffer }) => Promise<any>|any, options: { preferredSize?: { width: number, height: number } } = {}): Promise<DisposableStub> {
+ async start(onFrame: (frame: { data: Buffer }) => Promise<any>|any, options: { preferredSize?: { width: number, height: number }, annotate?: AnnotateOptions } = {}): Promise<DisposableStub> {
if (this._onFrame)
throw new Error('Screencast is already started');
this._onFrame = onFrame;
diff --git a/packages/playwright-core/src/client/types.ts b/packages/playwright-core/src/client/types.ts
index b5a526ab94..4009ec4f86 100644
--- a/packages/playwright-core/src/client/types.ts
+++ b/packages/playwright-core/src/client/types.ts
@@ -139,6 +139,9 @@ export type SelectorEngine = {
queryAll(root: HTMLElement, selector: string): HTMLElement[];
};
+export type AnnotatePosition = 'top-left' | 'top' | 'top-right' | 'bottom-left' | 'bottom' | 'bottom-right';
+export type AnnotateOptions = { duration?: number, position?: AnnotatePosition, fontSize?: number };
+
export type RemoteAddr = channels.RemoteAddr;
export type SecurityDetails = channels.SecurityDetails;
diff --git a/packages/playwright-core/src/client/video.ts b/packages/playwright-core/src/client/video.ts
index 8b3a026d4b..8a0683d766 100644
--- a/packages/playwright-core/src/client/video.ts
+++ b/packages/playwright-core/src/client/video.ts
@@ -18,6 +18,7 @@ import { Artifact } from './artifact';
import { DisposableStub } from './disposable';
import { EventEmitter } from './eventEmitter';
+import type { AnnotateOptions } from './types';
import type { Connection } from './connection';
import type { Page } from './page';
import type * as api from '../../types/types';
@@ -35,8 +36,8 @@ export class Video extends EventEmitter implements api.Video {
this._artifact = artifact;
}
- async start(options: { path?: string, size?: { width: number, height: number } } = {}) {
- const result = await this._page._channel.videoStart({ size: options.size });
+ async start(options: { path?: string, size?: { width: number, height: number }, annotate?: AnnotateOptions } = {}) {
+ const result = await this._page._channel.videoStart({ size: options.size, annotate: options.annotate });
this._artifact = Artifact.from(result.artifact);
this._savePath = options.path;
return new DisposableStub(() => this.stop());
diff --git a/packages/playwright-core/src/protocol/validator.ts b/packages/playwright-core/src/protocol/validator.ts
index 0e3f875d02..6a7390b8da 100644
--- a/packages/playwright-core/src/protocol/validator.ts
+++ b/packages/playwright-core/src/protocol/validator.ts
@@ -50,6 +50,11 @@ scheme.Rect = tObject({
width: tFloat,
height: tFloat,
});
+scheme.AnnotateOptions = tObject({
+ duration: tOptional(tFloat),
+ position: tOptional(tEnum(['top-left', 'top', 'top-right', 'bottom-left', 'bottom', 'bottom-right'])),
+ fontSize: tOptional(tInt),
+});
scheme.SerializedValue = tObject({
n: tOptional(tFloat),
b: tOptional(tBoolean),
@@ -611,6 +616,7 @@ scheme.BrowserTypeLaunchPersistentContextParams = tObject({
width: tInt,
height: tInt,
})),
+ annotate: tOptional(tType('AnnotateOptions')),
})),
strictSelectors: tOptional(tBoolean),
serviceWorkers: tOptional(tEnum(['allow', 'block'])),
@@ -722,6 +728,7 @@ scheme.BrowserNewContextParams = tObject({
width: tInt,
height: tInt,
})),
+ annotate: tOptional(tType('AnnotateOptions')),
})),
strictSelectors: tOptional(tBoolean),
serviceWorkers: tOptional(tEnum(['allow', 'block'])),
@@ -793,6 +800,7 @@ scheme.BrowserNewContextForReuseParams = tObject({
width: tInt,
height: tInt,
})),
+ annotate: tOptional(tType('AnnotateOptions')),
})),
strictSelectors: tOptional(tBoolean),
serviceWorkers: tOptional(tEnum(['allow', 'block'])),
@@ -911,6 +919,7 @@ scheme.BrowserContextInitializer = tObject({
width: tInt,
height: tInt,
})),
+ annotate: tOptional(tType('AnnotateOptions')),
})),
strictSelectors: tOptional(tBoolean),
serviceWorkers: tOptional(tEnum(['allow', 'block'])),
@@ -1539,32 +1548,33 @@ scheme.PagePickLocatorResult = tObject({
});
scheme.PageCancelPickLocatorParams = tOptional(tObject({}));
scheme.PageCancelPickLocatorResult = tOptional(tObject({}));
-scheme.PageOverlayAddParams = tObject({
+scheme.PageOverlayShowParams = tObject({
html: tString,
- timeout: tOptional(tInt),
+ duration: tOptional(tFloat),
});
-scheme.PageOverlayAddResult = tObject({
+scheme.PageOverlayShowResult = tObject({
id: tString,
});
scheme.PageOverlayRemoveParams = tObject({
id: tString,
});
scheme.PageOverlayRemoveResult = tOptional(tObject({}));
-scheme.PageOverlayHideParams = tOptional(tObject({}));
-scheme.PageOverlayHideResult = tOptional(tObject({}));
-scheme.PageOverlayShowParams = tOptional(tObject({}));
-scheme.PageOverlayShowResult = tOptional(tObject({}));
-scheme.PageOverlayConfigureParams = tObject({
- actionDelay: tOptional(tInt),
- actionStyle: tOptional(tString),
- locatorStyle: tOptional(tString),
-});
-scheme.PageOverlayConfigureResult = tOptional(tObject({}));
+scheme.PageOverlayChapterParams = tObject({
+ title: tString,
+ description: tOptional(tString),
+ duration: tOptional(tFloat),
+});
+scheme.PageOverlayChapterResult = tOptional(tObject({}));
+scheme.PageOverlaySetVisibleParams = tObject({
+ visible: tBoolean,
+});
+scheme.PageOverlaySetVisibleResult = tOptional(tObject({}));
scheme.PageStartScreencastParams = tObject({
preferredSize: tOptional(tObject({
width: tInt,
height: tInt,
})),
+ annotate: tOptional(tType('AnnotateOptions')),
});
scheme.PageStartScreencastResult = tOptional(tObject({}));
scheme.PageStopScreencastParams = tOptional(tObject({}));
@@ -1574,6 +1584,7 @@ scheme.PageVideoStartParams = tObject({
width: tInt,
height: tInt,
})),
+ annotate: tOptional(tType('AnnotateOptions')),
});
scheme.PageVideoStartResult = tObject({
artifact: tChannel(['Artifact']),
@@ -2673,6 +2684,7 @@ scheme.ElectronLaunchParams = tObject({
width: tInt,
height: tInt,
})),
+ annotate: tOptional(tType('AnnotateOptions')),
})),
strictSelectors: tOptional(tBoolean),
timezoneId: tOptional(tString),
@@ -2908,6 +2920,7 @@ scheme.AndroidDeviceLaunchBrowserParams = tObject({
width: tInt,
height: tInt,
})),
+ annotate: tOptional(tType('AnnotateOptions')),
})),
strictSelectors: tOptional(tBoolean),
serviceWorkers: tOptional(tEnum(['allow', 'block'])),
diff --git a/packages/playwright-core/src/server/dispatchers/pageDispatcher.ts b/packages/playwright-core/src/server/dispatchers/pageDispatcher.ts
index 7d292cd18b..44198f302d 100644
--- a/packages/playwright-core/src/server/dispatchers/pageDispatcher.ts
+++ b/packages/playwright-core/src/server/dispatchers/pageDispatcher.ts
@@ -355,8 +355,8 @@ export class PageDispatcher extends Dispatcher<Page, channels.PageChannel, Brows
await recorder?.setMode('none');
}
- async overlayAdd(params: channels.PageOverlayAddParams): Promise<channels.PageOverlayAddResult> {
- const id = await this._page.overlay.add(params.html, params.timeout);
+ async overlayShow(params: channels.PageOverlayShowParams): Promise<channels.PageOverlayShowResult> {
+ const id = await this._page.overlay.show(params.html, params.duration);
return { id };
}
@@ -364,16 +364,12 @@ export class PageDispatcher extends Dispatcher<Page, channels.PageChannel, Brows
await this._page.overlay.remove(params.id);
}
- async overlayHide(params: channels.PageOverlayHideParams): Promise<channels.PageOverlayHideResult> {
- await this._page.overlay.hide();
- }
-
- async overlayShow(params: channels.PageOverlayShowParams): Promise<channels.PageOverlayShowResult> {
- await this._page.overlay.show();
+ async overlayChapter(params: channels.PageOverlayChapterParams): Promise<channels.PageOverlayChapterResult> {
+ await this._page.overlay.chapter(params);
}
- async overlayConfigure(params: channels.PageOverlayConfigureParams): Promise<channels.PageOverlayConfigureResult> {
- await this._page.overlay.configure(params);
+ async overlaySetVisible(params: channels.PageOverlaySetVisibleParams): Promise<channels.PageOverlaySetVisibleResult> {
+ await this._page.overlay.setVisible(params.visible);
}
async startScreencast(params: channels.PageStartScreencastParams, progress?: Progress): Promise<channels.PageStartScreencastResult> {
@@ -383,7 +379,7 @@ export class PageDispatcher extends Dispatcher<Page, channels.PageChannel, Brows
this._screencastListener = (frame: ScreencastFrame) => {
this._dispatchEvent('screencastFrame', { data: frame.buffer });
};
- await this._page.screencast.startScreencast(this._screencastListener, { quality: 90, width: size.width, height: size.height });
+ await this._page.screencast.startScreencast(this._screencastListener, { quality: 90, width: size.width, height: size.height, annotate: params.annotate });
}
async stopScreencast(params: channels.PageStopScreencastParams, progress?: Progress): Promise<channels.PageStopScreencastResult> {
diff --git a/packages/playwright-core/src/server/overlay.ts b/packages/playwright-core/src/server/overlay.ts
index 6b772acfc7..9ee6b23e1d 100644
--- a/packages/playwright-core/src/server/overlay.ts
+++ b/packages/playwright-core/src/server/overlay.ts
@@ -14,37 +14,33 @@
* limitations under the License.
*/
-import { createGuid, debugLogger } from '../utils';
-import { renderTitleForCall } from '../utils';
+import { createGuid, debugLogger, escapeHTML } from '../utils';
import { Page } from './page';
-import type { CallMetadata, InstrumentationListener, SdkObject } from './instrumentation';
-
-export class Overlay implements InstrumentationListener {
+export class Overlay {
private readonly _page: Page;
- private _options: { actionDelay?: number; actionStyle?: string; locatorStyle?: string; } | undefined;
private _overlays = new Map<string, string>();
constructor(page: Page) {
this._page = page;
- this._page.instrumentation.addListener(this, page.browserContext);
- this._page.on(Page.Events.InternalFrameNavigatedToNewDocument, () => {
+ this._page.on(Page.Events.InternalFrameNavigatedToNewDocument, frame => {
+ if (frame.parentFrame())
+ return;
for (const [id, html] of this._overlays)
this._doAdd(id, html).catch(e => debugLogger.log('error', e));
});
}
dispose() {
- this._page.instrumentation.removeListener(this);
}
- async add(html: string, timeout?: number): Promise<string> {
+ async show(html: string, duration?: number): Promise<string> {
const id = createGuid();
this._overlays.set(id, html);
// We must return id even if this call fails.
await this._doAdd(id, html).catch(e => debugLogger.log('error', e));
- if (timeout) {
- await new Promise(f => setTimeout(f, timeout));
+ if (duration) {
+ await new Promise(f => setTimeout(f, duration));
await this.remove(id);
}
return id;
@@ -65,56 +61,78 @@ export class Overlay implements InstrumentationListener {
}, { injected: await utility.injectedScript(), id }).catch(e => debugLogger.log('error', e));
}
- async hide(): Promise<void> {
- const utility = await this._page.mainFrame()._utilityContext();
- await utility.evaluate(({ injected }) => {
- injected.hideUserOverlays();
- }, { injected: await utility.injectedScript() }).catch(e => debugLogger.log('error', e));
- }
-
- async show(): Promise<void> {
+ async chapter(options: { title: string, description?: string, duration?: number }): Promise<void> {
+ const fadeDuration = 300;
+ const descriptionHtml = options.description ? `<div id="description">${escapeHTML(options.description)}</div>` : '';
+ const styleSheet = `
+ @keyframes pw-chapter-fade-in {
+ from { opacity: 0; }
+ to { opacity: 1; }
+ }
+ @keyframes pw-chapter-fade-out {
+ from { opacity: 1; }
+ to { opacity: 0; }
+ }
+ #background {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ backdrop-filter: blur(2px);
+ animation: pw-chapter-fade-in ${fadeDuration}ms ease-out forwards;
+ }
+ #background.fade-out {
+ animation: pw-chapter-fade-out ${fadeDuration}ms ease-in forwards;
+ }
+ #content {
+ background: rgba(0, 0, 0, 0.7);
+ border: 1px solid rgba(255, 255, 255, 0.15);
+ border-radius: 16px;
+ padding: 40px 56px;
+ max-width: 560px;
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
+ }
+ #title {
+ color: white;
+ font-family: system-ui, -apple-system, sans-serif;
+ font-size: 28px;
+ font-weight: 600;
+ line-height: 1.3;
+ text-align: center;
+ letter-spacing: -0.01em;
+ }
+ #description {
+ color: rgba(255, 255, 255, 0.7);
+ font-family: system-ui, -apple-system, sans-serif;
+ font-size: 15px;
+ line-height: 1.5;
+ margin-top: 12px;
+ text-align: center;
+ }
+ `;
+ const duration = options.duration ?? 2000;
+ const html = `<style>${styleSheet}</style><div id="background"><div id="content"><div id="title">${escapeHTML(options.title)}</div>${descriptionHtml}</div></div>`;
+ const id = await this.show(html);
+ await new Promise(f => setTimeout(f, duration));
+ // Trigger fade-out, then remove after animation completes.
const utility = await this._page.mainFrame()._utilityContext();
- await utility.evaluate(({ injected }) => {
- injected.showUserOverlays();
- }, { injected: await utility.injectedScript() }).catch(e => debugLogger.log('error', e));
+ await utility.evaluate(({ injected, id, fadeDuration }) => {
+ const overlay = injected.getUserOverlay(id);
+ const bg = overlay?.querySelector('#background');
+ if (bg)
+ bg.classList.add('fade-out');
+ return new Promise(f => injected.utils.builtins.setTimeout(f, fadeDuration));
+ }, { injected: await utility.injectedScript(), id, fadeDuration }).catch(e => debugLogger.log('error', e));
+ await this.remove(id);
}
- async configure(options: { actionDelay?: number; actionStyle?: string; locatorStyle?: string }): Promise<void> {
- this._options = options;
- }
-
- async onBeforeCall(sdkObject: SdkObject, metadata: CallMetadata, parentId?: string): Promise<void> {
- if (!this._options?.actionDelay)
+ async setVisible(visible: boolean): Promise<void> {
+ if (!this._overlays.size)
return;
- metadata.annotate = true;
- }
-
- async onBeforeInputAction(sdkObject: SdkObject, metadata: CallMetadata): Promise<void> {
- if (!this._options?.actionDelay)
- return;
-
- const page = sdkObject.attribution.page;
- if (!page)
- return;
-
- const actionTitle = renderTitleForCall(metadata);
- const utility = await page.mainFrame()._utilityContext();
-
- // Run this outside of the progress timer.
- await utility.evaluate(async options => {
- const { injected, delay } = options;
- injected.setScreencastAnnotation(options);
- await new Promise(f => injected.utils.builtins.setTimeout(f, delay));
- injected.setScreencastAnnotation(null);
- }, {
- injected: await utility.injectedScript(),
- delay: this._options?.actionDelay,
- point: metadata.point,
- box: metadata.box,
- actionTitle,
- actionStyle: this._options?.actionStyle,
- locatorStyle: this._options?.locatorStyle,
- }).catch(e => debugLogger.log('error', e));
+ const utility = await this._page.mainFrame()._utilityContext();
+ await utility.evaluate(({ injected, visible }) => {
+ injected.setUserOverlaysVisible(visible);
+ }, { injected: await utility.injectedScript(), visible }).catch(e => debugLogger.log('error', e));
}
-
}
diff --git a/packages/playwright-core/src/server/screencast.ts b/packages/playwright-core/src/server/screencast.ts
index 646827e8ac..b816750458 100644
--- a/packages/playwright-core/src/server/screencast.ts
+++ b/packages/playwright-core/src/server/screencast.ts
@@ -15,7 +15,7 @@
*/
import path from 'path';
-import { assert, createGuid } from '../utils';
+import { assert, createGuid, renderTitleForCall } from '../utils';
import { debugLogger } from '../utils';
import { VideoRecorder } from './videoRecorder';
import { Page } from './page';
@@ -23,11 +23,12 @@ import { registry } from './registry';
import { validateVideoSize } from './browserContext';
import type * as types from './types';
+import type { CallMetadata, InstrumentationListener, SdkObject } from './instrumentation';
export type ScreencastListener = (frame: types.ScreencastFrame) => void;
-export type ScreencastOptions = { width: number, height: number, quality: number };
+export type ScreencastOptions = { width: number, height: number, quality: number, annotate?: types.AnnotateOptions };
-export class Screencast {
+export class Screencast implements InstrumentationListener {
private _page: Page;
private _videoRecorder: VideoRecorder | null = null;
private _videoId: string | null = null;
@@ -36,14 +37,17 @@ export class Screencast {
// When throttling for tracing, 200ms between frames, except for 10 frames around the action.
private _frameThrottler: FrameThrottler | undefined;
private _videoFrameListener: ScreencastListener | null = null;
+ private _annotate: types.AnnotateOptions | undefined;
constructor(page: Page) {
this._page = page;
+ this._page.instrumentation.addListener(this, page.browserContext);
}
dispose() {
this._frameThrottler?.dispose();
this._frameThrottler = undefined;
+ this._page.instrumentation.removeListener(this);
}
startForTracing(listener: ScreencastListener) {
@@ -74,7 +78,10 @@ export class Screencast {
if (!recordVideo)
return;
// validateBrowserContextOptions ensures correct video size.
- return this._launchVideoRecorder(recordVideo.dir, recordVideo.size!);
+ const videoOptions = this._launchVideoRecorder(recordVideo.dir, recordVideo.size!);
+ if (recordVideo.annotate)
+ videoOptions.annotate = recordVideo.annotate;
+ return videoOptions;
}
private _launchVideoRecorder(dir: string, size: { width: number, height: number }): types.VideoOptions {
@@ -106,6 +113,7 @@ export class Screencast {
quality: 90,
width: options.width,
height: options.height,
+ annotate: options.annotate,
});
return this._page.browserContext._browser._videoStarted(this._page, videoId, options.outputFile);
}
@@ -145,6 +153,8 @@ export class Screencast {
async startScreencast(listener: ScreencastListener, options: ScreencastOptions) {
this._clients.set(listener, options);
+ if (!this._annotate && options.annotate)
+ this._annotate = options.annotate;
if (this._clients.size === 1)
await this._page.delegate.startScreencast(options);
}
@@ -153,12 +163,47 @@ export class Screencast {
this._clients.delete(listener);
if (!this._clients.size)
await this._page.delegate.stopScreencast();
+ this._annotate = Array.from(this._clients.values()).find(options => options.annotate)?.annotate;
}
onScreencastFrame(frame: types.ScreencastFrame) {
for (const listener of this._clients.keys())
listener(frame);
}
+
+ async onBeforeCall(sdkObject: SdkObject, metadata: CallMetadata, parentId?: string): Promise<void> {
+ if (!this._annotate)
+ return;
+ metadata.annotate = true;
+ }
+
+ async onBeforeInputAction(sdkObject: SdkObject, metadata: CallMetadata): Promise<void> {
+ if (!this._annotate)
+ return;
+
+ const page = sdkObject.attribution.page;
+ if (!page)
+ return;
+
+ const actionTitle = renderTitleForCall(metadata);
+ const utility = await page.mainFrame()._utilityContext();
+
+ // Run this outside of the progress timer.
+ await utility.evaluate(async options => {
+ const { injected, duration } = options;
+ injected.setScreencastAnnotation(options);
+ await new Promise(f => injected.utils.builtins.setTimeout(f, duration));
+ injected.setScreencastAnnotation(null);
+ }, {
+ injected: await utility.injectedScript(),
+ duration: this._annotate?.duration ?? 500,
+ point: metadata.point,
+ box: metadata.box,
+ actionTitle,
+ position: this._annotate?.position,
+ fontSize: this._annotate?.fontSize,
+ }).catch(e => debugLogger.log('error', e));
+ }
}
class FrameThrottler {
diff --git a/packages/playwright-core/src/server/types.ts b/packages/playwright-core/src/server/types.ts
index 1903a95432..86dbcc4229 100644
--- a/packages/playwright-core/src/server/types.ts
+++ b/packages/playwright-core/src/server/types.ts
@@ -43,8 +43,12 @@ export type PointerActionWaitOptions = CommonActionOptions & {
trial?: boolean;
};
+export type AnnotatePosition = 'top-left' | 'top' | 'top-right' | 'bottom-left' | 'bottom' | 'bottom-right';
+
export type AnnotateOptions = {
- action?: { delay?: number },
+ duration?: number,
+ position?: AnnotatePosition,
+ fontSize?: number,
};
export type VideoOptions = {
diff --git a/packages/playwright-core/src/tools/cli-client/skill/references/video-recording.md b/packages/playwright-core/src/tools/cli-client/skill/references/video-recording.md
index 29a0776b66..0116ece790 100644
--- a/packages/playwright-core/src/tools/cli-client/skill/references/video-recording.md
+++ b/packages/playwright-core/src/tools/cli-client/skill/references/video-recording.md
@@ -33,39 +33,59 @@ playwright-cli video-stop --filename=recordings/checkout-test-run-42.webm
### 2. Record entire hero scripts.
-When recording a video for the user or as a proof of work, it is best to create a code snippet and execute it.
+When recording a video for the user or as a proof of work, it is best to create a code snippet and execute it with run-code.
It allows pulling appropriate pauses between the actions and annotating the video. There are new Playwright APIs for that.
-1) Perform scenario using CLI and take note of all locators and actions
-2) Create a file with the intended script for video (below)
-3) Use playwright-cli run-code with it
+1) Perform scenario using CLI and take note of all locators and actions. You'll need those locators to request thier bounding boxes for highlight.
+2) Create a file with the intended script for video (below). Use pressSequentially w/ delay for nice typing, make reasonable pauses.
+3) Use playwright-cli run-code --file your-script.js
+
+**Important**: Overlays are `pointer-events: none` — they do not interfere with page interactions. You can safely keep sticky overlays visible while clicking, filling, or performing any actions on the page.
```js
async page => {
await page.video().start({ path: 'video.webm', size: { width: 1280, height: 800 } });
await page.goto('https://demo.playwright.dev/todomvc');
- // Render big message, can be much prettier, this is just a basic version.
- await page.overlay.add(`
- <div style="position: absolute;
- top: 50%;
- left: 50%;
- transform: translateX(-50%);
- padding: 6px;
- background: #808080A0;
- border-radius: 10px;
- font-size: 24px;
- color: white;">1. Add the first item</div>
- `, { timeout: 2000 });
+ // Show a chapter card — blurs the page and shows a dialog.
+ // Blocks until duration expires, then auto-removes.
+ // Use this for simple use cases, but always feel free to hand-craft your own beautiful
+ // overlay via await page.overlay.show().
+ await page.overlay.chapter('Adding Todo Items', {
+ description: 'We will add several items to the todo list.',
+ duration: 2000,
+ });
// Perform action
- await page.getByRole('textbox', { name: 'What needs to be done?' }).pressSequentially('Walk the dog');
+ await page.getByRole('textbox', { name: 'What needs to be done?' }).pressSequentially('Walk the dog', { delay: 60 });
await page.getByRole('textbox', { name: 'What needs to be done?' }).press('Enter');
+ await page.waitForTimeout(1000);
+
+ // Show next chapter
+ await page.overlay.chapter('Verifying Results', {
+ description: 'Checking the item appeared in the list.',
+ duration: 2000,
+ });
+
+ // Add a sticky annotation that stays while you perform actions.
+ // Overlays are pointer-events: none, so they won't block clicks.
+ const annotation = await page.overlay.show(`
+ <div style="position: absolute; top: 8px; right: 8px;
+ padding: 6px 12px; background: rgba(0,0,0,0.7);
+ border-radius: 8px; font-size: 13px; color: white;">
+ ✓ Item added successfully
+ </div>
+ `);
- // Wait a bit for user to see what happened.
- await page.waitForTimeout(2000);
+ // Perform more actions while the annotation is visible
+ await page.getByRole('textbox', { name: 'What needs to be done?' }).pressSequentially('Buy groceries', { delay: 60 });
+ await page.getByRole('textbox', { name: 'What needs to be done?' }).press('Enter');
+ await page.waitForTimeout(1500);
+
+ // Remove the annotation when done
+ await annotation.dispose();
- // Now annotate what happened right on the screen.
+ // You can also highlight relevant locators and provide contextual annotations.
const bounds = await page.getByText('Walk the dog').boundingBox();
await page.overlay.add(`
<div style="position: absolute;
@@ -80,22 +100,28 @@ async page => {
left: ${bounds.x + bounds.width / 2}px;
transform: translateX(-50%);
padding: 6px;
- background: #808080A0;
+ background: #808080;
border-radius: 10px;
font-size: 14px;
color: white;">Check it out, it is right above this text
</div>
- `, { timeout: 2000 });
-
+ `, { duration: 2000 });
- // Alternatively, you can add sticky overlays and remove them explicitly:
- const o1 = await page.overlay.add('...');
- // Perform actions...
- await o1.dispose();
await page.video().stop();
}
```
+Embrace creativity, overlays are powerful.
+
+### Overlay API Summary
+
+| Method | Use Case |
+|--------|----------|
+| `page.overlay.chapter(title, { description?, duration?, styleSheet? })` | Full-screen chapter card with blurred backdrop — ideal for section transitions |
+| `page.overlay.show(html, { duration? })` | Custom HTML overlay — use for callouts, labels, highlights |
+| `disposable.dispose()` | Remove a sticky overlay added without duration |
+| `page.overlay.setVisible(false/true)` | Temporarily hide/show all overlays |
+
## Tracing vs Video
| Feature | Video | Tracing |
diff --git a/packages/playwright-core/src/utils/isomorphic/protocolMetainfo.ts b/packages/playwright-core/src/utils/isomorphic/protocolMetainfo.ts
index 18943d5657..70e91bff28 100644
--- a/packages/playwright-core/src/utils/isomorphic/protocolMetainfo.ts
+++ b/packages/playwright-core/src/utils/isomorphic/protocolMetainfo.ts
@@ -148,11 +148,10 @@ export const methodMetainfo = new Map<string, MethodMetainfo>([
['Page.bringToFront', { title: 'Bring to front', }],
['Page.pickLocator', { title: 'Pick locator', group: 'configuration', }],
['Page.cancelPickLocator', { title: 'Cancel pick locator', group: 'configuration', }],
- ['Page.overlayAdd', { title: 'Add overlay', group: 'configuration', }],
- ['Page.overlayRemove', { title: 'Remove overlay', group: 'configuration', }],
- ['Page.overlayHide', { title: 'Hide overlay', group: 'configuration', }],
['Page.overlayShow', { title: 'Show overlay', group: 'configuration', }],
- ['Page.overlayConfigure', { title: 'Configure overlay', group: 'configuration', }],
+ ['Page.overlayRemove', { title: 'Remove overlay', group: 'configuration', }],
+ ['Page.overlayChapter', { title: 'Show chapter overlay', group: 'configuration', }],
+ ['Page.overlaySetVisible', { title: 'Set overlay visibility', group: 'configuration', }],
['Page.startScreencast', { title: 'Start screencast', group: 'configuration', }],
['Page.stopScreencast', { title: 'Stop screencast', group: 'configuration', }],
['Page.videoStart', { title: 'Start video recording', group: 'configuration', }],
diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.ts
index 83b7f3ae26..c9122c015d 100644
--- a/packages/playwright-core/types/types.d.ts
+++ b/packages/playwright-core/types/types.d.ts
@@ -10196,6 +10196,26 @@ export interface Browser {
*/
height: number;
};
+
+ /**
+ * If specified, enables visual annotations on interacted elements during video recording.
+ */
+ annotate?: {
+ /**
+ * How long each annotation is displayed in milliseconds. Defaults to `500`.
+ */
+ duration?: number;
+
+ /**
+ * Position of the action title overlay. Defaults to `"top-right"`.
+ */
+ position?: "top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right";
+
+ /**
+ * Font size of the action title in pixels. Defaults to `24`.
+ */
+ fontSize?: number;
+ };
};
/**
@@ -15469,6 +15489,26 @@ export interface BrowserType<Unused = {}> {
*/
height: number;
};
+
+ /**
+ * If specified, enables visual annotations on interacted elements during video recording.
+ */
+ annotate?: {
+ /**
+ * How long each annotation is displayed in milliseconds. Defaults to `500`.
+ */
+ duration?: number;
+
+ /**
+ * Position of the action title overlay. Defaults to `"top-right"`.
+ */
+ position?: "top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right";
+
+ /**
+ * Font size of the action title in pixels. Defaults to `24`.
+ */
+ fontSize?: number;
+ };
};
/**
@@ -16162,6 +16202,11 @@ export interface Screencast {
width: number;
height: number;
};
+ annotate?: {
+ duration?: number;
+ position?: 'top-left' | 'top' | 'top-right' | 'bottom-left' | 'bottom' | 'bottom-right';
+ fontSize?: number;
+ };
}): Promise<Disposable>;
/**
* Stops the screencast started with
@@ -17332,6 +17377,26 @@ export interface AndroidDevice {
*/
height: number;
};
+
+ /**
+ * If specified, enables visual annotations on interacted elements during video recording.
+ */
+ annotate?: {
+ /**
+ * How long each annotation is displayed in milliseconds. Defaults to `500`.
+ */
+ duration?: number;
+
+ /**
+ * Position of the action title overlay. Defaults to `"top-right"`.
+ */
+ position?: "top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right";
+
+ /**
+ * Font size of the action title in pixels. Defaults to `24`.
+ */
+ fontSize?: number;
+ };
};
/**
@@ -19912,6 +19977,26 @@ export interface Electron {
*/
height: number;
};
+
+ /**
+ * If specified, enables visual annotations on interacted elements during video recording.
+ */
+ annotate?: {
+ /**
+ * How long each annotation is displayed in milliseconds. Defaults to `500`.
+ */
+ duration?: number;
+
+ /**
+ * Position of the action title overlay. Defaults to `"top-right"`.
+ */
+ position?: "top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right";
+
+ /**
+ * Font size of the action title in pixels. Defaults to `24`.
+ */
+ fontSize?: number;
+ };
};
/**
@@ -20830,49 +20915,42 @@ export interface Mouse {
*/
export interface Overlay {
/**
- * Adds an overlay with the given HTML content. The overlay is displayed on top of the page until removed. Returns a
- * disposable that removes the overlay when disposed.
- * @param html HTML content for the overlay.
- * @param options
- */
- add(html: string, options?: {
- /**
- * Optional timeout to remove the decoration after. Decoration stays until dismissed if not provided.
- */
- timeout?: number;
- }): Promise<Disposable>;
-
- /**
- * Configures overlay behavior.
+ * Shows a chapter overlay with a title and optional description, centered on the page with a blurred backdrop. Useful
+ * for narrating video recordings. The overlay is removed after the specified duration, or 2000ms.
+ * @param title Title text displayed prominently in the overlay.
* @param options
*/
- configure(options?: {
+ chapter(title: string, options?: {
/**
- * Delay in milliseconds between actions when overlay is active.
+ * Optional description text displayed below the title.
*/
- actionDelay?: number;
+ description?: string;
/**
- * CSS style string applied to the action title element displayed during actions.
+ * Duration in milliseconds after which the overlay is automatically removed. Defaults to `2000`.
*/
- actionStyle?: string;
-
- /**
- * CSS style string applied to the locator highlight element displayed during actions.
- */
- locatorStyle?: string;
+ duration?: number;
}): Promise<void>;
/**
- * Hides all overlays without removing them. Overlays can be shown again with
- * [overlay.show()](https://playwright.dev/docs/api/class-overlay#overlay-show).
+ * Sets visibility of all overlays without removing them.
+ * @param visible Whether overlays should be visible.
*/
- hide(): Promise<void>;
+ setVisible(visible: boolean): Promise<void>;
/**
- * Shows previously hidden overlays.
+ * Adds an overlay with the given HTML content. The overlay is displayed on top of the page until removed. Returns a
+ * disposable that removes the overlay when disposed.
+ * @param html HTML content for the overlay.
+ * @param options
*/
- show(): Promise<void>;
+ show(html: string, options?: {
+ /**
+ * Duration in milliseconds after which the overlay is automatically removed. Overlay stays until dismissed if not
+ * provided.
+ */
+ duration?: number;
+ }): Promise<Disposable>;
}
/**
@@ -22061,6 +22139,27 @@ export interface Video {
* @param options
*/
start(options?: {
+ /**
+ * If specified, enables visual annotations on interacted elements during video recording. Interacted elements are
+ * highlighted with a semi-transparent blue box and click points are shown as red circles.
+ */
+ annotate?: {
+ /**
+ * How long each annotation is displayed in milliseconds. Defaults to `500`.
+ */
+ duration?: number;
+
+ /**
+ * Position of the action title overlay. Defaults to `"top-right"`.
+ */
+ position?: "top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right";
+
+ /**
+ * Font size of the action title in pixels. Defaults to `24`.
+ */
+ fontSize?: number;
+ };
+
/**
* Path where the video should be saved when the recording is stopped.
*/
@@ -22966,6 +23065,26 @@ export interface BrowserContextOptions {
*/
height: number;
};
+
+ /**
+ * If specified, enables visual annotations on interacted elements during video recording.
+ */
+ annotate?: {
+ /**
+ * How long each annotation is displayed in milliseconds. Defaults to `500`.
+ */
+ duration?: number;
+
+ /**
+ * Position of the action title overlay. Defaults to `"top-right"`.
+ */
+ position?: "top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right";
+
+ /**
+ * Font size of the action title in pixels. Defaults to `24`.
+ */
+ fontSize?: number;
+ };
};
/**
diff --git a/packages/playwright/src/index.ts b/packages/playwright/src/index.ts
index 47ef15d93a..90ae8c00e5 100644
--- a/packages/playwright/src/index.ts
+++ b/packages/playwright/src/index.ts
@@ -18,7 +18,7 @@ import fs from 'fs';
import path from 'path';
import * as playwrightLibrary from 'playwright-core';
-import { setBoxedStackPrefixes, createGuid, currentZone, debugMode, jsonStringifyForceASCII, asLocatorDescription, renderTitleForCall, getActionGroup } from 'playwright-core/lib/utils';
+import { setBoxedStackPrefixes, createGuid, currentZone, debugMode, jsonStringifyForceASCII, asLocatorDescription, renderTitleForCall, getActionGroup, escapeHTML } from 'playwright-core/lib/utils';
import { buildErrorContext } from './errorContext';
import { currentTestInfo } from './common/globals';
import { rootTestType } from './common/testType';
@@ -372,10 +372,12 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
`If you would like to configure your page before each test, do that in beforeEach hook instead.`,
].join('\n'));
}
+ const annotate = typeof video === 'string' ? undefined : video.annotate;
const videoOptions: BrowserContextOptions = captureVideo ? {
recordVideo: {
dir: tracing().artifactsDir(),
size: typeof video === 'string' ? undefined : video.size,
+ annotate: annotate?.action,
}
} : {};
const context = await browser.newContext({ ...videoOptions, ...options }) as BrowserContextImpl;
@@ -446,7 +448,7 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
const { context, close } = await _contextFactory();
testInfo._onCustomMessageCallback = createCustomMessageHandler(testInfo, context);
await runDaemonForContext(testInfo, context);
- await installScreencastTitleUpdater(testInfo, context, annotate);
+ await installScreencastTitleUpdater(testInfo, context, annotate?.test);
await use(context);
await close();
return;
@@ -455,7 +457,7 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
const context = await browserImpl._wrapApiCall(() => browserImpl._newContextForReuse(), { internal: true });
testInfo._onCustomMessageCallback = createCustomMessageHandler(testInfo, context);
await runDaemonForContext(testInfo, context);
- await installScreencastTitleUpdater(testInfo, context, annotate);
+ await installScreencastTitleUpdater(testInfo, context, annotate?.test);
await use(context);
const closeReason = testInfo.status === 'timedOut' ? 'Test timeout of ' + testInfo.timeout + 'ms exceeded.' : 'Test ended.';
await browserImpl._wrapApiCall(() => browserImpl._disconnectFromReusedContext(closeReason), { internal: true });
@@ -469,10 +471,8 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
// First time we are reusing the context, we should create the page.
let [page] = context.pages();
- if (!page) {
+ if (!page)
page = await context.newPage();
- await page.overlay.add(test.info().titlePath.join(' › '));
- }
await use(page);
},
@@ -801,37 +801,24 @@ class ArtifactsRecorder {
}
}
-async function installScreencastTitleUpdater(testInfo: TestInfoImpl, context: BrowserContext, annotate?: { action?: { delay?: number, actionStyle?: string, locatorStyle?: string }, test?: { level?: 'file' | 'title' | 'step' } }) {
- if (!annotate?.action && !annotate?.test)
+async function installScreencastTitleUpdater(testInfo: TestInfoImpl, context: BrowserContext, testAnnotate?: { level?: 'file' | 'title' | 'step', position?: string, fontSize?: number }) {
+ if (!testAnnotate)
return;
- if (annotate.action) {
- const configureOptions = {
- actionDelay: annotate.action.delay,
- actionStyle: annotate.action.actionStyle,
- locatorStyle: annotate.action.locatorStyle
- };
- for (const page of context.pages())
- await page.overlay.configure(configureOptions);
- context.on('page', page => {
- page.overlay.configure(configureOptions).catch(() => {});
- });
- }
-
- if (!annotate?.test)
- return;
-
- const testTitle = annotate.test.level === 'file' ? [testInfo.titlePath[0]] : testInfo.titlePath;
+ const testTitle = testAnnotate.level === 'file' ? [testInfo.titlePath[0]] : testInfo.titlePath;
const stepStack: string[] = [];
const overlays = new Map<Page, { dispose(): Promise<void> }>();
+ const position = testAnnotate.position ?? 'top-left';
+ const fontSize = testAnnotate.fontSize ?? 14;
+ const level = testAnnotate.level ?? 'step';
const updateOverlay = async () => {
- const parts = annotate.test!.level === 'step' ? [...testTitle, ...stepStack] : testTitle;
- const html = createTestOverlay(parts);
+ const parts = level === 'step' ? [...testTitle, ...stepStack] : testTitle;
+ const html = createTestOverlay(parts, position, fontSize);
for (const page of context.pages()) {
await overlays.get(page)?.dispose();
overlays.delete(page);
- const disposable = await page.overlay.add(html);
+ const disposable = await page.overlay.show(html);
overlays.set(page, disposable);
}
};
@@ -850,9 +837,18 @@ async function installScreencastTitleUpdater(testInfo: TestInfoImpl, context: Br
await updateOverlay();
}
-function createTestOverlay(parts: string[]) {
- return `<div style="white-space: nowrap; font-size: 13px; padding: 3px 6px; background: rgba(0,0,0,0.5); color: white; border-radius: 4px; position: absolute; top: 3px; left: 3px;">
- ${parts.map(p => `<div>${p}</div>`).join('')}
+function createTestOverlay(parts: string[], position: string, fontSize: number) {
+ const positionStyles: Record<string, string> = {
+ 'top-left': 'top: 3px; left: 3px;',
+ 'top': 'top: 3px; left: 50%; transform: translateX(-50%);',
+ 'top-right': 'top: 3px; right: 3px;',
+ 'bottom-left': 'bottom: 3px; left: 3px;',
+ 'bottom': 'bottom: 3px; left: 50%; transform: translateX(-50%);',
+ 'bottom-right': 'bottom: 3px; right: 3px;',
+ };
+ const posStyle = positionStyles[position] ?? positionStyles['top-left'];
+ return `<div style="white-space: nowrap; font-size: ${fontSize}px; padding: 3px 6px; background: rgba(0,0,0,0.5); color: white; border-radius: 4px; position: absolute; ${posStyle}">
+ ${parts.map(p => `<div>${escapeHTML(p)}</div>`).join('')}
</div>`;
}
diff --git a/packages/playwright/src/matchers/toMatchSnapshot.ts b/packages/playwright/src/matchers/toMatchSnapshot.ts
index f2858657f1..f4aa5cc164 100644
--- a/packages/playwright/src/matchers/toMatchSnapshot.ts
+++ b/packages/playwright/src/matchers/toMatchSnapshot.ts
@@ -364,67 +364,75 @@ export async function toHaveScreenshot(
if (this.isNot) {
if (!hasSnapshot)
return helper.handleMissingNegated();
-
- // Having `errorMessage` means we timed out while waiting
- // for screenshots not to match, so screenshots
- // are actually the same in the end.
- expectScreenshotOptions.expected = await fs.promises.readFile(helper.expectedPath);
- const isDifferent = !(await page._expectScreenshot(expectScreenshotOptions)).errorMessage;
- return isDifferent ? helper.handleDifferentNegated() : helper.handleMatchingNegated();
}
// Fast path: there's no screenshot and we don't intend to update it.
- if (helper.updateSnapshots === 'none' && !hasSnapshot)
+ if (!this.isNot && helper.updateSnapshots === 'none' && !hasSnapshot)
return helper.createMatcherResult(`A snapshot doesn't exist at ${helper.expectedPath}.`, false);
- if (!hasSnapshot) {
- // Regenerate a new screenshot by waiting until two screenshots are the same.
- const { actual, previous, diff, errorMessage, log, timedOut } = await page._expectScreenshot(expectScreenshotOptions);
- // We tried re-generating new snapshot but failed.
- // This can be due to e.g. spinning animation, so we want to show it as a diff.
- if (errorMessage) {
- const header = formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toHaveScreenshot', locator: locator?.toString(), expectation: 'expected', timeout, timedOut });
- return helper.handleDifferent(actual, undefined, previous, diff, header, errorMessage, log, this._stepInfo);
+ // Hide overlays during screenshot capture so they don't affect visual comparison.
+ await page.overlay.setVisible(false);
+ try {
+ if (this.isNot) {
+ // Having `errorMessage` means we timed out while waiting
+ // for screenshots not to match, so screenshots
+ // are actually the same in the end.
+ expectScreenshotOptions.expected = await fs.promises.readFile(helper.expectedPath);
+ const isDifferent = !(await page._expectScreenshot(expectScreenshotOptions)).errorMessage;
+ return isDifferent ? helper.handleDifferentNegated() : helper.handleMatchingNegated();
}
- // We successfully generated new screenshot.
- return helper.handleMissing(actual!, this._stepInfo);
- }
-
- // General case:
- // - snapshot exists
- // - regular matcher (i.e. not a `.not`)
- const expected = await fs.promises.readFile(helper.expectedPath);
- expectScreenshotOptions.expected = helper.updateSnapshots === 'all' ? undefined : expected;
+ if (!hasSnapshot) {
+ // Regenerate a new screenshot by waiting until two screenshots are the same.
+ const { actual, previous, diff, errorMessage, log, timedOut } = await page._expectScreenshot(expectScreenshotOptions);
+ // We tried re-generating new snapshot but failed.
+ // This can be due to e.g. spinning animation, so we want to show it as a diff.
+ if (errorMessage) {
+ const header = formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toHaveScreenshot', locator: locator?.toString(), expectation: 'expected', timeout, timedOut });
+ return helper.handleDifferent(actual, undefined, previous, diff, header, errorMessage, log, this._stepInfo);
+ }
+
+ // We successfully generated new screenshot.
+ return helper.handleMissing(actual!, this._stepInfo);
+ }
- const { actual, previous, diff, errorMessage, log, timedOut } = await page._expectScreenshot(expectScreenshotOptions);
- const writeFiles = (actualBuffer: Buffer) => {
- writeFileSync(helper.expectedPath, actualBuffer);
- writeFileSync(helper.actualPath, actualBuffer);
- /* eslint-disable no-console */
- console.log(helper.expectedPath + ' is re-generated, writing actual.');
- return helper.createMatcherResult(helper.expectedPath + ' running with --update-snapshots, writing actual.', true);
- };
+ // General case:
+ // - snapshot exists
+ // - regular matcher (i.e. not a `.not`)
+ const expected = await fs.promises.readFile(helper.expectedPath);
+ expectScreenshotOptions.expected = helper.updateSnapshots === 'all' ? undefined : expected;
- if (!errorMessage) {
- // Screenshot is matching, but is not necessarily the same as the expected.
- if (helper.updateSnapshots === 'all' && actual && compareBuffersOrStrings(actual, expected)) {
+ const { actual, previous, diff, errorMessage, log, timedOut } = await page._expectScreenshot(expectScreenshotOptions);
+ const writeFiles = (actualBuffer: Buffer) => {
+ writeFileSync(helper.expectedPath, actualBuffer);
+ writeFileSync(helper.actualPath, actualBuffer);
+ /* eslint-disable no-console */
console.log(helper.expectedPath + ' is re-generated, writing actual.');
- return writeFiles(actual);
+ return helper.createMatcherResult(helper.expectedPath + ' running with --update-snapshots, writing actual.', true);
+ };
+
+ if (!errorMessage) {
+ // Screenshot is matching, but is not necessarily the same as the expected.
+ if (helper.updateSnapshots === 'all' && actual && compareBuffersOrStrings(actual, expected)) {
+ console.log(helper.expectedPath + ' is re-generated, writing actual.');
+ return writeFiles(actual);
+ }
+ return helper.handleMatching();
+ }
+
+ if (helper.updateSnapshots === 'changed' || helper.updateSnapshots === 'all') {
+ if (actual)
+ return writeFiles(actual);
+ let header = formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toHaveScreenshot', locator: locator?.toString(), expectation: 'expected', timeout, timedOut });
+ header += ' Failed to re-generate expected.\n';
+ return helper.handleDifferent(actual, expectScreenshotOptions.expected, previous, diff, header, errorMessage, log, this._stepInfo);
}
- return helper.handleMatching();
- }
- if (helper.updateSnapshots === 'changed' || helper.updateSnapshots === 'all') {
- if (actual)
- return writeFiles(actual);
- let header = formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toHaveScreenshot', locator: locator?.toString(), expectation: 'expected', timeout, timedOut });
- header += ' Failed to re-generate expected.\n';
+ const header = formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toHaveScreenshot', locator: locator?.toString(), expectation: 'expected', timeout, timedOut });
return helper.handleDifferent(actual, expectScreenshotOptions.expected, previous, diff, header, errorMessage, log, this._stepInfo);
+ } finally {
+ await page.overlay.setVisible(true);
}
-
- const header = formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toHaveScreenshot', locator: locator?.toString(), expectation: 'expected', timeout, timedOut });
- return helper.handleDifferent(actual, expectScreenshotOptions.expected, previous, diff, header, errorMessage, log, this._stepInfo);
}
function writeFileSync(aPath: string, content: Buffer | string) {
diff --git a/packages/playwright/types/test.d.ts b/packages/playwright/types/test.d.ts
index 2172696333..395b684f2e 100644
--- a/packages/playwright/types/test.d.ts
+++ b/packages/playwright/types/test.d.ts
@@ -6953,7 +6953,7 @@ export interface PlaywrightWorkerOptions {
*
* Learn more about [recording video](https://playwright.dev/docs/test-use-options#recording-options).
*/
- video: VideoMode | /** deprecated */ 'retry-with-video' | { mode: VideoMode, size?: ViewportSize, annotate?: { action?: { delay?: number, actionStyle?: string, locatorStyle?: string }, test?: { level?: 'file' | 'title' | 'step' } } };
+ video: VideoMode | /** deprecated */ 'retry-with-video' | { mode: VideoMode, size?: ViewportSize, annotate?: { action?: { duration?: number, position?: 'top-left' | 'top' | 'top-right' | 'bottom-left' | 'bottom' | 'bottom-right', fontSize?: number }, test?: { level?: 'file' | 'title' | 'step', position?: 'top-left' | 'top' | 'top-right' | 'bottom-left' | 'bottom' | 'bottom-right', fontSize?: number } } };
}
export type ScreenshotMode = 'off' | 'on' | 'only-on-failure' | 'on-first-failure';
diff --git a/packages/protocol/src/channels.d.ts b/packages/protocol/src/channels.d.ts
index 35a5c35dac..3fda9fd22b 100644
--- a/packages/protocol/src/channels.d.ts
+++ b/packages/protocol/src/channels.d.ts
@@ -176,6 +176,12 @@ export type Rect = {
height: number,
};
+export type AnnotateOptions = {
+ duration?: number,
+ position?: 'top-left' | 'top' | 'top-right' | 'bottom-left' | 'bottom' | 'bottom-right',
+ fontSize?: number,
+};
+
export type SerializedValue = {
n?: number,
b?: boolean,
@@ -1027,6 +1033,7 @@ export type BrowserTypeLaunchPersistentContextParams = {
width: number,
height: number,
},
+ annotate?: AnnotateOptions,
},
strictSelectors?: boolean,
serviceWorkers?: 'allow' | 'block',
@@ -1110,6 +1117,7 @@ export type BrowserTypeLaunchPersistentContextOptions = {
width: number,
height: number,
},
+ annotate?: AnnotateOptions,
},
strictSelectors?: boolean,
serviceWorkers?: 'allow' | 'block',
@@ -1261,6 +1269,7 @@ export type BrowserNewContextParams = {
width: number,
height: number,
},
+ annotate?: AnnotateOptions,
},
strictSelectors?: boolean,
serviceWorkers?: 'allow' | 'block',
@@ -1329,6 +1338,7 @@ export type BrowserNewContextOptions = {
width: number,
height: number,
},
+ annotate?: AnnotateOptions,
},
strictSelectors?: boolean,
serviceWorkers?: 'allow' | 'block',
@@ -1400,6 +1410,7 @@ export type BrowserNewContextForReuseParams = {
width: number,
height: number,
},
+ annotate?: AnnotateOptions,
},
strictSelectors?: boolean,
serviceWorkers?: 'allow' | 'block',
@@ -1468,6 +1479,7 @@ export type BrowserNewContextForReuseOptions = {
width: number,
height: number,
},
+ annotate?: AnnotateOptions,
},
strictSelectors?: boolean,
serviceWorkers?: 'allow' | 'block',
@@ -1603,6 +1615,7 @@ export type BrowserContextInitializer = {
width: number,
height: number,
},
+ annotate?: AnnotateOptions,
},
strictSelectors?: boolean,
serviceWorkers?: 'allow' | 'block',
@@ -2147,11 +2160,10 @@ export interface PageChannel extends PageEventTarget, EventTargetChannel {
bringToFront(params?: PageBringToFrontParams, progress?: Progress): Promise<PageBringToFrontResult>;
pickLocator(params?: PagePickLocatorParams, progress?: Progress): Promise<PagePickLocatorResult>;
cancelPickLocator(params?: PageCancelPickLocatorParams, progress?: Progress): Promise<PageCancelPickLocatorResult>;
- overlayAdd(params: PageOverlayAddParams, progress?: Progress): Promise<PageOverlayAddResult>;
+ overlayShow(params: PageOverlayShowParams, progress?: Progress): Promise<PageOverlayShowResult>;
overlayRemove(params: PageOverlayRemoveParams, progress?: Progress): Promise<PageOverlayRemoveResult>;
- overlayHide(params?: PageOverlayHideParams, progress?: Progress): Promise<PageOverlayHideResult>;
- overlayShow(params?: PageOverlayShowParams, progress?: Progress): Promise<PageOverlayShowResult>;
- overlayConfigure(params: PageOverlayConfigureParams, progress?: Progress): Promise<PageOverlayConfigureResult>;
+ overlayChapter(params: PageOverlayChapterParams, progress?: Progress): Promise<PageOverlayChapterResult>;
+ overlaySetVisible(params: PageOverlaySetVisibleParams, progress?: Progress): Promise<PageOverlaySetVisibleResult>;
startScreencast(params: PageStartScreencastParams, progress?: Progress): Promise<PageStartScreencastResult>;
stopScreencast(params?: PageStopScreencastParams, progress?: Progress): Promise<PageStopScreencastResult>;
videoStart(params: PageVideoStartParams, progress?: Progress): Promise<PageVideoStartResult>;
@@ -2671,14 +2683,14 @@ export type PagePickLocatorResult = {
export type PageCancelPickLocatorParams = {};
export type PageCancelPickLocatorOptions = {};
export type PageCancelPickLocatorResult = void;
-export type PageOverlayAddParams = {
+export type PageOverlayShowParams = {
html: string,
- timeout?: number,
+ duration?: number,
};
-export type PageOverlayAddOptions = {
- timeout?: number,
+export type PageOverlayShowOptions = {
+ duration?: number,
};
-export type PageOverlayAddResult = {
+export type PageOverlayShowResult = {
id: string,
};
export type PageOverlayRemoveParams = {
@@ -2688,34 +2700,36 @@ export type PageOverlayRemoveOptions = {
};
export type PageOverlayRemoveResult = void;
-export type PageOverlayHideParams = {};
-export type PageOverlayHideOptions = {};
-export type PageOverlayHideResult = void;
-export type PageOverlayShowParams = {};
-export type PageOverlayShowOptions = {};
-export type PageOverlayShowResult = void;
-export type PageOverlayConfigureParams = {
- actionDelay?: number,
- actionStyle?: string,
- locatorStyle?: string,
-};
-export type PageOverlayConfigureOptions = {
- actionDelay?: number,
- actionStyle?: string,
- locatorStyle?: string,
-};
-export type PageOverlayConfigureResult = void;
+export type PageOverlayChapterParams = {
+ title: string,
+ description?: string,
+ duration?: number,
+};
+export type PageOverlayChapterOptions = {
+ description?: string,
+ duration?: number,
+};
+export type PageOverlayChapterResult = void;
+export type PageOverlaySetVisibleParams = {
+ visible: boolean,
+};
+export type PageOverlaySetVisibleOptions = {
+
+};
+export type PageOverlaySetVisibleResult = void;
export type PageStartScreencastParams = {
preferredSize?: {
width: number,
height: number,
},
+ annotate?: AnnotateOptions,
};
export type PageStartScreencastOptions = {
preferredSize?: {
width: number,
height: number,
},
+ annotate?: AnnotateOptions,
};
export type PageStartScreencastResult = void;
export type PageStopScreencastParams = {};
@@ -2726,12 +2740,14 @@ export type PageVideoStartParams = {
width: number,
height: number,
},
+ annotate?: AnnotateOptions,
};
export type PageVideoStartOptions = {
size?: {
width: number,
height: number,
},
+ annotate?: AnnotateOptions,
};
export type PageVideoStartResult = {
artifact: ArtifactChannel,
@@ -4666,6 +4682,7 @@ export type ElectronLaunchParams = {
width: number,
height: number,
},
+ annotate?: AnnotateOptions,
},
strictSelectors?: boolean,
timezoneId?: string,
@@ -4702,6 +4719,7 @@ export type ElectronLaunchOptions = {
width: number,
height: number,
},
+ annotate?: AnnotateOptions,
},
strictSelectors?: boolean,
timezoneId?: string,
@@ -5089,6 +5107,7 @@ export type AndroidDeviceLaunchBrowserParams = {
width: number,
height: number,
},
+ annotate?: AnnotateOptions,
},
strictSelectors?: boolean,
serviceWorkers?: 'allow' | 'block',
@@ -5155,6 +5174,7 @@ export type AndroidDeviceLaunchBrowserOptions = {
width: number,
height: number,
},
+ annotate?: AnnotateOptions,
},
strictSelectors?: boolean,
serviceWorkers?: 'allow' | 'block',
diff --git a/packages/protocol/src/protocol.yml b/packages/protocol/src/protocol.yml
index 2e9b84fccf..6e7dd7c329 100644
--- a/packages/protocol/src/protocol.yml
+++ b/packages/protocol/src/protocol.yml
@@ -59,6 +59,21 @@ Rect:
width: float
height: float
+AnnotateOptions:
+ type: object
+ properties:
+ duration: float?
+ position:
+ type: enum?
+ literals:
+ - top-left
+ - top
+ - top-right
+ - bottom-left
+ - bottom
+ - bottom-right
+ fontSize: int?
+
SerializedValue:
type: object
@@ -598,6 +613,7 @@ ContextOptions:
properties:
width: int
height: int
+ annotate: AnnotateOptions?
strictSelectors: boolean?
serviceWorkers:
type: enum?
@@ -2092,12 +2108,12 @@ Page:
title: Cancel pick locator
group: configuration
- overlayAdd:
- title: Add overlay
+ overlayShow:
+ title: Show overlay
group: configuration
parameters:
html: string
- timeout: int?
+ duration: float?
returns:
id: string
@@ -2107,21 +2123,19 @@ Page:
parameters:
id: string
- overlayHide:
- title: Hide overlay
- group: configuration
-
- overlayShow:
- title: Show overlay
+ overlayChapter:
+ title: Show chapter overlay
group: configuration
+ parameters:
+ title: string
+ description: string?
+ duration: float?
- overlayConfigure:
- title: Configure overlay
+ overlaySetVisible:
+ title: Set overlay visibility
group: configuration
parameters:
- actionDelay: int?
- actionStyle: string?
- locatorStyle: string?
+ visible: boolean
startScreencast:
title: Start screencast
@@ -2132,6 +2146,7 @@ Page:
properties:
width: int
height: int
+ annotate: AnnotateOptions?
stopScreencast:
title: Stop screencast
@@ -2146,6 +2161,7 @@ Page:
properties:
width: int
height: int
+ annotate: AnnotateOptions?
returns:
artifact: Artifact
@@ -4166,6 +4182,7 @@ Electron:
properties:
width: int
height: int
+ annotate: AnnotateOptions?
strictSelectors: boolean?
timezoneId: string?
tracesDir: string?
diff --git a/tests/library/overlay.spec.ts b/tests/library/overlay.spec.ts
index 8864bed4bf..6ed17b8433 100644
--- a/tests/library/overlay.spec.ts
+++ b/tests/library/overlay.spec.ts
@@ -23,7 +23,7 @@ test('should add and remove overlay', async ({ browser, server }) => {
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
- const disposable = await page.overlay.add('<div id="my-overlay">Hello Overlay</div>');
+ const disposable = await page.overlay.show('<div id="my-overlay">Hello Overlay</div>');
await expect(page.locator('x-pw-user-overlays')).toBeVisible();
await expect(page.locator('.x-pw-user-overlay')).toHaveCount(1);
await expect(page.locator('#my-overlay')).toHaveText('Hello Overlay');
@@ -39,8 +39,8 @@ test('should add multiple overlays', async ({ browser, server }) => {
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
- const d1 = await page.overlay.add('<div id="overlay-1">First</div>');
- const d2 = await page.overlay.add('<div id="overlay-2">Second</div>');
+ const d1 = await page.overlay.show('<div id="overlay-1">First</div>');
+ const d2 = await page.overlay.show('<div id="overlay-2">Second</div>');
await expect(page.locator('.x-pw-user-overlay')).toHaveCount(2);
await expect(page.locator('#overlay-1')).toHaveText('First');
await expect(page.locator('#overlay-2')).toHaveText('Second');
@@ -60,13 +60,13 @@ test('should hide and show overlays', async ({ browser, server }) => {
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
- await page.overlay.add('<div id="my-overlay">Visible</div>');
+ await page.overlay.show('<div id="my-overlay">Visible</div>');
await expect(page.locator('x-pw-user-overlays')).toBeVisible();
- await page.overlay.hide();
+ await page.overlay.setVisible(false);
await expect(page.locator('x-pw-user-overlays')).toBeHidden();
- await page.overlay.show();
+ await page.overlay.setVisible(true);
await expect(page.locator('x-pw-user-overlays')).toBeVisible();
await expect(page.locator('#my-overlay')).toHaveText('Visible');
@@ -78,7 +78,7 @@ test('should survive navigation', async ({ browser, server }) => {
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
- await page.overlay.add('<div id="persistent">Survives Reload</div>');
+ await page.overlay.show('<div id="persistent">Survives Reload</div>');
await expect(page.locator('#persistent')).toHaveText('Survives Reload');
await page.goto(server.EMPTY_PAGE);
@@ -95,7 +95,7 @@ test('should remove overlay and not restore after navigation', async ({ browser,
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
- const disposable = await page.overlay.add('<div id="temp">Temporary</div>');
+ const disposable = await page.overlay.show('<div id="temp">Temporary</div>');
await expect(page.locator('#temp')).toHaveText('Temporary');
await disposable.dispose();
@@ -112,7 +112,7 @@ test('should sanitize scripts from overlay html', async ({ browser, server }) =>
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
- await page.overlay.add('<div id="safe">Safe</div><script>window.__injected = true</script>');
+ await page.overlay.show('<div id="safe">Safe</div><script>window.__injected = true</script>');
await expect(page.locator('#safe')).toHaveText('Safe');
expect(await page.evaluate(() => (window as any).__injected)).toBeUndefined();
@@ -124,7 +124,7 @@ test('should strip event handlers from overlay html', async ({ browser, server }
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
- await page.overlay.add('<div id="clean" onclick="window.__clicked=true">Click me</div>');
+ await page.overlay.show('<div id="clean" onclick="window.__clicked=true">Click me</div>');
await expect(page.locator('#clean')).toHaveText('Click me');
const hasOnclick = await page.locator('#clean').evaluate(el => el.hasAttribute('onclick'));
expect(hasOnclick).toBe(false);
@@ -138,7 +138,7 @@ test('should show action highlight and title on click', async ({ browser, server
await page.goto(server.EMPTY_PAGE);
await page.setContent('<button id="btn">Click me</button>');
- await page.overlay.configure({ actionDelay: 5000 });
+ await page.screencast.start(() => {}, { annotate: { duration: 5000 } });
const clickPromise = page.locator('#btn').click();
await expect(page.locator('x-pw-highlight')).toBeVisible();
@@ -149,48 +149,12 @@ test('should show action highlight and title on click', async ({ browser, server
await context.close();
});
-test('should apply locatorStyle to highlight element', async ({ browser, server }) => {
- const context = await browser.newContext();
- const page = await context.newPage();
- await page.goto(server.EMPTY_PAGE);
- await page.setContent('<button id="btn">Click me</button>');
-
- await page.overlay.configure({ actionDelay: 5000, locatorStyle: 'border: 5px solid red' });
- const clickPromise = page.locator('#btn').click();
-
- const highlight = page.locator('x-pw-highlight');
- await expect(highlight).toBeVisible();
- const border = await highlight.evaluate(el => el.style.border);
- expect(border).toBe('5px solid red');
-
- await clickPromise;
- await context.close();
-});
-
-test('should apply actionStyle to title element', async ({ browser, server }) => {
- const context = await browser.newContext();
- const page = await context.newPage();
- await page.goto(server.EMPTY_PAGE);
- await page.setContent('<button id="btn">Click me</button>');
-
- await page.overlay.configure({ actionDelay: 5000, actionStyle: 'font-size: 42px' });
- const clickPromise = page.locator('#btn').click();
-
- const title = page.locator('x-pw-title');
- await expect(title).toBeVisible();
- const fontSize = await title.evaluate(el => el.style.fontSize);
- expect(fontSize).toBe('42px');
-
- await clickPromise;
- await context.close();
-});
-
test('should auto-remove overlay after timeout', async ({ browser, server }) => {
const context = await browser.newContext();
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
- await page.overlay.add('<div id="timed">Temporary</div>', { timeout: 1 });
+ await page.overlay.show('<div id="timed">Temporary</div>', { duration: 1 });
await expect(page.locator('.x-pw-user-overlay')).toHaveCount(0);
await context.close();
@@ -201,7 +165,7 @@ test('should allow styles in overlay html', async ({ browser, server }) => {
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
- await page.overlay.add('<div id="styled" style="color: red; font-size: 20px;">Styled</div>');
+ await page.overlay.show('<div id="styled" style="color: red; font-size: 20px;">Styled</div>');
await expect(page.locator('#styled')).toHaveText('Styled');
const color = await page.locator('#styled').evaluate(el => getComputedStyle(el).color);
expect(color).toBe('rgb(255, 0, 0)');
diff --git a/tests/playwright-test/to-have-screenshot.spec.ts b/tests/playwright-test/to-have-screenshot.spec.ts
index 6ec17e52f7..75363092c4 100644
--- a/tests/playwright-test/to-have-screenshot.spec.ts
+++ b/tests/playwright-test/to-have-screenshot.spec.ts
@@ -1584,3 +1584,20 @@ test.describe('update-snapshots', () => {
expect(comparePNGs(newBaseline, EXPECTED_SNAPSHOT)).not.toBe(null);
});
});
+
+test('should hide overlays during toHaveScreenshot', async ({ runInlineTest }, testInfo) => {
+ const result = await runInlineTest({
+ ...playwrightConfig({
+ snapshotPathTemplate: '__screenshots__/{testFilePath}/{arg}{ext}',
+ }),
+ '__screenshots__/a.spec.js/snapshot.png': whiteImage,
+ 'a.spec.js': `
+ const { test, expect } = require('@playwright/test');
+ test('is a test', async ({ page }) => {
+ await page.overlay.show('<div style="position:absolute;inset:0;background:red"></div>');
+ await expect(page).toHaveScreenshot('snapshot.png');
+ });
+ `
+ });
+ expect(result.exitCode).toBe(0);
+});
diff --git a/utils/generate_types/overrides-test.d.ts b/utils/generate_types/overrides-test.d.ts
index c944cadba5..e21a0d33ec 100644
--- a/utils/generate_types/overrides-test.d.ts
+++ b/utils/generate_types/overrides-test.d.ts
@@ -260,7 +260,7 @@ export interface PlaywrightWorkerOptions {
connectOptions: ConnectOptions | undefined;
screenshot: ScreenshotMode | { mode: ScreenshotMode } & Pick<PageScreenshotOptions, 'fullPage' | 'omitBackground'>;
trace: TraceMode | /** deprecated */ 'retry-with-trace' | { mode: TraceMode, snapshots?: boolean, screenshots?: boolean, sources?: boolean, attachments?: boolean };
- video: VideoMode | /** deprecated */ 'retry-with-video' | { mode: VideoMode, size?: ViewportSize, annotate?: { action?: { delay?: number, actionStyle?: string, locatorStyle?: string }, test?: { level?: 'file' | 'title' | 'step' } } };
+ video: VideoMode | /** deprecated */ 'retry-with-video' | { mode: VideoMode, size?: ViewportSize, annotate?: { action?: { duration?: number, position?: 'top-left' | 'top' | 'top-right' | 'bottom-left' | 'bottom' | 'bottom-right', fontSize?: number }, test?: { level?: 'file' | 'title' | 'step', position?: 'top-left' | 'top' | 'top-right' | 'bottom-left' | 'bottom' | 'bottom-right', fontSize?: number } } };
}
export type ScreenshotMode = 'off' | 'on' | 'only-on-failure' | 'on-first-failure';
diff --git a/utils/generate_types/overrides.d.ts b/utils/generate_types/overrides.d.ts
index 6f7f23037c..dd9ee4b97c 100644
--- a/utils/generate_types/overrides.d.ts
+++ b/utils/generate_types/overrides.d.ts
@@ -248,6 +248,11 @@ export interface Screencast {
width: number;
height: number;
};
+ annotate?: {
+ duration?: number;
+ position?: 'top-left' | 'top' | 'top-right' | 'bottom-left' | 'bottom' | 'bottom-right';
+ fontSize?: number;
+ };
}): Promise<Disposable>;
}