Dialogs
Introduction
CSTesting can interact with JavaScript dialogs: alert, confirm, and prompt, as well as the beforeunload confirmation when closing the page. You set how the next dialog will be handled before the action that triggers it (e.g. before click()). If you do not set a response, the action that opens the dialog can block until the dialog is handled (behavior depends on the browser/backend).
alert(), confirm(), prompt() dialogs
In C:\CSTesting-Python, register a dialog handler on BrowserApi with browser.set_dialog_handler(fn). The handler receives {"type": "alert"|"confirm"|"prompt"|..., "message": "..."} and returns a dict:
- Accept:
{"accept": True}— optional"prompt_text"for prompts. - Dismiss:
{"accept": False}— confirm/prompt Cancel.
Set the handler before the action that opens the dialog. Call browser.set_dialog_handler(None) to clear.
Example: accept alert
def on_dialog(evt):
return {"accept": True}
browser.set_dialog_handler(on_dialog)
await browser.locator("#btnAlert").click() # alert("Hello")
browser.set_dialog_handler(None)
Example: dismiss confirm
browser.set_dialog_handler(lambda e: {"accept": False})
await browser.locator("#btnConfirm").click()
Example: prompt with text
browser.set_dialog_handler(lambda e: {"accept": True, "prompt_text": "my input"})
await browser.locator("#btnPrompt").click()
beforeunload dialog
Playwright may show a beforeunload prompt when leaving the page. Use the same set_dialog_handler pattern before await browser.close() or navigation if your app uses beforeunload.
browser.set_dialog_handler(lambda e: {"accept": True})
await browser.close()
browser.set_dialog_handler(None)
Print dialogs
CSTesting does not provide a dedicated API for print dialogs (window.print()). The native print dialog is controlled by the OS/browser and is not a JavaScript alert/confirm/prompt dialog.
To test that a print dialog would be triggered, you can:
- Stub
window.printin the page (e.g. viabrowser.evaluate(...)) and assert that it was called, or - Rely on your app's own logic and assert on the state of the page before/after the "Print" action.
Example of stubbing and asserting that print was requested:
from cstesting import expect
await browser.goto("https://example.com/page-with-print")
await browser.evaluate(
"window.printRequested = false; window.print = function() { window.printRequested = true; };"
)
await browser.locator("//button[contains(.,'Print')]").first().click()
requested = await browser.evaluate("window.printRequested")
expect(requested).to_be_truthy()
(Adjust the selector to match your page; use XPath if needed, e.g. //button[contains(.,'Print')].)
Summary
| Dialog type | CSTesting API | Notes |
|---|---|---|
| alert / confirm / prompt | browser.set_dialog_handler(fn) then action | Return {"accept": True/False, "prompt_text": "..."}. |
| beforeunload | Handler before close() / navigate | Same handler API. |
| No built-in API | Stub window.print and assert it was called if needed. |