or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

browser-management.mddevice-emulation.mdelement-handling.mdindex.mdinput-interaction.mdlocators-waiting.mdmedia-generation.mdnetwork-control.mdpage-interaction.mdperformance-debugging.md

network-control.mddocs/

0

# Network Control

1

2

Request and response interception, network monitoring, and offline mode simulation for comprehensive network testing and debugging.

3

4

## Capabilities

5

6

### HTTPRequest Class

7

8

Represents HTTP requests with interception and monitoring capabilities.

9

10

```typescript { .api }

11

/**

12

* HTTP request with interception capabilities

13

*/

14

class HTTPRequest {

15

/** Get request URL */

16

url(): string;

17

18

/** Get HTTP method */

19

method(): string;

20

21

/** Get request headers */

22

headers(): Record<string, string>;

23

24

/** Get POST data */

25

postData(): string | undefined;

26

27

/** Check if request has POST data */

28

hasPostData(): boolean;

29

30

/** Fetch POST data asynchronously */

31

fetchPostData(): Promise<string | undefined>;

32

33

/** Get resource type */

34

resourceType(): ResourceType;

35

36

/** Get initiating frame */

37

frame(): Frame | null;

38

39

/** Check if navigation request */

40

isNavigationRequest(): boolean;

41

42

/** Get request initiator */

43

initiator(): Protocol.Network.Initiator | undefined;

44

45

/** Get redirect chain */

46

redirectChain(): HTTPRequest[];

47

48

/** Abort request */

49

abort(errorCode?: ErrorCode, priority?: number): Promise<void>;

50

51

/** Continue request with overrides */

52

continue(overrides?: ContinueRequestOverrides, priority?: number): Promise<void>;

53

54

/** Mock request response */

55

respond(response: Partial<ResponseForRequest>, priority?: number): Promise<void>;

56

57

/** Check if interception handled */

58

isInterceptResolutionHandled(): boolean;

59

60

/** Get associated response */

61

response(): HTTPResponse | null;

62

}

63

64

type ResourceType = "document" | "stylesheet" | "image" | "media" | "font" | "script" | "texttrack" | "xhr" | "fetch" | "eventsource" | "websocket" | "manifest" | "other";

65

66

type ErrorCode = "aborted" | "accessdenied" | "addressunreachable" | "blockedbyclient" | "blockedbyresponse" | "connectionaborted" | "connectionclosed" | "connectionfailed" | "connectionrefused" | "connectionreset" | "internetdisconnected" | "namenotresolved" | "timedout" | "failed";

67

68

interface ContinueRequestOverrides {

69

url?: string;

70

method?: string;

71

postData?: string;

72

headers?: Record<string, string>;

73

}

74

75

interface ResponseForRequest {

76

status?: number;

77

headers?: Record<string, string>;

78

body?: string | Uint8Array;

79

contentType?: string;

80

}

81

```

82

83

**Usage Examples:**

84

85

```typescript

86

// Enable request interception

87

await page.setRequestInterception(true);

88

89

page.on("request", async (request) => {

90

console.log(`${request.method()} ${request.url()}`);

91

92

// Block images

93

if (request.resourceType() === "image") {

94

await request.abort();

95

return;

96

}

97

98

// Modify headers

99

if (request.url().includes("api")) {

100

await request.continue({

101

headers: {

102

...request.headers(),

103

"Authorization": "Bearer token123"

104

}

105

});

106

return;

107

}

108

109

// Mock response

110

if (request.url().includes("config.json")) {

111

await request.respond({

112

status: 200,

113

contentType: "application/json",

114

body: JSON.stringify({ mode: "test" })

115

});

116

return;

117

}

118

119

await request.continue();

120

});

121

```

122

123

### HTTPResponse Class

124

125

Represents HTTP responses with content access and metadata.

126

127

```typescript { .api }

128

/**

129

* HTTP response with content and metadata access

130

*/

131

class HTTPResponse {

132

/** Get response URL */

133

url(): string;

134

135

/** Get HTTP status code */

136

status(): number;

137

138

/** Get status text */

139

statusText(): string;

140

141

/** Check if status is 200-299 */

142

ok(): boolean;

143

144

/** Get response headers */

145

headers(): Record<string, string>;

146

147

/** Get remote server address */

148

remoteAddress(): RemoteAddress;

149

150

/** Get TLS security details */

151

securityDetails(): SecurityDetails | null;

152

153

/** Get timing information */

154

timing(): Protocol.Network.ResourceTiming | null;

155

156

/** Get raw response body */

157

content(): Promise<Uint8Array>;

158

159

/** Get response as Buffer */

160

buffer(): Promise<Buffer>;

161

162

/** Get response as text */

163

text(): Promise<string>;

164

165

/** Parse response as JSON */

166

json(): Promise<any>;

167

168

/** Get originating request */

169

request(): HTTPRequest;

170

171

/** Check if served from cache */

172

fromCache(): boolean;

173

174

/** Check if served from service worker */

175

fromServiceWorker(): boolean;

176

177

/** Get associated frame */

178

frame(): Frame | null;

179

}

180

181

interface RemoteAddress {

182

ip: string;

183

port: number;

184

}

185

186

interface SecurityDetails {

187

issuer: string;

188

validFrom: number;

189

validTo: number;

190

protocol: string;

191

subjectName: string;

192

subjectAlternativeNames: string[];

193

}

194

```

195

196

**Usage Examples:**

197

198

```typescript

199

page.on("response", async (response) => {

200

console.log(`${response.status()} ${response.url()}`);

201

202

// Check for errors

203

if (!response.ok()) {

204

console.error(`Failed request: ${response.status()} ${response.statusText()}`);

205

}

206

207

// Process API responses

208

if (response.url().includes("/api/") && response.ok()) {

209

try {

210

const data = await response.json();

211

console.log("API Response:", data);

212

} catch (error) {

213

console.error("Failed to parse JSON:", error);

214

}

215

}

216

217

// Check security

218

const security = response.securityDetails();

219

if (security) {

220

console.log(`TLS: ${security.protocol}, Issuer: ${security.issuer}`);

221

}

222

});

223

```

224

225

### Network Configuration

226

227

Configure network behavior and interception.

228

229

```typescript { .api }

230

/**

231

* Enable request interception

232

* @param value - Whether to intercept requests

233

*/

234

setRequestInterception(value: boolean): Promise<void>;

235

236

/**

237

* Set offline mode

238

* @param enabled - Whether to enable offline mode

239

*/

240

setOfflineMode(enabled: boolean): Promise<void>;

241

242

/**

243

* Set extra HTTP headers

244

* @param headers - Headers to add to all requests

245

*/

246

setExtraHTTPHeaders(headers: Record<string, string>): Promise<void>;

247

248

/**

249

* Set authentication credentials

250

* @param credentials - HTTP auth credentials or null to disable

251

*/

252

authenticate(credentials: Credentials | null): Promise<void>;

253

254

interface Credentials {

255

username: string;

256

password: string;

257

}

258

```

259

260

**Usage Examples:**

261

262

```typescript

263

// Configure network

264

await page.setExtraHTTPHeaders({

265

"Accept-Language": "en-US,en;q=0.9",

266

"User-Agent": "Custom Bot 1.0"

267

});

268

269

// Set authentication

270

await page.authenticate({

271

username: "testuser",

272

password: "testpass"

273

});

274

275

// Enable offline mode

276

await page.setOfflineMode(true);

277

await page.goto("https://example.com"); // Will fail

278

279

await page.setOfflineMode(false);

280

await page.goto("https://example.com"); // Will succeed

281

```

282

283

### Network Waiting

284

285

Wait for specific network events.

286

287

```typescript { .api }

288

/**

289

* Wait for request matching predicate

290

* @param urlOrPredicate - URL string or predicate function

291

* @param options - Wait options

292

*/

293

waitForRequest(

294

urlOrPredicate: string | ((request: HTTPRequest) => boolean),

295

options?: WaitTimeoutOptions

296

): Promise<HTTPRequest>;

297

298

/**

299

* Wait for response matching predicate

300

* @param urlOrPredicate - URL string or predicate function

301

* @param options - Wait options

302

*/

303

waitForResponse(

304

urlOrPredicate: string | ((response: HTTPResponse) => boolean),

305

options?: WaitTimeoutOptions

306

): Promise<HTTPResponse>;

307

308

/**

309

* Wait for network to be idle

310

* @param options - Network idle options

311

*/

312

waitForNetworkIdle(options?: WaitForNetworkIdleOptions): Promise<void>;

313

314

interface WaitTimeoutOptions {

315

timeout?: number;

316

}

317

318

interface WaitForNetworkIdleOptions {

319

timeout?: number;

320

idleTime?: number;

321

}

322

```

323

324

**Usage Examples:**

325

326

```typescript

327

// Wait for specific requests/responses

328

const apiRequest = page.waitForRequest("/api/users");

329

const apiResponse = page.waitForResponse(

330

response => response.url().includes("/api/") && response.ok()

331

);

332

333

await page.click("#load-data");

334

335

const request = await apiRequest;

336

const response = await apiResponse;

337

338

console.log(`Request: ${request.method()} ${request.url()}`);

339

console.log(`Response: ${response.status()}`);

340

341

// Wait for network idle

342

await page.goto("https://spa-app.com");

343

await page.waitForNetworkIdle({ idleTime: 1000 });

344

console.log("All network requests completed");

345

```

346

347

### Cookie Management

348

349

Manage HTTP cookies for network requests.

350

351

```typescript { .api }

352

/**

353

* Get cookies for URLs

354

* @param urls - URLs to get cookies for (optional)

355

*/

356

cookies(...urls: string[]): Promise<Cookie[]>;

357

358

/**

359

* Set cookies

360

* @param cookies - Cookies to set

361

*/

362

setCookie(...cookies: CookieParam[]): Promise<void>;

363

364

/**

365

* Delete cookies

366

* @param cookies - Cookies to delete

367

*/

368

deleteCookie(...cookies: DeleteCookiesRequest[]): Promise<void>;

369

370

interface Cookie {

371

name: string;

372

value: string;

373

domain: string;

374

path: string;

375

expires?: number;

376

size?: number;

377

httpOnly?: boolean;

378

secure?: boolean;

379

session?: boolean;

380

sameSite?: "Strict" | "Lax" | "None";

381

}

382

383

interface CookieParam {

384

name: string;

385

value: string;

386

url?: string;

387

domain?: string;

388

path?: string;

389

expires?: number;

390

httpOnly?: boolean;

391

secure?: boolean;

392

sameSite?: "Strict" | "Lax" | "None";

393

}

394

395

interface DeleteCookiesRequest {

396

name: string;

397

url?: string;

398

domain?: string;

399

path?: string;

400

}

401

```

402

403

**Usage Examples:**

404

405

```typescript

406

// Set cookies

407

await page.setCookie(

408

{

409

name: "session",

410

value: "abc123",

411

domain: "example.com"

412

},

413

{

414

name: "preferences",

415

value: "dark-mode",

416

domain: "example.com",

417

httpOnly: true,

418

secure: true

419

}

420

);

421

422

// Get cookies

423

const cookies = await page.cookies("https://example.com");

424

console.log("Page cookies:", cookies);

425

426

// Delete cookies

427

await page.deleteCookie(

428

{ name: "session", domain: "example.com" },

429

{ name: "temp-token", domain: "example.com" }

430

);

431

```