Video Recording in Playwright
















Complete Guide to Video Recording in Playwright Java – Step-by-Step Tutorial with Example

Video recording in Playwright Java is one of the most powerful features for modern test automation. When you are running automated browser tests, especially in large-scale enterprise applications, simply relying on logs and screenshots is often not enough. That’s where Playwright’s built-in video recording capability becomes extremely valuable.

In this comprehensive guide, you will learn:

  • What video recording in Playwright Java is

  • Why it is important in automation testing

  • How video recording works internally

  • How to configure and enable it

  • Step-by-step Java example

  • Best practices for managing recorded videos

  • CI/CD integration tips

  • Common mistakes to avoid

This article is fully SEO-optimized, beginner-friendly, and written in a natural human tone so you can easily understand and implement video recording in your Playwright automation framework.


What Is Video Recording in Playwright Java?

In Playwright Java, video recording is a feature that allows you to capture the entire browser session during automated test execution. The output is saved as a video file (usually in .webm format), which you can replay later to analyze the test flow.

Instead of guessing what went wrong from logs, you can visually watch the execution exactly as it happened.

This feature is enabled at the BrowserContext level, meaning every page created inside that context will automatically have its own recorded video.


Why Video Recording Is Important in Test Automation

Modern web applications are dynamic. They use:

  • AJAX requests

  • Lazy loading

  • Dynamic UI updates

  • Animations

  • Conditional rendering

When a test fails, it may not always be obvious why.

1. Better Debugging

When a test fails, watching the recorded video helps you:

  • See if an element was visible

  • Check if the page loaded properly

  • Identify timing issues

  • Detect UI glitches

  • Understand unexpected redirects

Instead of spending hours analyzing logs, you can quickly pinpoint the issue.


2. Complete Test Flow Visibility

Unlike screenshots (which capture only one moment), video recording captures:

  • Every click

  • Every navigation

  • Every form fill

  • Every scroll

  • Every interaction

It provides complete transparency of the test journey.


3. Useful for Reporting and Stakeholders

You can attach recorded videos to:

  • Test reports

  • CI/CD pipeline reports

  • Bug tracking systems

  • Email reports

Developers and stakeholders can watch the execution without running the test themselves.


4. Regression Testing Validation

In regression testing, you want to ensure that new changes do not break existing flows.

Video recording allows you to:

  • Visually compare test runs

  • Confirm UI behavior remains consistent

  • Validate animation or layout changes


How Video Recording Works in Playwright Java

Let’s understand the internal working mechanism.

1. BrowserContext-Level Configuration

Video recording is enabled while creating a BrowserContext.

When you configure:

setRecordVideoDir(Paths.get("videos/"))

Playwright begins capturing all actions performed inside pages created from that context.


2. Automatic Video Creation per Page

Each page inside the context:

Page page = context.newPage();

Will automatically generate its own video file.


3. Video Storage

By default:

  • Videos are stored in the directory you specify.

  • Files are saved in .webm format.

  • Video is finalized only after the page or context is closed.

Important: If you forget to close the page or context, the video may not be saved properly.


Video Format Used in Playwright

Playwright saves videos in:

.webm format

Why .webm?

  • Lightweight

  • High compression

  • Browser compatible

  • Easy to attach in reports

Most modern browsers and media players support .webm.


Step-by-Step Guide: Record Video in Playwright Java

Let’s automate:

https://example.com

We will:

  1. Launch browser

  2. Enable video recording

  3. Perform actions

  4. Close context

  5. Verify video saved


Java Code Example – Record Video in Playwright

import com.microsoft.playwright.*; import java.nio.file.Paths; public class VideoRecordingExample { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { // (a) Launch browser Browser browser = playwright.chromium() .launch(new BrowserType.LaunchOptions().setHeadless(false)); // (b) Set video recording options Browser.NewContextOptions contextOptions = new Browser.NewContextOptions() .setRecordVideoDir(Paths.get("videos/")) // Directory to save videos .setRecordVideoSize(1280, 720); // Optional resolution // (c) Create browser context with video enabled BrowserContext context = browser.newContext(contextOptions); // (d) Create new page Page page = context.newPage(); // (e) Navigate to website page.navigate("https://example.com"); // (f) Perform some action page.click("text=More information"); // Wait for demo purpose page.waitForTimeout(3000); // (g) Close page and context (important to finalize video) page.close(); context.close(); System.out.println("Video saved in videos/ directory"); } } }


Code Explanation

(a) Launch Browser

Browser browser = playwright.chromium().launch(...)

Launches Chromium browser instance.


(b) Enable Video Recording

.setRecordVideoDir(Paths.get("videos/"))

Specifies the folder where videos will be saved.

.setRecordVideoSize(1280, 720)

Optional resolution setting.


(c) Create BrowserContext

Video recording starts only when the context is created with recording options.


(d) Create Page

Each page gets its own video file.


(e) Perform Actions

Any interaction is recorded:

  • Click

  • Fill

  • Scroll

  • Navigation


(f) Close Page & Context

Very Important:

Video is finalized only after closing:

page.close(); context.close();


Project Structure Example

Project ├── src ├── videos │ ├── 3f9b2d.webm │ ├── 6a1c7e.webm └── pom.xml

Each execution generates a unique video file.


Best Practices for Video Recording in Playwright Java

1. Record Only When Necessary

Video recording consumes:

  • Disk space

  • Execution time

  • CI storage

Best practice:

  • Enable video only for failed tests

  • Enable video in debug mode

  • Disable in full regression unless needed


2. Use Separate Directory Per Test Run

Example:

videos/run_01/ videos/run_02/

Prevents overwriting old videos.


3. Clean Up Old Videos

Large automation projects may generate hundreds of videos.

Implement cleanup strategy:

  • Delete older than 7 days

  • Archive important runs


4. Integrate with CI/CD

Video files can be attached to:

  • Jenkins artifacts

  • GitHub Actions artifacts

  • Azure DevOps pipelines

  • GitLab CI

This helps teams review failures without local execution.


Video Recording vs Screenshots vs Trace Viewer

Let’s compare:

FeatureScreenshotVideoTrace Viewer
Captures single momentYesNoNo
Captures entire flowNoYesYes
Shows timelineNoLimitedYes
LightweightYesModerateModerate
Best for debuggingMediumHighVery High

Video is ideal when you need visual flow confirmation.


Common Mistakes to Avoid

1. Forgetting to Close Context

If you don’t close the context:

Video may not save properly.


2. Not Creating Video Directory

Make sure:

videos/

Exists and is writable.


3. Enabling Video in Headless Mode Without Testing

Video works in headless mode, but always test configuration once in headed mode.


4. Large File Storage in CI

Videos can accumulate quickly.

Always configure:

  • Artifact cleanup

  • Retention policies


Advanced Customization Tips

Retrieve Video Path Programmatically

You can get the video file path:

Path videoPath = page.video().path(); System.out.println("Video Path: " + videoPath);

Useful for:

  • Attaching video to reports

  • Custom naming logic


Rename Video File

You can move video after test execution:

page.video().saveAs(Paths.get("videos/TestCase01.webm"));

This gives meaningful file names.


When Should You Use Video Recording?

Use video recording when:

  • Debugging flaky tests

  • Validating UI transitions

  • Creating demo automation videos

  • Demonstrating automation capability

  • Investigating CI failures

Avoid always-on recording in large-scale test suites unless necessary.


SEO Summary: Video Recording in Playwright Java

If you are working with Playwright automation using Java, enabling video recording can significantly improve debugging efficiency, reporting clarity, and regression confidence. By configuring video recording at the BrowserContext level, you ensure that every browser interaction is captured visually.

Key takeaways:

  • Video recording is enabled via setRecordVideoDir()

  • Videos are saved in .webm format

  • Each page generates a separate video

  • Video is finalized only after closing page/context

  • Ideal for debugging and CI reporting

  • Should be used strategically to avoid storage overload


Final Thoughts

Video recording in Playwright Java is not just a luxury feature — it is a practical debugging and reporting tool that enhances test automation reliability.

Instead of relying only on console logs or screenshots, a full video gives you a real-time replay of your automated browser session. This makes troubleshooting faster, collaboration easier, and automation frameworks more robust.

If you are building a scalable automation framework using Playwright with Java, integrating video recording properly can elevate your testing strategy to a professional level.


Suggested Posts:

1. Count Multiple Elements in Dropdown in Playwright
2. File Upload in Playwright
3. Comma Selectors in Playwright
4. Trace Viewer in Playwright
5. Page Object Model in Playwright

How to Show Visible Elements in Playwright


















Visible Elements in Playwright Java – Complete Guide with Examples

When working with web automation, one of the most important concepts to understand is visible elements. Many beginners assume that if an element exists in the DOM, it can be interacted with. However, that is not always true. In real-world web applications, elements may exist in the page structure but still not be visible or interactable.

In this comprehensive guide, you will learn:

  • What visible elements are in web automation

  • Why visibility matters in Playwright

  • Common reasons elements are not visible

  • How Playwright handles visibility internally

  • How to filter visible elements using Playwright Java

  • A complete working Java example

  • Best practices for handling visible elements

  • Real-world automation use cases

This article is fully SEO optimized, AdSense-friendly, and written in a natural human style to help both beginners and experienced automation engineers.


What Are Visible Elements?

In web automation, a visible element is an element that is actually displayed on the web page and can be seen or interacted with by a user.

An element may exist in the DOM (Document Object Model) but still not be visible on the page.

For example, an element might be:

  • Hidden using CSS (display: none)

  • Hidden using visibility: hidden

  • Invisible using opacity: 0

  • Positioned outside the viewport

  • Overlapped by another element

  • Not yet rendered due to dynamic loading

  • Inside a collapsed dropdown or modal

In all these cases, the element exists in the DOM but is not visible to the user.


Why Visibility Matters in Playwright?

Playwright is designed to simulate real user behavior. Unlike some automation tools that interact with elements simply because they exist in the DOM, Playwright ensures that actions like:

  • click()

  • fill()

  • type()

  • hover()

are performed only on visible and actionable elements.

This is extremely important for realistic testing.

Preventing False Positives

If your automation script interacts with hidden elements, it may:

  • Pass tests incorrectly

  • Ignore UI bugs

  • Miss rendering issues

  • Fail in real-world user scenarios

Playwright prevents such problems by verifying visibility before performing actions.


Common Scenarios Where Elements Are Not Visible

Understanding why elements are not visible helps you debug automation issues faster.

1. CSS Display None

display: none;

The element is completely removed from visual layout.


2. Visibility Hidden

visibility: hidden;

The element occupies space but is not visible.


3. Opacity Zero

opacity: 0;

The element is transparent.


4. Off-Screen Elements

Elements that require scrolling to become visible.


5. Dynamic Rendering

Elements that load after:

  • AJAX calls

  • API responses

  • User interactions


6. Overlapping Elements

Sometimes popups or modals cover other elements.


How Playwright Handles Visibility

Playwright includes built-in checks for:

  • Element visibility

  • Element stability

  • Element enabled state

  • Element receiving pointer events

This ensures that automation mimics actual user interactions.


Working with Visible Elements in Playwright Java

When you locate elements using:

page.locator("button");

It may return multiple elements. Some might be visible, others hidden.

Playwright allows you to:

  • Filter only visible elements

  • Check visibility status

  • Assert visibility

  • Extract visible content


Steps to Show All Visible Elements in Playwright Java

To display visible elements on a webpage:

  1. Navigate to the webpage

  2. Select all elements using universal selector *

  3. Loop through elements

  4. Check visibility

  5. Print visible elements


Example Website

We will use:

https://example.com

This is a simple static demo site suitable for demonstration.


Complete Java Code Example

Below is a working Playwright Java example that prints all visible elements:

import com.microsoft.playwright.*; public class VisibleElementsExample { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { Browser browser = playwright.chromium() .launch(new BrowserType.LaunchOptions().setHeadless(false)); BrowserContext context = browser.newContext(); Page page = context.newPage(); // Navigate to website page.navigate("https://example.com"); // Select all elements Locator allElements = page.locator("*"); int count = allElements.count(); System.out.println("Total Elements Found: " + count); System.out.println("Visible Elements:"); for (int i = 0; i < count; i++) { Locator element = allElements.nth(i); if (element.isVisible()) { String tagName = element.evaluate("el => el.tagName").toString(); String text = element.innerText().trim(); System.out.println("Tag: " + tagName + ", Text: " + text); } } browser.close(); } } }


Code Explanation

Let’s break down the important parts.


(a) Navigate to Website

page.navigate("https://example.com");

Loads the webpage.


(b) Select All Elements

page.locator("*");

The universal selector * selects every element in the DOM.


(c) Count Elements

allElements.count();

Returns total number of elements on the page.


(d) Loop Through Elements

We iterate through each element using:

allElements.nth(i);


(e) Check Visibility

element.isVisible();

Returns true only if element is visible.


(f) Extract Tag Name

element.evaluate("el => el.tagName");

Uses JavaScript to retrieve the HTML tag name.


(g) Get Visible Text

element.innerText();

Returns only visible text content.


Using Visibility in Assertions

In automation testing, you often need to verify if an element is visible.

Example:

Locator successMessage = page.locator(".success"); if (successMessage.isVisible()) { System.out.println("Success message is visible"); }

Or using Playwright Assertions:

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; assertThat(successMessage).isVisible();

This ensures correct UI behavior.


Filtering Only Visible Elements

Playwright also allows filtering directly:

Locator visibleButtons = page.locator("button").filter( new Locator.FilterOptions().setHasText("Submit") );

You can also use:

page.locator("button:visible");

This CSS pseudo-class selects only visible elements.


Real-World Use Cases

Handling visible elements is important in:

  • Dropdown menus

  • Modal dialogs

  • Pop-up alerts

  • Dynamic search results

  • Pagination controls

  • Navigation menus

Example:

A dropdown contains 10 items but only 5 are visible after clicking.

Your script should only interact with visible items.


Debugging Visible Elements

Sometimes testers log visible elements to debug UI rendering issues.

Example:

  • Checking which buttons are visible after login

  • Verifying menu items based on user roles

  • Confirming dynamic content loading

This helps ensure:

  • UI consistency

  • Correct rendering

  • Proper access control


Best Practices for Handling Visible Elements

To make automation stable:


1. Always Check Visibility Before Action

Even though Playwright auto-checks visibility, explicit checks improve clarity.


2. Use Assertions

Instead of printing results, assert visibility in test cases.


3. Avoid Force Click

Avoid using force options unless absolutely necessary.


4. Wait for Dynamic Elements

Use:

page.waitForSelector(".element");

before checking visibility.


5. Scroll Into View

If element is outside viewport:

element.scrollIntoViewIfNeeded();


Common Interview Questions

Q1: What is a visible element?

An element that is displayed and interactable on the web page.

Q2: Can an element exist in DOM but not be visible?

Yes.

Q3: How do you check visibility in Playwright?

Using:

element.isVisible();

Q4: Why is visibility important?

To simulate real user interactions.


Common Mistakes to Avoid

  • Interacting with hidden elements

  • Not waiting for dynamic rendering

  • Ignoring overlapping elements

  • Using static waits instead of smart waits


Advanced Tip: Handling Hidden Dropdown Elements

Some dropdown options are hidden until clicked.

Example:

page.locator("#dropdown").click(); Locator options = page.locator(".dropdown-item"); for (int i = 0; i < options.count(); i++) { if (options.nth(i).isVisible()) { System.out.println(options.nth(i).innerText()); } }

This ensures you only interact with displayed options.


Conclusion

Understanding visible elements in Playwright Java is fundamental for building realistic and reliable automation tests. Just because an element exists in the DOM does not mean it is visible or interactable.

In this complete guide, we covered:

  • What visible elements are

  • Why visibility matters

  • Common hidden element scenarios

  • How Playwright checks visibility

  • Java example to display visible elements

  • Best practices and interview questions

Mastering visibility handling ensures:

  • Stable automation

  • Realistic user simulation

  • Reduced flaky tests

  • Accurate UI validation

If you are serious about becoming an expert in Playwright automation, always prioritize working with visible and interactable elements.


Suggested Posts:

1. BrowserContext in Playwright
2. File Upload in Playwright
3. Comma Selectors in Playwright
4. Trace Viewer in Playwright
5. Page Object Model in Playwright