Modals & Overlays
Dialogs built into the page: a native <dialog>, a custom modal, one modal on top of another, and a popup that shows up whenever it likes.
Find the dialog, then look inside it
A modal is a dialog with a name. Scope every locator to it: buttons such as "Close" or "Cancel" often exist elsewhere on the page too.
const invite = page.getByRole('dialog', { name: 'Invite teammate' });
await invite.getByLabel('Email').fill('ada@example.com');
await invite.getByRole('button', { name: 'Send invite' }).click();
await expect(invite).toBeHidden();The page behind a modal
A native <dialog> opened with showModal() makes the rest of the page inert. Playwright waits for an inert button to become clickable, so the click times out. That is the modal working. Custom modals only cover the page with a backdrop; there the error says another element "intercepts pointer events".
// A short trial click proves the page behind is blocked.
await expect(
page.getByRole('button', { name: 'Rename project' }).click({ trial: true, timeout: 1000 })
).rejects.toThrow();Focus
A good modal moves focus inside when it opens, keeps Tab inside while open, and gives focus back to the button that opened it. Check all three with toBeFocused().
A modal on top of a modal
Both dialogs are on the page at the same time. Give each its own locator by name, and assert which ones are still open.
Popups that appear whenever they like
Newsletter and cookie popups appear at random moments and block clicks. A try/catch around every click cannot cover all of them. Register a handler once: before each action, Playwright checks whether the overlay is visible and runs your handler first.
await page.addLocatorHandler(
page.getByRole('dialog', { name: 'Join our newsletter' }),
async (overlay) => {
await overlay.getByRole('button', { name: 'No thanks' }).click();
}
);Native dialog
Project: Apollo
Custom modal
Sending an invite takes a moment.
Modal over a modal
Post: Hello world
Shop
Cart: 0 items
Loading products…
Related exercises
- Dialogs & WindowsBeginnerJavaScript DialogsHandle native alert, confirm and prompt dialogs, including the ones that arrive in pairs, late, or when you leave.
- Mouse & KeyboardBeginnerKeyboard ActionsDrive the page with the keyboard alone: typing, Tab order, shortcuts and held keys.
- Dynamic ElementsIntermediateActionabilityUnderstand what Playwright waits for before it clicks, and what force: true hides.
Read the guide: Playwright auto-waiting: how to fix flaky tests