or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-features.mdapi-testing.mdassertions.mdbrowser-management.mdelement-location.mdindex.mdmobile-testing.mdnetwork-interception.mdpage-interaction.md

network-interception.mddocs/

0

# Network Interception

1

2

Intercept, modify, and mock network requests and responses for testing offline scenarios, API mocking, and comprehensive network monitoring.

3

4

## Capabilities

5

6

### Request Interception

7

8

Intercept and modify network requests at the page or context level.

9

10

```python { .api }

11

class Page:

12

def route(

13

self,

14

url: Union[str, Pattern, Callable[[str], bool]],

15

handler: Callable[[Route], None]

16

) -> None:

17

"""

18

Intercept requests matching URL pattern.

19

20

Args:

21

url: URL pattern to intercept

22

handler: Function to handle intercepted requests

23

"""

24

25

def unroute(

26

self,

27

url: Union[str, Pattern, Callable[[str], bool]],

28

handler: Optional[Callable[[Route], None]] = None

29

) -> None:

30

"""

31

Remove request interception.

32

33

Args:

34

url: URL pattern to stop intercepting

35

handler: Specific handler to remove (all if None)

36

"""

37

38

class BrowserContext:

39

def route(

40

self,

41

url: Union[str, Pattern, Callable[[str], bool]],

42

handler: Callable[[Route], None]

43

) -> None:

44

"""Intercept requests across all pages in context."""

45

46

def unroute(

47

self,

48

url: Union[str, Pattern, Callable[[str], bool]],

49

handler: Optional[Callable[[Route], None]] = None

50

) -> None:

51

"""Remove context-level request interception."""

52

53

class Route:

54

"""Handle intercepted network requests."""

55

request: Request

56

57

def abort(self, error_code: Optional[str] = None) -> None:

58

"""

59

Abort request with error.

60

61

Args:

62

error_code: Error code ('failed', 'aborted', 'timedout', etc.)

63

"""

64

65

def continue_(

66

self,

67

url: Optional[str] = None,

68

method: Optional[str] = None,

69

post_data: Optional[str] = None,

70

headers: Optional[Dict[str, str]] = None

71

) -> None:

72

"""

73

Continue request with optional modifications.

74

75

Args:

76

url: Override request URL

77

method: Override HTTP method

78

post_data: Override POST data

79

headers: Override/add headers

80

"""

81

82

def fulfill(

83

self,

84

status: Optional[int] = None,

85

headers: Optional[Dict[str, str]] = None,

86

body: Optional[Union[str, bytes]] = None,

87

json: Optional[Any] = None,

88

path: Optional[str] = None,

89

content_type: Optional[str] = None,

90

response: Optional[APIResponse] = None

91

) -> None:

92

"""

93

Fulfill request with custom response.

94

95

Args:

96

status: HTTP status code

97

headers: Response headers

98

body: Response body

99

json: JSON response body

100

path: File path for response body

101

content_type: Content-Type header

102

response: Copy response from APIResponse

103

"""

104

```

105

106

### Request and Response Objects

107

108

Access request and response data for monitoring and debugging.

109

110

```python { .api }

111

class Request:

112

"""HTTP request representation."""

113

url: str

114

method: str

115

post_data: Optional[str]

116

post_data_json: Optional[Any]

117

post_data_buffer: Optional[bytes]

118

headers: Dict[str, str]

119

resource_type: str

120

frame: Frame

121

122

def response(self) -> Optional[Response]:

123

"""Get response for this request."""

124

125

def is_navigation_request(self) -> bool:

126

"""Check if this is a navigation request."""

127

128

class Response:

129

"""HTTP response representation."""

130

url: str

131

ok: bool

132

status: int

133

status_text: str

134

headers: Dict[str, str]

135

request: Request

136

137

def body(self) -> bytes:

138

"""Get response body as bytes."""

139

140

def text(self) -> str:

141

"""Get response body as text."""

142

143

def json(self) -> Any:

144

"""Parse response body as JSON."""

145

```

146

147

## Usage Examples

148

149

### API Mocking

150

151

```python

152

from playwright.sync_api import sync_playwright

153

154

def handle_api_route(route):

155

if "api/users" in route.request.url:

156

route.fulfill(

157

status=200,

158

json={"users": [{"id": 1, "name": "Test User"}]}

159

)

160

else:

161

route.continue_()

162

163

with sync_playwright() as p:

164

browser = p.chromium.launch()

165

page = browser.new_page()

166

167

# Mock API responses

168

page.route("**/api/**", handle_api_route)

169

170

page.goto("https://app.com")

171

browser.close()

172

```

173

174

### Request Monitoring

175

176

```python

177

requests = []

178

responses = []

179

180

def log_request(request):

181

requests.append({

182

"url": request.url,

183

"method": request.method,

184

"headers": request.headers

185

})

186

187

def log_response(response):

188

responses.append({

189

"url": response.url,

190

"status": response.status,

191

"size": len(response.body())

192

})

193

194

with sync_playwright() as p:

195

browser = p.chromium.launch()

196

page = browser.new_page()

197

198

page.on("request", log_request)

199

page.on("response", log_response)

200

201

page.goto("https://example.com")

202

203

print(f"Requests: {len(requests)}")

204

print(f"Responses: {len(responses)}")

205

206

browser.close()

207

```