How do I manage multiple locators and dialog overlays in Playwright?


To manage multiple locators and dialog overlays in @playwright/test, you can use the locator.or() method. This allows you to create a locator that matches either of two locators, which is helpful when you want to click on a button but sometimes encounter a dialog overlay instead.

Here's an example where you want to click on a "New email" button, but a security settings dialog might appear:

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

test('handle locator or and dialog overlays', async ({ page }) => {
  await page.goto('https://ray.run');

  const newEmail = page.getByRole('button', { name: 'New email' });
  const dialog = page.getByText('Confirm security settings');
  await expect(newEmail.or(dialog)).toBeVisible();

  // Handle dialog if visible, then click on newEmail

This code waits until either newEmail or dialog is visible on the page. If dialog is visible, you can click on the "Dismiss" button to close it before clicking on newEmail. If not, simply click on newEmail.

Additionally, you can filter elements that don't match certain conditions using options like hasNot and hasNotText in locator.filter(). For example:

const rowLocator = page.locator('tr');
await rowLocator
  .filter({ hasNotText: 'text in column 1' })
  .filter({ hasNot: page.getByRole('button', { name: 'column 2 button' }) })

This code filters out rows containing specific text in column 1 or having a column 2 button with certain text.

Lastly, use web-first assertions like expect(locator).toBeAttached() to ensure an element is present in the page's DOM. This is different from expect(locator).toBeVisible(), which checks if an element is both attached and visible.

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.