Finding and clicking buttons

Find buttons by role and name

Find a button the way a user would: by its role and the text on it. That text is the button's accessible name.

await page.getByRole('button', { name: 'Primary action' }).click();

Names match as substrings

name: 'Click me' also matches "Double click me" and "Right click me", because names are matched as case-insensitive substrings. Playwright then refuses to act and reports a strict mode violation, listing every match. Pass exact: true to match the whole name.

await page.getByRole('button', { name: 'Click me', exact: true }).click();

Other kinds of click

await page.getByRole('button', { name: 'Double click me' }).dblclick();
await page.getByRole('button', { name: 'Right click me' }).click({ button: 'right' });

Playwright waits before it clicks

Before clicking, Playwright waits until the button is visible, stable and enabled. Clicking a disabled button does not fail at once: it waits, then times out with an error that explains why. To check the state itself, assert it:

await expect(page.getByRole('button', { name: 'Disabled button' })).toBeDisabled();
await expect(page.getByTestId('button-result')).toHaveText('Button clicked');

Basic buttons

Normal left clicks. One button is disabled.

Double and right click

These buttons ignore a normal click.