Sunday, April 13, 2025

Handle Hidden Elements in dropdown in playwright

 In this example we will explore how to effectively handle hidden dropdowns using Playwright, a robust framework for browser automation. Hidden dropdowns can be a bit sneaky in UI automation — especially in frameworks like React, Angular, or libraries like Bootstrap, Select2, or Material UI. 

These dropdowns may:

  1. Not be visible in the DOM until opened
  2. Be hidden via CSS (display: none, visibility: hidden, etc.)
  3. Render outside the component (in a portal/div elsewhere in the DOM)

Handle Hidden Elements in dropdown in playwright

How to use debugger in chrome dev tool :


1. Open a website or blank page.

2. Open DevTools (F12 or Ctrl+Shift+I / Cmd+Option+I)

3. Go to the Console tab.

4. Paste and run
setTimeout(() => {
  debugger;
}, 5000);
5. After 5 seconds, the browser will pause, and you can:
  • Inspect variables
  • Step through the code
  • Use the Console while paused

How to use debugger in chrome dev tool :



Understanding Hidden Dropdowns

Hidden dropdowns are elements that contain options but are not directly visible in the DOM until a user interacts with them. This can make it difficult to inspect and interact with these elements programmatically.

Example 

// @ts-check
import { test, expect } from '@playwright/test';

test('Handle bootstrap dropdown', async ({page}) => {
 
  await page.goto("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");

  // Fill in the username and password
  await page.locator("input[placeholder='Username']").fill("Admin");
  await page.locator("input[placeholder='Password']").fill("admin123");
  
  // Click the login button
  await page.locator("button[type='submit']").click();
  
  // Click on the PIM tab
  await page.locator("//span[text()='PIM']").click();

  // Before you click on drop down go to console and start debugger using below mention script
  /* 
  setTimeout(() => {   debugger;  }, 5000);  
  */

// Click on the Sub Unit dropdown
  await page.locator("//label[text()='Sub Unit']//following::div[1]").click();

  // Select an option from the dropdown
  await page.locator("//span[text()='Development']").click();

});  

Handling hidden dropdowns in Playwright requires understanding how to interact with dynamically generated elements that may not be immediately visible. 


No comments:

Post a Comment