Wednesday, April 30, 2025

Playwright force click on hidden element

 In Playwright, forcing a click on a hidden element might not work due to the library's built-in checks for element visibility and interaction readiness, even when using force: true. The force option bypasses some checks (like actionability), but Playwright still requires the element to be in the DOM and not completely obscured or detached. Here’s how to troubleshoot and resolve the issue:


NOTE : force: true bypasses actionability checks (like visibility, being in viewport), but:

  1. It does not magically make a hidden element clickable if it's not rendered or present.
  2. If the element is display: none or detached from DOM, Playwright still cannot click it.

Playwright force click on hidden element


Use the force: true only if the element is invisible but in DOM

In this example we are using force option to make a hidden element clickable if it's not rendered or present.

const element = await page.$('your-selector');
if (element) {
  await page.click('your-selector', { force: true });
} else {
  console.error('Element not found');
}

Use JavaScript to click it manually

If you're sure you want to simulate the click regardless of visibility:
await page.evaluate(() => {
  const el = document.querySelector('#your-element');
  if (el) (el as HTMLElement).click();
});


Make it visible first

If the element is hidden by CSS:
await page.evaluate(() => {
  const el = document.querySelector('#your-element');
  if (el) el.style.display = 'block';  // or remove a class hiding it
});
await page.click('#your-element');


Also you can implement the following approach as well.

// Try forced click
  try {
    await page.click(selector, { force: true });
    console.log('Forced click successful');
  } catch (error) {
    console.error('Forced click failed, trying JS click:', error);
    // Fallback to JavaScript click
    await page.evaluate((sel) => {
      document.querySelector(sel).click();
    }, selector);
  }
}

This is all about locating the hidden element in playwright.


No comments:

Post a Comment