skip to content

Native Dialog Handling

A script alert, confirm or prompt blocks the page until it is answered, and the driver reaches it through its own switch. Interviewers use it to test what 'the page is blocked' really means.

on this pageshow

explore

questions

3

In Selenium, how do you read a JavaScript confirm dialog's text and then accept or cancel it?

level: juniorimportance: must knowfreq 78%

answer

  1. It is a switch, not a find
  2. One handle object, four methods
  3. OK versus Cancel, and what returns
  4. switchTo().alert() gives you an Alert
  5. getText, accept, dismiss, sendKeys

basics

~10 s

Take 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 s

A 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 lines
java
driver.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

for a junior

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.

for a middle

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.

for a senior

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.

for a principal

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.

saying these in an interview costs you the question

  • 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
open as a page

A Selenium test fails with UnhandledAlertException and the confirm dialog is gone by the time you look. Why?

level: seniorimportance: must knowfreq 52%

basics

~10 s

Selenium 4 sessions default to the dismiss and notify prompt handler, so the remote end dismissed the dialog and then failed that command with UnhandledAlertException. Nothing lost the dialog; the default answered it.

open as a page

In Selenium, which commands still work while a JavaScript alert is open, and which fail?

level: middleimportance: should knowfreq 44%

basics

~20 s

Only the four alert commands reached through driver.switchTo().alert() still work: getText, accept, dismiss and sendKeys. Every other command first checks for an open prompt, so it answers or reports the dialog instead of doing its job.

open as a page