Skip to content

Instantly share code, notes, and snippets.

@atistrcsn
Last active February 9, 2025 14:02
Show Gist options
  • Select an option

  • Save atistrcsn/7e7e540609b2802746a47a399c062168 to your computer and use it in GitHub Desktop.

Select an option

Save atistrcsn/7e7e540609b2802746a47a399c062168 to your computer and use it in GitHub Desktop.
Wait for Manual Click - Playwright Helper Function
import { Page } from "playwright"
/**
* Waits for a manual user click on a specified element in Playwright tests. Useful for scenarios
* requiring human verification or manual intervention during automated test execution. The function
* injects a click listener into the page context and waits for a genuine click event.
*
* Typical use cases:
* - Manual verification steps in automated flows
* - Interactive debugging of test scenarios
* - Hybrid manual/automated testing workflows
*
* @example
* // Wait indefinitely for manual click
* await waitForManualClick(page, '.verify-button');
*
* // Wait with 5 second timeout
* await waitForManualClick(page, '#submit-form', 5000);
*
* @param page - Playwright Page object
* @param selector - CSS selector for the target element
* @param timeout - Optional timeout in milliseconds (default: 0 - no timeout)
* @returns Promise that resolves when the click happens
* @throws Error if element is not found or timeout occurs
*/
export async function waitForManualClick(page: Page, selector: string, timeout = 0): Promise<void> {
// First verify if element exists to fail fast
const element = await page.locator(selector)
if (!element) {
throw new Error(`Element with selector "${selector}" not found`)
}
// Set up click detection
await page.evaluate((sel) => {
window["clickHappened"] = false
const element = document.querySelector(sel)
if (element) {
element.addEventListener("click", () => {
window["clickHappened"] = true
})
}
}, selector)
// Wait for click
try {
await page.waitForFunction(() => window["clickHappened"] === true, { timeout })
} catch (error) {
if (error instanceof Error && error.message.includes("timeout")) {
throw new Error(`Timeout waiting for click on "${selector}" after ${timeout}ms`)
}
throw error
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment