How do I wait for an event on a specific element in Playwright? Like page.waitForEvent
(docs) but from a specific element only, not the whole page.
This can be done with the Locator.evaluate
method, making note of the fact that Playwright will not let you forward the actual browser event as-is, so any values that you want from your event need to be explicitly sent over:
const myLocator = page.locator("my-element").first();
await myLocator.waitFor();
const myEvent = await myLocator.evaluate(
(element) =>
new Promise((resolve) =>
element.addEventListener("<event-type-here>", (event) => {
// extract some example event data
const { type, target } = event;
const { id } = target;
// then resolve the promise with that data
resolve({ type, targetId: id });
})
)
);