skip to content

Opening and Closing Sessions

What really happens between constructing a driver object and quitting it: a process starts, options shape it, a session id comes back, and cleanup has to run. Leaks here bite every team.

on this pageshow

explore

questions

16

In Selenium 4, what actually happens when a Java test calls new ChromeDriver()?

level: juniorimportance: must knowfreq 85%

answer

  1. One line, several moving parts
  2. Something starts before the browser does
  3. A port on the loopback interface
  4. Then an HTTP request creates something
  5. The reply carries an identifier

basics

~20 s

Constructing ChromeDriver starts a local driver process, waits for it to listen on a free loopback port, then sends it a new-session request. The driver launches the browser and replies with a session id that every later command carries.

solid answer

~40 s

In Selenium 4, `new ChromeDriver()` starts a driver process as a child of the test process, waits until it is listening on a free loopback port, then sends it the new-session command with the capabilities requested. The driver launches the browser and replies with a session id; the constructor stores that id and returns, so an open browser window on a blank page already exists before `driver.get(...)` runs. Every later command is another HTTP request to that same port, addressed to that session id. `ChromeDriver`, `FirefoxDriver`, `EdgeDriver` and `SafariDriver` all behave this way and all extend `RemoteWebDriver`; the remote class skips the local process and talks to a URL instead.

code

java · 14 lines
java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class SubmitTalkTest {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://cfp.example.com/submit-talk");
            System.out.println(driver.getTitle());
        } finally {
            driver.quit();
        }
    }
}

go deeper

for a junior

Be ready to name, in order, what the constructor does: starts a driver process, waits for a bound port, sends a new-session request, receives a session id, and leaves an open browser window on a blank page.

for a middle

Explain that client and driver speak HTTP over a loopback port the driver chose, and that the browser is a third process that neither the test nor the driver runs inside. Say why the line blocks.

for a senior

Show that construction is treated as the slowest and most environment-dependent step of a run, and that a failure on this line is diagnosed as setup rather than chased through the test body.

for a principal

Own the resource arithmetic: every construction is a process, a bound port and a browser's memory footprint, and that unit is what a team's run capacity is planned around.

## The line under the microscope In Selenium 4 the statement `WebDriver driver = new ChromeDriver();` looks like an ordinary object allocation, and it is not one. By the time that constructor returns, a separate **operating-system process** is running on the test machine, it is listening on a TCP port, an HTTP request has crossed to it, a real browser window is open, and the test holds a **session id** that every later command will carry. A suite that fills in a conference talk-submission form usually spends more wall-clock time on that one line than on the navigation that follows it. ## The sequence, in order 1. The constructor starts a **driver process** — for Chrome, the `chromedriver` binary — as a child of the test process. 2. That process binds a **free port on the loopback interface** and begins serving HTTP there; the client polls that address until it answers, which is why the line blocks. 3. The client sends the **new session** command, `POST /session`, to that address, carrying the capabilities describing the browser it wants. 4. The driver launches the browser itself and waits until it is controllable. 5. The driver replies with a **session id** and the capabilities it actually granted; the client stores the id and the constructor returns. Only after step 5 can `driver.get("https://cfp.example.com/submit-talk")` do anything, and that call is simply the next HTTP request to the same port, addressed to the session id from step 4. ## What you are holding when it returns - A **live browser session** — a window already exists, on a blank page, before the test navigates anywhere. - A **session id**: an opaque string the driver chose, not the client, scoping every later command. - An object declared as `WebDriver` but actually a `ChromeDriver`, which extends `RemoteWebDriver` — the very class used to talk to a driver on another host. - A **child process**, plus a browser process, that stay alive until the session ends. ## The local classes and their remote counterpart | Constructor | What it starts on the test machine | Where the browser runs | |---|---|---| | `new ChromeDriver()` | a Chrome driver process on a loopback port | the test machine | | `new FirefoxDriver()` | a Firefox driver process on a loopback port | the test machine | | `new EdgeDriver()` | an Edge driver process on a loopback port | the test machine | | `new SafariDriver()` | the Safari driver process, macOS only | the test machine | | `new RemoteWebDriver(url, options)` | nothing — it opens an HTTP connection to the URL | wherever that URL answers | The four local classes differ only in which browser they manage; each is a `RemoteWebDriver` underneath, which is why the test code written on top of them is identical. ## Why the shape matters - **Construction is a setup step that can fail.** A test throwing on this line never reached an assertion; it is an environment failure, not a product defect. - **It is not free.** A process start, a port bind and a browser launch take seconds, not milliseconds, so the number of constructions in a run is a real cost. - **Nothing is in-process.** The test never calls into the browser; it sends HTTP to the driver, which drives the browser by its own means. That is why a debugger cannot step into a click. - **The order is fixed.** The port must answer before the new-session request can be sent, and the session must exist before any command can be addressed. ```java WebDriver driver = new ChromeDriver(); driver.get("https://cfp.example.com/submit-talk"); ``` The second line is not the beginning of the browser's life; it is already the second command of an established session. ## What the constructor does not do - It does not navigate. The session opens on a blank page; the talk-submission form is not loaded until it is asked for. - It does not hand back a half-built object. If the driver never answers on its port, or declines the session, the line throws instead of returning something unusable. - It does not give two browsers. One constructor call means one session and one browser to drive. ## Where candidates go wrong - Describing the constructor as merely creating an object, with the browser opening on the first `get`. - Believing the client library drives the browser directly, with no separate process between them. - Assuming the client invents the session id and tells the driver to use it. - Forgetting the loopback port entirely, which makes every later question about remote endpoints impossible to answer.

  • After the constructor returns, how does the test code actually reach the driver?
    Over HTTP to the loopback port the driver bound. Each API call on the driver object becomes a request to that address, addressed to the session id the driver returned, and the reply is parsed back into a Java value.
  • What is different if the test constructs FirefoxDriver instead?
    The shape is the same: a driver process, a bound port, a new-session request, a session id. Only the driver process and the browser differ. Both classes extend `RemoteWebDriver`, so test code declared as `WebDriver` needs no change at all.
  • Is a browser window open before the first get() call?
    Yes. The new-session reply means the browser is already launched and controllable, sitting on a blank page. `driver.get(...)` only navigates an existing session; it never creates one.

It is less like calling a method and more like hiring a switchboard operator: the operator has to be running and answering on their own line before you can ask them to open anything for you.

saying these in an interview costs you the question

  • Says the constructor only creates a Java object and opens nothing
  • Thinks the client library drives the browser directly, with no process between
  • Believes the browser opens only when get() is first called
  • Cannot say that the driver listens on a local HTTP port
  • Assumes the client library generates the session id itself
open as a page

In Selenium 4, where does a driver's session id come from and what uses it?

level: middleimportance: must knowfreq 62%

basics

~20 s

The remote end creates it. The client sends a new-session request, the driver opens a browser and replies with an opaque session id. The client stores it and addresses every later command to that id, one session per driver object.

open as a page

Nightly Selenium runs leave chromedriver processes alive on the build host between builds. How do you find and stop that?

level: seniorimportance: must knowfreq 57%

basics

~20 s

A driver service you build and start yourself is yours to stop. Orphans pile up when stop() is skipped on an exception path or the JVM is killed, so pair every start() with a finally, and add a host-level sweep for the kills.

open as a page

A Selenium driver constructor throws in CI — how do you tell which startup stage failed?

level: seniorimportance: must knowfreq 50%

basics

~20 s

Split it by what answered. A connection failure at the driver address means nothing was listening, so no session was requested. A session-not-created error means the endpoint answered and declined. A recorded session id means startup already finished.

open as a page

In Selenium, what is ChromeOptions for, and how do you apply it to a new Chrome session?

level: juniorimportance: should knowfreq 74%

basics

~10 s

ChromeOptions is Selenium's typed builder for how a Chrome session starts: launch switches, preferences, extensions and the browser binary. It takes effect only when you pass that instance to the ChromeDriver constructor.

open as a page

In Selenium, what is a ChromeDriverService and why does the Java client need one?

level: juniorimportance: should knowfreq 61%

basics

~10 s

A ChromeDriverService is Selenium's handle on the chromedriver executable. It builds the command line, starts that process, and knows the local HTTP address the Java client sends its WebDriver commands to.

open as a page

In Selenium, what is the difference between calling driver.close() and driver.quit()?

level: juniorimportance: should knowfreq 82%

basics

~20 s

close() shuts only the browser window the driver is focused on and leaves the session running. quit() ends the whole session: every window it owns closes, the browser exits, and the driver process is stopped.

open as a page

In Selenium 4, how do you run Chrome headless now that ChromeOptions.setHeadless() no longer exists?

level: middleimportance: should knowfreq 68%

basics

~10 s

Headless is a browser switch, not a Selenium setting. Build a ChromeOptions, call addArguments with --headless=new, and pass that object to the ChromeDriver constructor. Selenium 4 removed the setHeadless convenience toggle.

open as a page

In Selenium's ChromeOptions and FirefoxOptions, how do browser preferences differ from launch arguments?

level: middleimportance: should knowfreq 57%

basics

~20 s

A launch argument is a command-line switch handed to the browser process at startup; a preference is a setting written into the profile that session runs with. Chrome takes preferences as a map through setExperimentalOption; Firefox has addPreference.

open as a page

In Selenium, which port does ChromeDriverService listen on if you never call usingPort, and how do you pin it?

level: middleimportance: should knowfreq 52%

basics

~10 s

Selenium's driver-service builder picks a port that is free at build time, so every service gets a different one. Call usingPort(9515) to pin a fixed port, or usingAnyFreePort() to state the default choice explicitly.

open as a page

Why does a chromedriver started by Selenium refuse HTTP requests from another machine, and what changes that?

level: middleimportance: should knowfreq 34%

basics

~20 s

The driver executable listens on loopback and rejects non-local clients by default, because anyone who can reach it can drive a browser on that machine. ChromeDriver's --allowed-ips, and geckodriver's --host with --allow-hosts, open it deliberately.

open as a page

In Selenium, what profile does a Chrome session use by default, and what changes when ChromeOptions adds --user-data-dir?

level: seniorimportance: should knowfreq 46%

basics

~20 s

By default the driver creates a throwaway user-data directory per session, so every run starts with no cookies, extensions or history. Adding --user-data-dir points Chrome at a directory you keep, carrying state in and writing it back out.

open as a page

What changes when a Selenium suite swaps new ChromeDriver() for RemoteWebDriver against a URL?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Only construction changes. The remote form starts no process locally, takes a reachable URL plus capabilities naming the browser, and makes every command a network round-trip. The command set, the session id and the test code stay identical.

open as a page

A Selenium suite leaves chromedriver processes and temp profile directories on the CI agent - what causes that and how do you fix it?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Each leftover process is a session that was never deleted. In Selenium 4 only quit() sends Delete Session and stops the driver executable the client launched, so close-only teardown and killed runs leave both behind.

open as a page

On a long-lived shared runner, how far do you go beyond driver.quit() to stop Selenium sessions accumulating?

level: principalimportance: should knowfreq 36%

basics

~20 s

Make quit() unconditional first, then add one bounded backstop for the runs where it cannot execute: a scoped pre-run sweep, a disposable run environment, or moving browsers to a remote end that reaps its own abandoned sessions.

open as a page

In Selenium, what does a started ChromeDriverService's getUrl() return, and what is it used for?

level: juniorimportance: nice to knowfreq 26%

basics

~10 s

It returns the base HTTP address the driver process is listening on, such as http://localhost:9515. Use it to log the port, to probe the driver, or to point a RemoteWebDriver at that local driver.

open as a page