Skip to content

[java] Implement accessibility snapshots (ADR 18205) #18346

Open

Description

@AutomatedTester

Part of #18345, the ADR 18205 tracker. This is the Java plan we will implement if people are happy with it. Please comment here before the PR goes up.

Python (#18307) and JavaScript (#18308) set the reference behaviour, listed in the tracker. This issue only covers how Java does it.

Public API (org.openqa.selenium)

This is a role interface, like TakesScreenshot. It is implemented by RemoteWebDriver and RemoteWebElement, so ChromeDriver, FirefoxDriver and the others get it without the Augmenter. Nothing is added to WebDriver or WebElement, so other implementations do not break.

public interface TakesAccessibilitySnapshot {

  /** Snapshot with the default options (pruned). */
  default AccessibilityNode getAccessibilitySnapshot() {
    return getAccessibilitySnapshot(AccessibilitySnapshotOptions.defaults());
  }

  /**
   * @throws StaleElementReferenceException if called on an element that is no longer attached
   */
  AccessibilityNode getAccessibilitySnapshot(AccessibilitySnapshotOptions options);
}

Options are an immutable value with withers, following ClientConfig. There is no setter-style builder, so a shared default instance can never be changed:

AccessibilitySnapshotOptions.defaults()            // interestingOnly = true
    .withInterestingOnly(false);

The node is a final class rather than a record, because we compile with --release 11. It is immutable, its collections are unmodifiable, and it has getters in the usual Selenium Java style:

public final class AccessibilityNode {
  public String getRole();                       // "text" for text leaves, "iframe" for frames
  public String getName();                       // "" when none
  public String getDescription();                // "" when none
  public Optional<String> getValue();            // textbox, searchbox, combobox, range
  public Optional<String> getUrl();              // links with an href
  public Map<String, Object> getStates();        // Boolean, Integer, or the String "mixed"; unmodifiable, ordered
  public Optional<WebElement> getElement();      // empty for text leaves and generated content
  public List<AccessibilityNode> getChildren();  // unmodifiable, [] for leaves
  public Stream<AccessibilityNode> stream();     // this node and its descendants, depth-first
  public String toText();                        // ADR §1 text form
  @Override public String toString();            // same as toText()
}

The optional fields use Optional instead of @Nullable because users read them in chains such as node.getElement().ifPresent(WebElement::click). stream() is an extra for Java. It is additive under the record's compatibility rule, and it covers the most common thing people will do with the tree:

TakesAccessibilitySnapshot snapshots = (TakesAccessibilitySnapshot) driver;
AccessibilityNode tree = snapshots.getAccessibilitySnapshot();
System.out.println(tree.toText());

tree.stream()
    .filter(n -> n.getRole().equals("button") && n.getName().equals("Submit"))
    .findFirst()
    .flatMap(AccessibilityNode::getElement)
    .ifPresent(WebElement::click);

AccessibilityNode form =
    ((TakesAccessibilitySnapshot) driver.findElement(By.id("login")))
        .getAccessibilitySnapshot(AccessibilitySnapshotOptions.defaults().withInterestingOnly(false));

Internals (org.openqa.selenium.remote, package-private)

  • AccessibilitySnapshotter is created lazily, one per RemoteWebDriver. RemoteWebElement delegates to its parent's instance.
  • BiDi path. Used when the webSocketUrl capability is present. Raw script.callFunction and browsingContext.getTree go through the driver's HasBiDi.getHandle(), wrapped in a small internal org.openqa.selenium.bidi.Module subclass. It does not use the deprecated getBiDi()/maybeGetBiDi() (ADR 17670) or the public bidi.module.Script, so taking a snapshot never warns about calls the user did not make.
  • Classic path. Uses executeScript with the atom source. Frames are reached with switchTo().frame(WebElement) and switchTo().parentFrame() in a try/finally, so the current context is restored even if a frame throws.
  • AccessibilityNode.fromWire(...) (package-private) builds the tree from the atom's JSON with org.openqa.selenium.json.Json. It maps element indexes to RemoteWebElement through the driver's element factory.
  • Frames that cannot be reached are logged at Level.FINE and become childless iframe nodes. Stale roots throw StaleElementReferenceException.
  • Atom: a copy_file of //javascript/atoms/fragments:accessibility-snapshot-wire-typescript.js into //java/src/org/openqa/selenium/remote resources. It is read once with Read.resourceAsString.

Decorators and wrappers

  • WebDriverDecorator / EventFiringDecorator proxy every interface the decorated object implements, so the new interface passes through. A test will check this, including that getElement() on a decorated driver returns a decorated element.
  • RemoteWebDriver on Grid needs nothing extra. It works with the Classic path whatever the node is, and with BiDi when the Grid gives a webSocketUrl.

Tests

  • java/test/org/openqa/selenium/AccessibilityNodeTest (small, no browser): checks toText() against every corpus .json/.txt pair, plus escaping and state order.
  • java/test/org/openqa/selenium/AccessibilitySnapshotTest (JupiterTestBase, @ParameterizedTest over index.json): for each page, pruned and unpruned, compares against the corpus, preferring .webkit files on Safari. It also ports the other cases from the Python suite: rooted at the switched frame, context unchanged, frames stitched, subtree inside a frame, stale and detached roots, usable element references, a snapshot is a copy.
  • Both paths need covering. testing/drivers/Browser.java always calls enableBiDi(), so the suite needs a Classic variant that leaves BiDi off (JavaScript did the equivalent in [js] Snapshot accessibility in Classic sessions too #18308 by honouring webSocketUrl: false). This follows the repo's preference for real browsers over mocks.

Not changing

Nothing is deprecated, because this replaces no existing call. There is no CDP path.


Generated by Claude Code

Activity

  1. added
    C-java
    I-enhancement
    on Nov 19, 2026
  2. Abdelrhman-Ellithy commented on Nov 22, 2026

    @Abdelrhman-Ellithy
    Contributor

    The Java design here looks very solid using TakesAccessibilitySnapshot as a role interface on RemoteWebDriver and RemoteWebElement keeps third-party WebDriver implementations unbroken, and making AccessibilityNode an immutable Java 11 final class with stream() plus AccessibilitySnapshotOptions withers fits ClientConfig and the rest of the Java bindings cleanly.

    One quick implementation note on the atom loading path: since #18324 just flagged Read.resourceAsString as caller-sensitive on the JPMS module path, we should make sure the atom resource placement/loading in org.openqa.selenium.remote plays cleanly with JPMS (or stays aligned with however #18324 lands).

    Is a core maintainer or you already implementing #18346, or is this open for a community PR matching the Python (#18307) and JS (#18308) reference behavior and common/src/web/accessibility/ corpus? If it's open and the API shape is settled, I'd be glad to take this on. @AutomatedTester

  3. AutomatedTester commented on Nov 23, 2026

    @AutomatedTester
    MemberAuthor

    No one is implementing this, this issue is to make sure that we can make this idiomatic. if there are other concerns let me know

  4. Abdelrhman-Ellithy commented on Nov 23, 2026

    @Abdelrhman-Ellithy
    Contributor

    Got it, thanks. A few things to confirm first, while reading through the spec:

    • AccessibilityNode is in org.openqa.selenium while AccessibilitySnapshotter is in org.openqa.selenium.remote, so a package-private AccessibilityNode.fromWire(...) won't be visible to the snapshotter. Either AccessibilityNode needs a public constructor (keeping wire parsing in AccessibilitySnapshotter) or the factory has to be structured differently.
    • On decorators, WebDriverDecorator will proxy TakesAccessibilitySnapshot fine, but it only auto-wraps direct WebElement return values. It won't wrap WebElements nested inside AccessibilityNode#getElement() or its children unless WebDriverDecorator explicitly handles AccessibilityNode (or there's a helper to remap elements on the tree).
    • org.openqa.selenium.json.Json decodes JSON numbers as Long in untyped maps, whereas getStates() documents Integer (Boolean, Integer, or "mixed"), so those will need explicit narrowing when parsing. Probably also worth putting @NullMarked on the new public classes to stay consistent with recent Java changes.

    ready to start on the PR once agreed with the API shape.

  5. pujagani commented on Nov 24, 2026

    @pujagani
    Contributor

    Overall, the shape of this looks good to me. Only part that feels off is the how the options are proposed. It differs from how we do options for rest of the code.
    My suggestion would be:

    public class AccessibilitySnapshotOptions {
      private boolean interestingOnly = true;
      public boolean isInterestingOnly() { ... }
      public AccessibilitySnapshotOptions setInterestingOnly(boolean interestingOnly) { ...; return this; }
    }
    
    // interface default method
    default AccessibilityNode getAccessibilitySnapshot() {
      return getAccessibilitySnapshot(new AccessibilitySnapshotOptions());
    }
    

    Apart from this and the comments raised above (which I think are more implementation details and can be handled accordingly), the shape of this ADR looks good.

  6. Abdelrhman-Ellithy commented on Nov 24, 2026

    @Abdelrhman-Ellithy
    Contributor

    Makes total sense, using new AccessibilitySnapshotOptions() with fluent setInterestingOnly(...) matches PrintOptions and the rest of the Java bindings ...much better.
    I'll go ahead and start working on the PR with that options shape and the implementation details above.

  7. pujagani commented on Nov 24, 2026

    @pujagani
    Contributor

    I would recommend waiting until this ADR is approved then doing the work and also I believe a part of work was done by David Burns as well, so might be good to use that and build on top of it.

  8. Abdelrhman-Ellithy commented on Nov 24, 2026

    @Abdelrhman-Ellithy
    Contributor

    okay, I'll hold off until ADR #18205 is approved. Once it's merged I'll look at David's earlier work and build on top of it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-javaI-enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions