or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

events.mdindex.mdjavascript.mdlogging.mdnetwork.mdtargets.md

network.mddocs/

0

# Network Management

1

2

Network traffic monitoring, request interception, authentication handling, and response manipulation for comprehensive network control. Enables advanced testing scenarios including API mocking, authentication testing, and performance monitoring.

3

4

## Core Imports

5

6

```java

7

import org.openqa.selenium.devtools.v99.V99Network;

8

import org.openqa.selenium.devtools.DevTools;

9

import org.openqa.selenium.devtools.Command;

10

import org.openqa.selenium.devtools.Event;

11

import org.openqa.selenium.remote.http.HttpRequest;

12

import org.openqa.selenium.remote.http.HttpResponse;

13

import org.openqa.selenium.remote.http.Filter;

14

import org.openqa.selenium.UsernameAndPassword;

15

import org.openqa.selenium.Credentials;

16

import java.util.function.Predicate;

17

import java.util.function.Supplier;

18

import java.net.URI;

19

```

20

21

## Capabilities

22

23

### Network Handler

24

25

Creates a network operations handler for Chrome DevTools Protocol v99.

26

27

```java { .api }

28

/**

29

* Creates network operations handler for CDP v99

30

* @param devTools - DevTools client instance

31

*/

32

public V99Network(DevTools devTools);

33

```

34

35

### User Agent Override

36

37

Override the browser's user agent string for testing different client configurations.

38

39

```java { .api }

40

/**

41

* Set user agent override using string

42

* @param userAgent - User agent string

43

*/

44

public void setUserAgent(String userAgent);

45

46

/**

47

* Set user agent override using configuration object

48

* @param userAgent - User agent configuration

49

*/

50

public void setUserAgent(UserAgent userAgent);

51

52

/**

53

* Override browser user agent string (internal)

54

* @param userAgent - User agent configuration

55

* @return Command to set user agent override

56

*/

57

protected Command<Void> setUserAgentOverride(UserAgent userAgent);

58

59

/**

60

* User agent configuration

61

*/

62

public class UserAgent {

63

public UserAgent(String userAgent);

64

public String userAgent(); // User agent string

65

66

public UserAgent acceptLanguage(String acceptLanguage);

67

public Optional<String> acceptLanguage(); // Accept-Language header value

68

69

public UserAgent platform(String platform);

70

public Optional<String> platform(); // Platform identifier

71

}

72

```

73

74

### Network Caching

75

76

Control browser network cache behavior for testing scenarios.

77

78

```java { .api }

79

/**

80

* Enable browser network caching

81

* @return Command to enable caching

82

*/

83

protected Command<Void> enableNetworkCaching();

84

85

/**

86

* Disable browser network caching

87

* @return Command to disable caching

88

*/

89

protected Command<Void> disableNetworkCaching();

90

```

91

92

### Authentication Management

93

94

Manage HTTP authentication for different URI patterns.

95

96

```java { .api }

97

/**

98

* Add authentication handler for matching URIs

99

* @param whenThisMatches - Predicate to match URIs needing authentication

100

* @param useTheseCredentials - Supplier providing credentials for matched URIs

101

*/

102

public void addAuthHandler(Predicate<URI> whenThisMatches, Supplier<Credentials> useTheseCredentials);

103

104

/**

105

* Disable network interception and clear authentication handlers

106

*/

107

public void disable();

108

```

109

110

### Request Filtering and Interception

111

112

Configure custom request/response filtering and traffic interception.

113

114

```java { .api }

115

/**

116

* Reset network filter to default (no filtering)

117

*/

118

public void resetNetworkFilter();

119

120

/**

121

* Intercept all network traffic with custom filter

122

* @param filter - HTTP filter to process requests/responses

123

*/

124

public void interceptTrafficWith(Filter filter);

125

126

/**

127

* Prepare the network domain for traffic interception

128

*/

129

public void prepareToInterceptTraffic();

130

```

131

132

### Low-level Request Interception

133

134

Enable and disable request interception for monitoring and modifying network traffic.

135

136

```java { .api }

137

/**

138

* Enable request interception for all URL patterns

139

* @return Command to enable fetch interception

140

*/

141

protected Command<Void> enableFetchForAllPatterns();

142

143

/**

144

* Disable request interception

145

* @return Command to disable fetch interception

146

*/

147

protected Command<Void> disableFetch();

148

149

/**

150

* Get event for paused requests during interception

151

* @return Event handler for paused requests

152

*/

153

public Event<RequestPaused> requestPausedEvent();

154

```

155

156

### Authentication Handling

157

158

Handle HTTP authentication challenges during request interception.

159

160

```java { .api }

161

/**

162

* Get event for authentication required scenarios

163

* @return Event handler for auth challenges

164

*/

165

protected Event<AuthRequired> authRequiredEvent();

166

167

/**

168

* Extract origin URL from authentication challenge

169

* @param authRequired - Authentication challenge event

170

* @return Origin URL requiring authentication

171

*/

172

protected String getUriFrom(AuthRequired authRequired);

173

174

/**

175

* Continue request with authentication credentials

176

* @param authRequired - Authentication challenge event

177

* @param credentials - Username and password

178

* @return Command to provide credentials

179

*/

180

protected Command<Void> continueWithAuth(AuthRequired authRequired, UsernameAndPassword credentials);

181

182

/**

183

* Cancel authentication request

184

* @param authRequired - Authentication challenge event

185

* @return Command to cancel authentication

186

*/

187

protected Command<Void> cancelAuth(AuthRequired authRequired);

188

```

189

190

### Request and Response Manipulation

191

192

Modify or fulfill intercepted requests and responses.

193

194

```java { .api }

195

/**

196

* Convert paused request to Selenium HTTP objects

197

* @param pausedReq - Intercepted request data

198

* @return Either HTTP request or response object

199

*/

200

public Either<HttpRequest, HttpResponse> createSeMessages(RequestPaused pausedReq);

201

202

/**

203

* Extract request ID from paused request

204

* @param pausedReq - Paused request event

205

* @return Request ID string

206

*/

207

protected String getRequestId(RequestPaused pausedReq);

208

209

/**

210

* Continue request without modifications

211

* @param pausedRequest - Paused request to continue

212

* @return Command to continue unchanged

213

*/

214

protected Command<Void> continueWithoutModification(RequestPaused pausedRequest);

215

216

/**

217

* Continue request with modifications

218

* @param pausedReq - Paused request to modify

219

* @param req - Modified HTTP request

220

* @return Command to continue with changes

221

*/

222

protected Command<Void> continueRequest(RequestPaused pausedReq, HttpRequest req);

223

224

/**

225

* Fulfill request with custom response

226

* @param pausedReq - Paused request to fulfill

227

* @param res - Custom HTTP response

228

* @return Command to fulfill with custom response

229

*/

230

protected Command<Void> fulfillRequest(RequestPaused pausedReq, HttpResponse res);

231

```

232

233

## Protocol Types

234

235

### Authentication Types

236

237

```java { .api }

238

/**

239

* Authentication challenge event data

240

*/

241

public class AuthRequired {

242

/**

243

* Get request ID that triggered auth challenge

244

* @return Request ID

245

*/

246

public RequestId getRequestId();

247

248

/**

249

* Get authentication challenge details

250

* @return Challenge information

251

*/

252

public AuthChallenge getAuthChallenge();

253

}

254

255

/**

256

* Authentication challenge details

257

*/

258

public class AuthChallenge {

259

/**

260

* Get origin requiring authentication

261

* @return Origin URL

262

*/

263

public String getOrigin();

264

265

/**

266

* Get authentication scheme (Basic, Digest, etc.)

267

* @return Auth scheme

268

*/

269

public String getScheme();

270

271

/**

272

* Get realm for authentication

273

* @return Realm string

274

*/

275

public Optional<String> getRealm();

276

}

277

278

/**

279

* Authentication response configuration

280

*/

281

public class AuthChallengeResponse {

282

public enum Response {

283

PROVIDECREDENTIALS,

284

CANCELAUTH

285

}

286

287

public AuthChallengeResponse(Response response, Optional<String> username, Optional<String> password);

288

}

289

```

290

291

### Request Interception Types

292

293

```java { .api }

294

/**

295

* Paused request event data during interception

296

*/

297

public class RequestPaused {

298

/**

299

* Get unique request identifier

300

* @return Request ID

301

*/

302

public RequestId getRequestId();

303

304

/**

305

* Get HTTP request details

306

* @return Request object

307

*/

308

public Request getRequest();

309

310

/**

311

* Get response status code if response is being intercepted

312

* @return Optional status code

313

*/

314

public Optional<Integer> getResponseStatusCode();

315

316

/**

317

* Get response headers if response is being intercepted

318

* @return Optional response headers

319

*/

320

public Optional<List<HeaderEntry>> getResponseHeaders();

321

322

/**

323

* Get response error reason if request failed

324

* @return Optional error reason

325

*/

326

public Optional<String> getResponseErrorReason();

327

}

328

329

/**

330

* HTTP request representation

331

*/

332

public class Request {

333

/**

334

* Get HTTP method

335

* @return Method string (GET, POST, etc.)

336

*/

337

public String getMethod();

338

339

/**

340

* Get request URL

341

* @return URL string

342

*/

343

public String getUrl();

344

345

/**

346

* Get request headers

347

* @return Headers map

348

*/

349

public Map<String, String> getHeaders();

350

351

/**

352

* Get POST data if present

353

* @return Optional POST data

354

*/

355

public Optional<String> getPostData();

356

}

357

358

/**

359

* HTTP header entry

360

*/

361

public class HeaderEntry {

362

public HeaderEntry(String name, String value);

363

364

public String getName();

365

public String getValue();

366

}

367

```

368

369

## Usage Examples

370

371

### Basic Network Monitoring

372

373

```java

374

import org.openqa.selenium.devtools.DevTools;

375

import org.openqa.selenium.devtools.v99.V99Domains;

376

377

DevTools devTools = ...; // from ChromeDriver

378

V99Domains domains = new V99Domains(devTools);

379

380

// Disable caching for consistent testing

381

devTools.send(domains.network().disableNetworkCaching());

382

383

// Enable request interception

384

devTools.send(domains.network().enableFetchForAllPatterns());

385

386

// Monitor all requests

387

devTools.addListener(domains.network().requestPausedEvent(), pausedRequest -> {

388

if (pausedRequest.getResponseStatusCode().isPresent()) {

389

// This is a response being intercepted

390

System.out.println("Response: " + pausedRequest.getRequest().getUrl() +

391

" -> " + pausedRequest.getResponseStatusCode().get());

392

} else {

393

// This is a request being intercepted

394

System.out.println("Request: " + pausedRequest.getRequest().getMethod() +

395

" " + pausedRequest.getRequest().getUrl());

396

}

397

398

// Continue without modification

399

devTools.send(domains.network().continueWithoutModification(pausedRequest));

400

});

401

```

402

403

### Request Modification

404

405

```java

406

// Enable interception

407

devTools.send(domains.network().enableFetchForAllPatterns());

408

409

devTools.addListener(domains.network().requestPausedEvent(), pausedRequest -> {

410

// Only modify requests, not responses

411

if (pausedRequest.getResponseStatusCode().isEmpty()) {

412

Request originalRequest = pausedRequest.getRequest();

413

414

// Modify API requests to point to test server

415

if (originalRequest.getUrl().contains("/api/")) {

416

HttpRequest modifiedRequest = createHttpRequest(

417

originalRequest.getMethod(),

418

originalRequest.getUrl().replace("api.prod.com", "api.test.com"),

419

originalRequest.getHeaders(),

420

originalRequest.getPostData().orElse(null)

421

);

422

423

devTools.send(domains.network().continueRequest(pausedRequest, modifiedRequest));

424

} else {

425

devTools.send(domains.network().continueWithoutModification(pausedRequest));

426

}

427

} else {

428

devTools.send(domains.network().continueWithoutModification(pausedRequest));

429

}

430

});

431

```

432

433

### Response Mocking

434

435

```java

436

devTools.send(domains.network().enableFetchForAllPatterns());

437

438

devTools.addListener(domains.network().requestPausedEvent(), pausedRequest -> {

439

// Only handle requests (not responses)

440

if (pausedRequest.getResponseStatusCode().isEmpty()) {

441

String url = pausedRequest.getRequest().getUrl();

442

443

// Mock specific API endpoints

444

if (url.contains("/api/users")) {

445

String mockResponse = """

446

{

447

"users": [

448

{"id": 1, "name": "Test User", "email": "test@example.com"}

449

]

450

}

451

""";

452

453

HttpResponse response = createHttpResponse(

454

200,

455

mockResponse,

456

List.of(

457

new AbstractMap.SimpleEntry<>("Content-Type", "application/json"),

458

new AbstractMap.SimpleEntry<>("Access-Control-Allow-Origin", "*")

459

)

460

);

461

462

devTools.send(domains.network().fulfillRequest(pausedRequest, response));

463

} else {

464

devTools.send(domains.network().continueWithoutModification(pausedRequest));

465

}

466

} else {

467

devTools.send(domains.network().continueWithoutModification(pausedRequest));

468

}

469

});

470

```

471

472

### Authentication Handling

473

474

```java

475

// Listen for authentication challenges

476

devTools.addListener(domains.network().authRequiredEvent(), authRequired -> {

477

String origin = domains.network().getUriFrom(authRequired);

478

System.out.println("Authentication required for: " + origin);

479

480

// Provide credentials

481

UsernameAndPassword credentials = new UsernameAndPassword("testuser", "testpass");

482

devTools.send(domains.network().continueWithAuth(authRequired, credentials));

483

484

// Or cancel authentication:

485

// devTools.send(domains.network().cancelAuth(authRequired));

486

});

487

488

// Enable interception to trigger auth events

489

devTools.send(domains.network().enableFetchForAllPatterns());

490

```

491

492

### User Agent Override

493

494

```java

495

// Simple user agent override

496

domains.network().setUserAgent("Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15");

497

498

// Or using configuration object for more control

499

UserAgent mobileUserAgent = new UserAgent("Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15")

500

.acceptLanguage("en-US,en;q=0.9")

501

.platform("iPhone");

502

503

domains.network().setUserAgent(mobileUserAgent);

504

505

// Now all requests will use the mobile user agent

506

```

507

508

### Authentication Management

509

510

```java

511

// Add authentication for specific API endpoints

512

domains.network().addAuthHandler(

513

uri -> uri.getHost().equals("api.secure.com"),

514

() -> new UsernameAndPassword("apiuser", "secret123")

515

);

516

517

// Add authentication for multiple patterns

518

domains.network().addAuthHandler(

519

uri -> uri.getPath().startsWith("/admin/"),

520

() -> new UsernameAndPassword("admin", "adminpass")

521

);

522

523

// Enable interception to trigger auth handling

524

domains.network().prepareToInterceptTraffic();

525

526

// Cleanup when done

527

domains.network().disable(); // Clears all auth handlers

528

```

529

530

### Request Filtering

531

532

```java

533

// Prepare for traffic interception

534

domains.network().prepareToInterceptTraffic();

535

536

// Set up custom filter for request modification

537

Filter customFilter = next -> req -> {

538

// Add custom headers to all requests

539

req.addHeader("X-Test-Mode", "true");

540

req.addHeader("X-Request-Time", String.valueOf(System.currentTimeMillis()));

541

542

// Continue with the modified request

543

return next.execute(req);

544

};

545

546

// Apply the filter to all network traffic

547

domains.network().interceptTrafficWith(customFilter);

548

549

// Reset to default behavior when done

550

domains.network().resetNetworkFilter();

551

```

552

553

## Error Handling

554

555

Network operations can encounter various error conditions:

556

557

- **Protocol errors**: CDP communication failures

558

- **Request/response errors**: Invalid HTTP data

559

- **Authentication failures**: Invalid credentials or cancelled auth

560

- **Interception conflicts**: Multiple interception handlers

561

562

Handle errors through proper exception handling and event monitoring:

563

564

```java

565

try {

566

devTools.send(domains.network().enableFetchForAllPatterns());

567

} catch (DevToolsException e) {

568

System.err.println("Failed to enable network interception: " + e.getMessage());

569

}

570

571

// Monitor for failed requests

572

devTools.addListener(domains.network().requestPausedEvent(), pausedRequest -> {

573

if (pausedRequest.getResponseErrorReason().isPresent()) {

574

System.err.println("Request failed: " + pausedRequest.getRequest().getUrl() +

575

" - " + pausedRequest.getResponseErrorReason().get());

576

}

577

578

// Always continue or fulfill to avoid hanging requests

579

devTools.send(domains.network().continueWithoutModification(pausedRequest));

580

});

581

```

582

583

## Performance Considerations

584

585

- **Interception overhead**: Request interception adds latency to all network requests

586

- **Memory usage**: Large request/response bodies are held in memory during interception

587

- **Event processing**: Network event handlers should be lightweight to avoid blocking

588

- **Cleanup**: Always disable interception when not needed to restore normal performance