skip to content

Browser Context Control

Everything a Selenium test touches that is not an element: which document the driver is pointed at, and the browser state around it. Context bugs are why a correct locator finds nothing.

on this pageshow

explore

questions

24

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

In Selenium, which Chrome preferences make a download land in a directory your test picked, with no save prompt?

level: juniorimportance: must knowfreq 74%

basics

~20 s

Set the Chrome preference download.default_directory to an absolute path and download.prompt_for_download to false, passed as the prefs experimental option on ChromeOptions. The browser then writes the file into that folder on whichever machine runs the browser.

open as a page

In Selenium, what is the difference between driver.get(url) and driver.navigate().to(url)?

level: juniorimportance: must knowfreq 78%

basics

~10 s

Nothing functional separates them. Both send the same WebDriver Navigate To command and load the URL in the current tab. navigate() exists because the object it returns also carries back, forward and refresh.

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

A Selenium suite calls addCookie before navigating and every test throws InvalidCookieDomainException — why, and what is the fix?

level: seniorimportance: must knowfreq 70%

basics

~20 s

WebDriver can only set a cookie for the document the browser currently holds. A fresh session sits on a blank page with no host, so there is nothing for the cookie to belong to and addCookie rejects it. Navigate to the target origin first.

open as a page

A Selenium test switched into a course-enrolment wizard's payment iframe and now cannot find the wizard's Back button. Why?

level: seniorimportance: must knowfreq 68%

basics

~10 s

switchTo().frame() moves the whole session into that frame and it stays there. Every later command searches only the frame's document, so the wizard's Back button is unreachable until the test calls parentFrame() or defaultContent().

open as a page

In Selenium, why can navigate().refresh() after submitting an insurance-claim form create a duplicate claim?

level: seniorimportance: must knowfreq 52%

basics

~10 s

A reload repeats the request that produced the current document. If the confirmation page was rendered straight from the form's POST, refreshing sends that POST again and the server records a second claim.

open as a page

After driver.close() on a tab, a Selenium suite throws NoSuchWindowException on every later command. Why, and what is the fix?

level: seniorimportance: must knowfreq 57%

basics

~20 s

Closing a context never moves the driver's focus, so it still addresses a window that no longer exists and every command fails with no such window. Switch explicitly to a surviving handle immediately after the close.

open as a page

How do you keep Selenium's session-wide frame context correct across a deeply nested course-enrolment wizard?

level: principalimportance: must knowfreq 39%

basics

~20 s

Treat the frame context as one mutable pointer per session. Each helper should descend from the top document and restore it in a finally block, batch its work inside the frame, and never leave a failed test parked there.

open as a page

In Selenium's Java client, how do you set and read the browser window's size and position?

level: juniorimportance: should knowfreq 63%

basics

~10 s

Go through driver.manage().window(). Call setSize with a Dimension of width and height, and setPosition with a Point of x and y. Read them back with getSize and getPosition, which return the same two types.

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

In Selenium, which cookies does driver.manage().getCookies() actually return for the page currently loaded?

level: middleimportance: should knowfreq 55%

basics

~20 s

It returns the cookies associated with the address of the document the browser currently holds, with all their attributes. It is not the whole browser profile, and unlike a script read it also includes cookies marked HttpOnly.

open as a page

A Selenium test asserts on an exported CSV right after clicking Download and fails intermittently; why, and what fixes it?

level: middleimportance: should knowfreq 57%

basics

~20 s

WebDriver has no download-finished signal, so click returns while bytes are still arriving. Poll the download directory until the final filename exists and no partial file remains, Chrome writing .crdownload and Firefox .part while a transfer is in flight.

open as a page

In Selenium, how do the three switchTo().frame overloads locate a frame, and which exception does each raise?

level: middleimportance: should knowfreq 61%

basics

~20 s

An index counts the current document's frames in document order, a string is matched against a frame's name and then its id, and a WebElement is one you found yourself. All three throw NoSuchFrameException when the frame is absent.

open as a page

In Selenium, a portal link opens a second tab. How do you obtain that new tab's window handle?

level: middleimportance: should knowfreq 64%

basics

~20 s

Snapshot getWindowHandles() before the click, take the same set afterwards, and subtract the first from the second. The single handle left over is the new tab. Handles are opaque and unordered, so indexing into the set is unreliable.

open as a page

In Selenium, why does a headless run render a responsive page at a different layout than your headed run?

level: middleimportance: should knowfreq 58%

basics

~20 s

A headless browser has no desktop to size a window from, so it opens at a small fixed default - 800 by 600 in Chrome - and the page picks its narrow layout. Set the width explicitly at launch.

open as a page

Selenium's addCookie returned without throwing, yet getCookieNamed comes back null — what explains that?

level: seniorimportance: should knowfreq 45%

basics

~20 s

The driver handed the cookie to the browser, and the browser declined to keep it or stored it outside the current page's scope. An expiry in the past, a Secure flag on a non-secure page, or a path the page does not match all read back as nothing.

open as a page

Your Selenium test downloads a CSV while the browser runs on a Grid node; how do you get that file to the client?

level: seniorimportance: should knowfreq 44%

basics

~10 s

Request the se:downloadsEnabled capability so Selenium 4's Grid manages the session's download folder, then call getDownloadableFiles to list what arrived, downloadFile to copy one to a client path, and deleteDownloadableFiles to clear it.

open as a page

In Selenium, what is the difference between manage().window().maximize(), fullscreen() and minimize()?

level: juniorimportance: nice to knowfreq 36%

basics

~20 s

Maximize grows the window to fill the desktop's working area with the browser toolbars still showing. Fullscreen puts it in the browser's full-screen mode, hiding that chrome. Minimize hides the window from the display entirely.

open as a page

In Selenium 4, what does driver.switchTo().newWindow(WindowType.TAB) do, and how does WindowType.WINDOW differ?

level: juniorimportance: nice to knowfreq 28%

basics

~20 s

Selenium 4 creates a fresh, blank browsing context and switches the driver to it in one call, so no handle diffing is needed. WindowType.TAB asks for a tab in the current window; WindowType.WINDOW asks for a separate browser window.

open as a page

In Selenium, which Firefox preferences must be set together for a download to reach a folder you chose?

level: middleimportance: nice to knowfreq 31%

basics

~10 s

Firefox needs browser.download.folderList set to 2 so that browser.download.dir is honoured, plus browser.helperApps.neverAsk.saveToDisk listing the MIME types to save without asking. All of them go on FirefoxOptions with addPreference.

open as a page

In Selenium, what does driver.getCurrentUrl() return after a submitted claim form redirects to a confirmation page?

level: middleimportance: nice to knowfreq 41%

basics

~20 s

The address the tab is showing now, after every redirect has been followed, not the URL your test passed in. It is a live read from the browser, taken at the moment the call executes.

open as a page

A Selenium suite sets the window to 1280 wide, yet a min-width 1280px media query never matches. Why?

level: seniorimportance: nice to knowfreq 41%

basics

~20 s

Selenium sizes the whole browser window, not the page. Browser chrome and the vertical scrollbar come out of that number, so a 1280-wide window lays the page out in slightly less than 1280 CSS pixels and the query misses.

open as a page