In Selenium, how do you read a JavaScript confirm dialog's text and then accept or cancel it?
answer
- It is a switch, not a find
- One handle object, four methods
- OK versus Cancel, and what returns
- switchTo().alert() gives you an Alert
- getText, accept, dismiss, sendKeys
basics
~10 sTake the dialog with driver.switchTo().alert(), which returns an Alert. Call getText() for its message, then accept() to press OK or dismiss() to press Cancel. Use sendKeys only on a prompt, before accepting it.
solid answer
~40 sA native dialog is drawn by the browser, not by the page, so no locator finds it — Selenium reaches it through `driver.switchTo().alert()`, which returns an `Alert` handle. That handle has four methods: `getText()` returns the message the dialog is asking, `accept()` presses OK, `dismiss()` presses Cancel, and `sendKeys(String)` types into a `prompt`'s input field. What the page sees depends on which you call: a `confirm` returns `true` for accept and `false` for dismiss, and a `prompt` returns the typed text for accept and `null` for dismiss. Read before you answer — assert on `getText()` first, so an unexpected dialog fails the test instead of being confirmed by reflex. If no dialog is open, `switchTo().alert()` throws `NoAlertPresentException` rather than returning null.
code
java · 6 linesdriver.findElement(By.id("gift-message")).click();
Alert dialog = driver.switchTo().alert();
String question = dialog.getText();
dialog.sendKeys("Happy reading, from the bookshop");
dialog.accept();
System.out.println("Answered: " + question);go deeper
Recall the three calls in order: switchTo().alert() to take the dialog, getText() to read it, then accept() or dismiss() to answer. Remember that sendKeys applies to a prompt only.
Explain what the page receives: accept makes confirm return true and dismiss makes it false, while on a prompt accept hands back the typed text and dismiss hands back null.
Demonstrate that a test asserts the dialog's message before answering it, so a wrong or unexpected dialog fails loudly rather than being confirmed by a reflexive accept buried in a helper.
Weigh how much product behaviour should ride on native dialogs at all. They cannot be located, styled or asserted on like page content, and every automated check has to special-case them.
## Three dialogs, one API A page can open three **native dialogs** from script, and each of them blocks the page until it is answered: - `alert("...")` shows a message and one button; the page's script resumes when it closes and learns nothing about how. - `confirm("...")` shows a message with OK and Cancel, and returns `true` or `false` to the script. - `prompt("...")` shows a message, a text field, OK and Cancel, and returns the typed string or `null`. They are not page content. The browser draws them, they have no DOM nodes, and no locator reaches them: `driver.findElement(By.cssSelector(".modal"))` finds an application's own styled modal, never a native dialog. Selenium therefore gives them a switch of their own. ## Why the dialog gets its own switch While a native dialog is up the page is genuinely stopped: the script that called `confirm` has not returned, and nothing on the page can be clicked. The driver is blocked too, because the protocol builds that in — almost every WebDriver command starts by checking for an open prompt, so `findElement`, `click`, `getCurrentUrl` and `executeScript` refuse to do their usual work while one is open. The four alert commands are exempt precisely so a test can reach the dialog and answer it. Without that exemption there would be no way out of the block short of throwing the session away. ## Taking the dialog `driver.switchTo().alert()` returns an `Alert`, a small handle with exactly four methods. The client checks that a prompt is present when the handle is taken, so if nothing is open the call itself throws `NoAlertPresentException` instead of handing back a null or an empty object. | Method | What it does | What the page's own call returns | |---|---|---| | `getText()` | Returns the dialog's message | nothing; the dialog stays open | | `accept()` | Presses OK | `confirm` gets `true`; `prompt` gets the field's text | | `dismiss()` | Presses Cancel | `confirm` gets `false`; `prompt` gets `null` | | `sendKeys(String)` | Types into a `prompt`'s field | nothing until `accept()` follows | Two details catch people out. `getText()` returns the **message the page asked**, never the text typed into a `prompt`. And `sendKeys` is meaningful only on a `prompt`: an `alert` and a `confirm` have no input field, so sending text to one is an error rather than a harmless no-op. ## A checkout, step by step 1. The test clicks **Gift message** on the bookshop's checkout and the page calls `prompt("Add a gift message?")`. 2. `Alert dialog = driver.switchTo().alert();` takes the handle. 3. `dialog.getText()` returns `"Add a gift message?"`; assert on it, so an unexpected dialog fails the test instead of being answered blindly. 4. `dialog.sendKeys("Happy reading")` fills the field. 5. `dialog.accept()` closes the dialog, and the page receives `"Happy reading"` as the value of `prompt`. Had step 5 been `dismiss()`, `prompt` would have returned `null` and the typed text would have been thrown away — nothing in the field is submitted until OK is pressed. ## What the switch does not do - It does **not** change the driver's browsing context: the frame and window it pointed at before the dialog are the ones it points at afterwards. - It does **not** wait: the dialog is either present when the call runs or it is not. - It does **not** outlive the answer; once `accept()` or `dismiss()` has run, the handle is spent and taking a new one fails because no dialog remains. - It does **not** tell the three dialog types apart for you, so a test expecting a `prompt` that meets a `confirm` finds out only when `sendKeys` fails. ## Read, assert, then answer The habit worth forming is to read the dialog before answering it. Calling `accept()` on sight is the equivalent of clicking OK without looking: a checkout that asks **Charge your card for 3 books?** and one that asks **Discard the items in your basket?** are answered by exactly the same line of code, and only `getText()` tells them apart. A test that asserts the message first turns the dialog into evidence; a test that accepts on reflex turns it into a silent behaviour change nobody will notice.
- What does accept() do to a prompt that has already had sendKeys() called on it?It submits the typed text as the value of the page's `prompt` call, exactly as pressing OK would. Calling `dismiss()` instead discards it and hands the page `null`, so the field's contents never reach the application no matter what was typed.
- Does switchTo().alert() change which frame or window the driver is pointed at?No. Unlike the frame and window targets on the same `switchTo()` surface, taking an `Alert` handle leaves the current browsing context untouched. After answering the dialog the next `findElement` searches exactly the context it would have searched before, so there is nothing to switch back to.
- What happens if you call sendKeys on a plain alert or confirm dialog?It fails rather than doing nothing. Only a `prompt` has an input field, so the remote end rejects the send-text command for the other two types. A test that expects a `prompt` and meets a `confirm` therefore discovers the mismatch at that call.
It is the till attendant stopping mid-transaction to ask whether to charge your card: nothing else at the counter moves until someone answers, and the answer given, not the question asked, decides whether the sale goes through.
- Tries to find the dialog with findElement or a CSS selector
- Calls sendKeys on a plain alert or confirm, which has no input field
- Thinks getText returns text typed into a prompt rather than its message
- Believes dismiss on a plain alert reports a cancellation the page can detect
- Says accept only confirms, forgetting it also submits a prompt's typed text