Skip to content

WebDriver (Selenium)

Run Selenium and Selenide tests on Holtdroid devices — Chrome, Holtdroid WebView or any app's WebView — with DevTools, VPN locations, bad networks, DNS, connections, recordings and test markers.

Holtdroid speaks the W3C WebDriver protocol at /wd/hub, the way Selenium Grid, Selenoid or a cloud device farm does. A test suite that already uses RemoteWebDriver gets an Android device by changing its hub URL: each WebDriver session launches a device, drives its browser or WebView through chromedriver inside the session, and stops the device on quit.

On top of plain WebDriver a test can:

  • use Selenium DevTools (getDevTools()) as with a local Chrome;
  • start in a VPN location and switch it mid-test;
  • emulate a bad network for the whole device, from a slow link to a subway ride;
  • read the device’s DNS queries and connections, and rewrite DNS answers;
  • change device settings (theme, language, time zone, GPS…);
  • watch the run live in the portal, keep a recording of it, share it by link and pin markers on it when a test starts, fails or passes.
  • The server needs webdriver.enabled: true (configuration) and the users sign-in mode.
  • Tests sign in with an access token with the webdriver scope: under Account and passkeys → Access tokens, create one and keep it in your CI secrets (access tokens). A dedicated account for CI, with a device limit that covers the suite’s parallelism, keeps test devices apart from people’s.
  • Starting a device takes about half a minute, much longer than a desktop browser. Give the client a read timeout of a few minutes; launches beyond the free devices wait in line within webdriver.startTimeout (5 minutes by default).
var options = new ChromeOptions();
options.setCapability("holtdroid:options", Map.of("build", "stable", "location", "pl"));
var driver = RemoteWebDriver.builder()
.oneOf(options)
.config(ClientConfig.defaultConfig()
.baseUrl(new URL("https://android.example.com/wd/hub"))
.authenticateAs(new UsernameAndPassword("ci", System.getenv("HOLTDROID_TOKEN")))
.readTimeout(Duration.ofMinutes(5)))
.build();
driver.get("https://example.com/");
System.out.println(driver.getTitle());
driver.quit(); // stops the device

The token is the password of HTTP Basic, with any user name; a plain Authorization: Bearer header works as well. Avoid writing the token into the hub URL itself: clients tend to log it.

The same with curl:

Terminal window
H=https://android.example.com/wd/hub
curl -u "ci:$HOLTDROID_TOKEN" -d '{"capabilities":{"alwaysMatch":{"browserName":"chrome"}}}' $H/session

holtdroid:options.target chooses what the test drives.

target What starts
chrome (default) A Chromium build; the test drives the browser. build picks it: a milestone (158), a channel (stable, beta) or latest; stable by default
webview Holtdroid WebView opens url with a preset (browse, unlocked, kiosk, …) and webviewSettings (its adb settings); the test drives that WebView. webview picks the WebView build to install
app Any app from a source, given by source and artifact; the test drives its WebView. url opens a deep link in the app, process names the process when the WebView isn’t in the main one
native Any app from a source (source, artifact); the test drives the app’s native Android UI through appium-uiautomator2-server (compatible with io.appium:java-client and selenide-appium). Picked automatically when appium:automationName is UiAutomator2 and target is omitted; url opens a deep link in the app

For app the app must show a WebView page within a minute of starting. Apps that open with a native screen need a deep link (url) that leads to a page; the APK itself is never modified, its WebViews are made debuggable at runtime.

For native, standard Appium clients (AndroidDriver, UiAutomator2Options, selenide-appium) talk to /wd/hub without a custom client library. waitForIdleTimeout and waitForSelectorTimeout default to 0 so animated splash screens don’t block lookups (appium:settings[…] capabilities or POST /appium/settings override them); id, accessibility id, xpath, class name, -android uiautomator and Selenium CSS #id selectors, implicit waits, gestures, NATIVE_APP ↔ WEBVIEW_<process> context switching (getContextHandles() / context(...)) and common mobile:* commands are supported:

var options = new UiAutomator2Options()
.setCapability("holtdroid:options", Map.of(
"target", "native",
"source", "slack",
"artifact", artifactId,
"location", "pl"
));
var driver = new AndroidDriver(
ClientConfig.defaultConfig()
.baseUrl(new URL("https://android.example.com/wd/hub"))
.authenticateAs(new UsernameAndPassword("ci", System.getenv("HOLTDROID_TOKEN")))
.readTimeout(Duration.ofMinutes(5)),
options
);

Use the session’s Inspector tab to capture screen snapshots, verify selectors and copy ready AppiumBy / Selenide snippets (with a full Spring Boot + JUnit 5 login and navigation example).

Every key is optional.

Key What
target chrome, webview, app or native, see above
build chrome only: milestone, channel or latest
source, artifact A build of your own: the source’s name and the artifact id as the portal’s API lists it
url, preset, webviewSettings webview: the first page and how Holtdroid WebView is set up; app and native: url is a deep link
process app: the process with the WebView, such as com.example:web
webview A WebView build from the portal’s catalog to install before the test
provider, android, screen Where and on what the device runs, as in the launch dialog
location The VPN location the device starts in
network Emulated network conditions from the start: a network such as lte-good or a scenario such as subway (network conditions)
region {"region": "…", "server": "…", "backends": ["api.example.com"]}: a region’s paths to CDNs and servers on top of network
device Any device setting before the first page loads: {"darkMode": true, "locales": ["de-DE"], "timeZone": "Europe/Berlin"}
dns DNS rewrites from the start, as on the DNS tab: {"ttlMode": "keep", "rewrites": [{"pattern": "*.example.com", "kind": "address", "addresses": ["10.0.0.5"], "ttl": 60, "enabled": true}]}
darkMode, record As in the launch dialog; record: true asks for a recording where recordings are optional
inspectHttps true decrypts HTTPS in the session’s MITM proxy from the start
name A label for the run: written to the audit log and pinned as the recording’s first marker
scripts Scripts applied from the app’s start: saved ones [{"id": "…", "params": {"HOST": "…"}}], or inline Frida code {"source": "…"}, traffic rules {"rules": […]} or DNS rewrites {"dns": […]}
queue true by default: wait for a free device within webdriver.startTimeout instead of failing

The rest of the capabilities (goog:chromeOptions arguments, timeouts, …) go to chromedriver unchanged.

The new session’s capabilities carry three more entries:

Capability What
holtdroid:session {provider, id, url}; url opens the session in the portal, where the screen can be watched live
holtdroid:recording {id, url} when the session is recorded; url opens the recording in the portal
se:cdp A link to the browser’s DevTools, signed for this session (see below)

Selenium DevTools work as with a local Chrome. se:cdp is signed for the session, so Selenium connects to it without the token:

var devTools = ((HasDevTools) new Augmenter().augment(driver)).getDevTools();
devTools.createSession();
devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()));
devTools.addListener(Network.responseReceived(), r -> System.out.println(r.getResponse().getUrl()));

Network.emulateNetworkConditions through DevTools slows one browser; the network option and the device extension below shape the whole device’s traffic, WebSockets and video included.

Under /wd/hub/session/{sessionId}/holtdroid/ a test reaches the device with the same token. The calls take and return plain JSON (not wrapped in value); an error is {"status": …, "detail": "…"}.

Call What
GET network VPN location, external IP and country
PUT network/location {"location": "pl"} Switch the VPN location
GET, PATCH device Device settings. {"networkProfile": "subway"} emulates a bad network, "full" turns it off; {"networkRegion": {…}} a region
GET, PUT dns DNS rewrites and the TTL limit
POST dns/flush Clear Android’s DNS cache
GET dns/log?after={id} DNS queries newer than a cursor: {"items": […], "last": 42}; pass last as the next after
GET connections?since={RFC 3339 time} Connections open now or closed since then: host, address, port, VPN location, CDN edge, bytes; addresses says where each server is
GET screenshot The whole screen as PNG, system dialogs included
GET ui The native views on the screen
GET, POST clipboard The device’s clipboard, {"text": "…"}
POST markers {"kind": "start", "label": "…"} A marker on the recording; the answer has links that open the recording at it, see below
POST app/clear-data, app/clear-cache, app/clear-webview, app/restart, app/reinstall Clear the app’s data, cache or WebView state, restart or reinstall it; the WebDriver session stays open, see below
GET recording, POST recording {"share": true} The session’s recording: {active, id, url, share}; the POST makes a public link

DNS and connections need the session’s VPN sidecar. A typical check of what the app talked to:

Terminal window
X=https://android.example.com/wd/hub/session/$SESSION_ID/holtdroid
CURSOR=$(curl -s -u "ci:$HOLTDROID_TOKEN" "$X/dns/log" | jq .last)
SINCE=$(date -u +%Y-%m-%dT%H:%M:%SZ)
# … the test logs in …
curl -s -u "ci:$HOLTDROID_TOKEN" "$X/dns/log?after=$CURSOR" | jq -r '.items[].name'
curl -s -u "ci:$HOLTDROID_TOKEN" "$X/connections?since=$SINCE" | jq -r '.items[] | "\(.host) \(.outbound)"'

Where the server records sessions, a WebDriver session is recorded like any other: the screen, logcat, DevTools traffic, DNS and connections on one timeline. The recording’s link comes back in holtdroid:recording and from GET recording; POST recording {"share": true} adds a link that opens it without signing in, for a bug report or a CI summary.

Markers pin moments on that timeline. kind gives them their icon in the player; the label holds up to 120 characters.

kind Icon For
start flag a test starts, with its name
pass check it passed
fail bug it failed, with the assertion’s message
skip alert it was skipped or aborted
end pin it ended, when pass or fail doesn’t fit
note star anything else worth coming back to

The answer to POST markers links straight to that moment:

{
"recording": "20261201T101500Z-…",
"marker": { "id": "b3556e5f", "t": 84200, "label": "CheckoutTest.paysInPoland: expected PLN", "icon": "bug" },
"url": "https://android.example.com/recordings/20261201T101500Z-…#t=84.2&marker=b3556e5f",
"share": "https://android.example.com/r/a592cd8e…#t=84.2&marker=b3556e5f"
}

The player opens at the marker and highlights it on the timeline. url needs a portal account; share is there once the recording is shared (POST recording {"share": true}) and opens for anyone with the link, which suits a test dashboard. Put the failure marker’s link into the test report and a failed test is one click away from the moment it failed.

A recording keeps up to 200 markers.

A device takes about half a minute to start, so a test class (or a whole suite) can share one WebDriver session instead of starting a device per test:

  • keep one driver open across the class and quit it after the last test;
  • give each test a clean app with POST app/clear-data;
  • bracket each test with a start marker and a pass or fail marker, so the recording reads as a list of tests.

app/clear-data stops the app, clears its data (pm clear) and starts it again under the same instrumentation as at launch, so DevTools keep working. app/clear-cache empties only its cache and compiled code (needs a device with root), app/clear-webview empties app_webview/ and cache while keeping app preferences and login state (needs root), app/restart starts it cold and app/reinstall installs the build again. Each waits until the app is back and reattaches the WebDriver session to it under the same session id: Chrome is started again by chromedriver, Holtdroid WebView opens its first page again and an app’s WebView is waited for. Pages opened before are gone, so call it before the test opens its first page. A Selenium DevTools connection opened before has to be opened again. The same actions are on the session page’s App card, and for scripts at POST /s/{provider}/{id}/v1/app/{action} with an api-scoped token, where the app restarts but no WebDriver session is touched.

For a browser that should keep its app but lose a test’s traces, the lighter reset is driver.manage().deleteAllCookies(), clearing localStorage and sessionStorage, or DevTools’ Storage.clearDataForOrigin.

A session lives at most as long as the account’s session limit allows and is stopped after the idle timeout; every WebDriver command and extension call counts as activity.

The example keeps one device per test class, gives each test a clean app, marks each test on the recording and puts links to the test’s start and to its failure into an Allure report. It needs Selenide 7, Selenium 4, JUnit 5 and Allure; nothing else.

A Selenide driver provider that opens Holtdroid sessions:

public class HoltdroidDriverProvider implements WebDriverProvider {
static final String HUB = System.getenv().getOrDefault("HOLTDROID_HUB", "https://android.example.com/wd/hub");
static final String TOKEN = System.getenv("HOLTDROID_TOKEN");
@Override
public WebDriver createDriver(Capabilities capabilities) {
var options = new ChromeOptions().merge(capabilities);
options.setCapability("holtdroid:options", Map.of(
"target", "chrome",
"build", "stable",
"location", System.getenv().getOrDefault("HOLTDROID_LOCATION", ""),
"record", true,
"name", System.getProperty("holtdroid.name", "autotests")));
try {
return RemoteWebDriver.builder()
.oneOf(options)
.config(ClientConfig.defaultConfig()
.baseUrl(new URL(HUB))
.authenticateAs(new UsernameAndPassword("ci", TOKEN))
.readTimeout(Duration.ofMinutes(5)))
.build();
} catch (MalformedURLException e) {
throw new IllegalStateException(e);
}
}
}

A small client for the extensions:

public final class Holtdroid {
private static final HttpClient HTTP = HttpClient.newHttpClient();
private static final String AUTH = "Basic " + Base64.getEncoder()
.encodeToString(("ci:" + HoltdroidDriverProvider.TOKEN).getBytes(StandardCharsets.UTF_8));
private static final Pattern URL = Pattern.compile("\"url\":\"([^\"]+)\"");
private static final Pattern SHARE = Pattern.compile("\"share\":\"([^\"]+)\"");
public static String call(String method, String path, String json) {
var id = ((RemoteWebDriver) WebDriverRunner.getWebDriver()).getSessionId();
var request = HttpRequest.newBuilder(URI.create(HoltdroidDriverProvider.HUB + "/session/" + id + "/holtdroid/" + path))
.header("Authorization", AUTH)
.header("Content-Type", "application/json")
.timeout(Duration.ofMinutes(3))
.method(method, json == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(json))
.build();
try {
return HTTP.send(request, HttpResponse.BodyHandlers.ofString()).body();
} catch (IOException | InterruptedException e) {
throw new IllegalStateException(e);
}
}
/** Pins a marker now and returns the link that opens the recording at it (the public one once shared). */
public static String marker(String kind, String label) {
var answer = call("POST", "markers", "{\"kind\":\"" + kind + "\",\"label\":" + quote(label) + "}");
var share = SHARE.matcher(answer);
if (share.find()) return share.group(1);
var url = URL.matcher(answer);
return url.find() ? url.group(1) : null;
}
/** Clears the app's data and starts it again; the WebDriver session stays open. */
public static void clearApp() {
call("POST", "app/clear-data", null);
}
/** Makes the recording viewable without signing in, so marker links open from any dashboard. */
public static void shareRecording() {
call("POST", "recording", "{\"share\":true}");
}
public static void location(String location) {
call("PUT", "network/location", "{\"location\":" + quote(location) + "}");
}
private static String quote(String s) {
return "\"" + (s == null ? "" : s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", " ")) + "\"";
}
}

A JUnit 5 extension that marks every test and links the recording:

public class HoltdroidMarkers implements BeforeAllCallback, BeforeEachCallback, TestWatcher, AfterAllCallback {
@Override
public void beforeAll(ExtensionContext context) {
WebDriverRunner.getAndCheckWebDriver();
Holtdroid.shareRecording();
}
@Override
public void beforeEach(ExtensionContext context) {
Holtdroid.clearApp();
var start = Holtdroid.marker("start", testName(context));
if (start != null) {
Allure.link("Recording: test start", start);
}
}
@Override
public void testSuccessful(ExtensionContext context) {
Holtdroid.marker("pass", testName(context));
}
@Override
public void testFailed(ExtensionContext context, Throwable cause) {
var failure = Holtdroid.marker("fail", testName(context) + ": " + cause.getMessage());
if (failure != null) {
Allure.link("Recording: failure", failure);
Allure.addAttachment("Holtdroid recording", "text/uri-list", failure);
System.out.println("Holtdroid recording at the failure: " + failure);
}
}
@Override
public void testAborted(ExtensionContext context, Throwable cause) {
Holtdroid.marker("skip", testName(context));
}
@Override
public void afterAll(ExtensionContext context) {
Selenide.closeWebDriver(); // quit: the device stops
}
private static String testName(ExtensionContext context) {
return context.getRequiredTestClass().getSimpleName() + "." + context.getDisplayName();
}
}

And a test class:

@ExtendWith(HoltdroidMarkers.class)
class CheckoutTest {
@BeforeAll
static void setUp() {
Configuration.browser = HoltdroidDriverProvider.class.getName();
Configuration.timeout = 10_000;
}
@Test
void paysInPoland() {
Holtdroid.location("pl");
open("https://shop.example.com/");
$("#pay").click();
$(".receipt").shouldHave(text("PLN"));
}
@Test
void paysOnASlowNetwork() {
Holtdroid.call("PATCH", "device", "{\"networkProfile\":\"gprs\"}");
open("https://shop.example.com/");
$("#pay").click();
$(".receipt").shouldBe(visible);
}
}

TestWatcher runs after the test’s @AfterEach, while the driver is still open, so the result marker lands right after the test. In the report a failed test carries Recording: failure, a link that opens the player at the failure, also as a text/uri-list attachment and in the console output for runners without Allure. The recording is shared once per class so the links open from a dashboard without a portal account; drop shareRecording() to keep them for signed-in people only. With JUnit’s parallel execution each thread keeps its own driver and so its own device; the account’s device limit caps how many run at once.

Cross-target & hybrid app testing (chrome + native WebView)

Section titled “Cross-target & hybrid app testing (chrome + native WebView)”

Many teams test the same web feature both in mobile Chromium (target: chrome) and embedded inside a native Android container app (target: native), reusing one device across tests without rebuilding the APK.

Resolving the latest APK build and compatible WebView

Section titled “Resolving the latest APK build and compatible WebView”

Instead of hardcoding artifact IDs in tests, resolve them dynamically from the portal API using the api-scoped token before opening /wd/hub/session:

  • GET /api/v1/artifacts — filter by source and build prefix or exact version, picking the newest uploadedAt.
  • GET /api/v1/providers — inspect the target provider’s abis and webviewPackages.
  • GET /api/v1/webviews — match the requested milestone (e.g. 159) or channel (stable) whose abis fit the provider, then pass its id in holtdroid:options.webview.
  • If running against custom test environments on Chromium, add "--disable-features=HttpsUpgrades" to goog:chromeOptions.args so test hosts are not upgraded unexpectedly.

Preserving app login across tests with app/clear-webview

Section titled “Preserving app login across tests with app/clear-webview”

When testing web flows inside an authenticated native app, wiping the whole app with app/clear-data forces every test to repeat login and onboarding. Use app/clear-webview between tests instead: it clears only app_webview/, cache/ and code_cache/ and restarts the app while keeping shared_prefs/ and databases/ (the app’s auth session) intact:

// Called from BeforeEach when reusing the same native device across tests
Holtdroid.call("POST", "app/clear-webview", null);

A robust pattern is to sign in once when a fresh session starts, verify the signed-in account explicitly before any feature test runs (so auth issues fail the precondition rather than masking feature assertions), and on subsequent reused tests check that the authenticated marker is still present without logging in again.

Injecting a test URL via Frida and switching to WEBVIEW_*

Section titled “Injecting a test URL via Frida and switching to WEBVIEW_*”

If a native screen opens an arbitrary web URL when tapping a tile or card and deep links are unavailable, install a Frida hook over the agent Scripts API right before opening the section (POST /s/{provider}/{id}/v1/scripts/run):

Java.perform(function () {
var WebView = Java.use("android.webkit.WebView")
try {
WebView.setWebContentsDebuggingEnabled(true)
} catch (e) {}
var oneArg = WebView.loadUrl.overload("java.lang.String")
oneArg.implementation = function (url) {
if (url && /^https?:/i.test(url) && typeof params !== "undefined" && params && params.WEBVIEW_URL) {
return oneArg.call(this, params.WEBVIEW_URL)
}
return oneArg.call(this, url)
}
var twoArg = WebView.loadUrl.overload("java.lang.String", "java.util.Map")
twoArg.implementation = function (url, headers) {
if (url && /^https?:/i.test(url) && typeof params !== "undefined" && params && params.WEBVIEW_URL) {
return twoArg.call(this, params.WEBVIEW_URL, headers)
}
return twoArg.call(this, url, headers)
}
})

Hook both loadUrl(String) and loadUrl(String, Map) overloads: Android apps vary in which overload they call when opening an embedded view. Pass keep: false with params: {"WEBVIEW_URL": targetUrl} so each reused test injects its own fresh session URL after app/clear-webview.

When browsing a list or grid to open the WebView (for example, looking for cards that offer a Demo / Free play mode without logging in):

  • Dismiss promo popups or unsupported bottom sheets cleanly with driver.navigate().back().
  • Scroll Jetpack Compose or RecyclerView lists with mobile: scrollGesture (area, direction: "down", percent: 0.8) and track visited card labels so each card is tried once.

Once the WebView opens, plain Selenium RemoteWebDriver works without switching to an Appium-specific client by calling /contexts and /context:

// 1. Poll GET /wd/hub/session/{sid}/contexts until a "WEBVIEW_..." handle appears
String webViewContext = pollForWebViewContext(sessionId);
// 2. Switch context with POST /wd/hub/session/{sid}/context {"name": webViewContext}
Holtdroid.switchContext(sessionId, webViewContext);
// 3. Run standard Selenide / Selenium web assertions inside the app's WebView
$(".balance").shouldHave(text("100.00"));
assertThat(WebDriverRunner.getWebDriver().getTitle()).isNotBlank();
// 4. Switch back to native UI when needed
Holtdroid.switchContext(sessionId, "NATIVE_APP");

If a test also needs to verify native API calls made before opening the WebView, start the session with "inspectHttps": true in holtdroid:options and query GET /s/{provider}/{id}/v1/mitm/flows.

What you see Why
401 on /wd/hub No token, a revoked or expired one, or one without the webdriver scope (403)
session not created … no free slot Every device is busy and queue is off, or the wait passed webdriver.startTimeout
session not created … unable to discover open pages app: the app showed no WebView page; open one with a deep link in url
invalid session id after a while The session was stopped: quit, the idle timeout, the session limit, or someone stopped it in the portal
400 from dns/log or connections The session runs without a VPN sidecar