October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Use Java Event Listeners in Selenium

Use Selenium’s WebDriverListener with EventFiringDecorator to observe Java WebDriver calls, with practical guidance on callback scope, ordering, exceptions, and legacy examples.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In current Selenium Java code, implement WebDriverListener, pass it to EventFiringDecorator, and use the driver returned by decorate(originalDriver). Calls made through that decorated driver trigger listener callbacks for WebDriver operations and related objects such as elements and alerts.

Register a listener with EventFiringDecorator

This example logs a navigation before it happens and an element click after it completes. It follows Selenium’s documented API pattern; it is illustrative rather than a claim of locally executed testing.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.events.EventFiringDecorator;
import org.openqa.selenium.support.events.WebDriverListener;

public class ListenerExample {
  public static void main(String[] args) {
    WebDriver original = new FirefoxDriver();

    WebDriverListener listener = new WebDriverListener() {
      @Override
      public void beforeGet(WebDriver driver, String url) {
        System.out.println("Opening: " + url);
      }

      @Override
      public void afterClick(WebElement element) {
        System.out.println("Clicked an element");
      }
    };

    WebDriver driver = new EventFiringDecorator(listener).decorate(original);
    try {
      driver.get("https://www.selenium.dev/");
    } finally {
      driver.quit();
    }
  }
}

The essential detail is retaining and using the returned decorated driver. EventFiringDecorator wraps the original and returns an object implementing the same interfaces. Calls made directly through an unwrapped reference do not pass through that wrapper, so they will not invoke its listener callbacks. See the EventFiringDecorator Java API.

Choose callbacks for the events you need

Specific callbacks

Use callbacks such as beforeGet, afterClick, or afterGetText when you want a clear, targeted hook. An after callback can inspect a method’s returned value where the callback signature provides it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Generic callbacks

For wider instrumentation, implement generic callbacks such as beforeAnyWebElementCall or beforeAnyCall. A listener can combine generic and specific callbacks, but broad hooks may produce noisy logs; filter or format their output deliberately. The available callback methods and defaults are documented in WebDriverListener.

Callback order

When both generic and specific hooks apply, before callbacks run from broad to narrow: beforeAnyCall, then beforeAnyWebDriverCall, then beforeGet, for example. Corresponding after callbacks run in reverse order. Account for that ordering if multiple callbacks log, measure, or attach context to an operation.

Keep listener work safe and lightweight

Listener methods execute in the same thread as the WebDriver method being observed. Avoid blocking operations in callbacks: slow logging, network calls, or waits can delay the browser command itself. Keep callbacks short and move expensive work outside the command path when possible.

Exceptions thrown by listener code are suppressed by default. If failures inside the listener should fail the test or calling operation, override throwsExceptions() in the listener to return true. This changes how listener exceptions are handled; it does not make a failed WebDriver operation succeed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a decorator when you need to change behavior

Listeners are for observing calls and performing limited side effects. They are not a general way to prevent decorated methods from running or to change their arguments and return values. For substantial behavior changes, Selenium documents WebDriverDecorator as the appropriate direction. See the decorator API documentation for the distinction.

Update older event-listener examples

Older tutorials may register AbstractEventListener, EventFiringWebDriver, or WebDriverEventListener. Selenium’s migration guidance says those classes were removed and shows the replacement pattern: implement WebDriverListener, construct EventFiringDecorator, and decorate the driver. The migration article by Selenium contributor Oscar Devora was published on December 8, 2023: Java event-class removal and migration. For the Selenium version in your project, check its package documentation because APIs can change in later releases.

Or skip the browser setup

If your goal is a screenshot rather than observing Java WebDriver commands, ScreenshotNeo offers a screenshot API and MCP server. One GET request can return an image or PDF; it does not require a Selenium listener.

ScreenshotNeo API documentation

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
  • Cookie and consent banners, newsletter popups, and chat widgets are removed before capture; each cleanup step can be turned off.
  • Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing; responses identify the page verdict and billing status in headers.
  • An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients.
  • The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots.

Sign up for ScreenshotNeo’s free plan.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Frequently Asked Questions

Does a listener observe calls made through WebElements as well as the driver?

Yes. The decorator forwards events from WebDriver and derived objects, including WebElements and alerts.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can one listener implement both specific and generic callbacks?

Yes. The callbacks can be combined; generic before callbacks run before specific ones, while after callbacks run in reverse order.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.