respond method
Fulfills request with given response. To use this, request interception should
be enabled with page.setRequestInterception. Exception is thrown if
request interception is not enabled.
An example of fulfilling all requests with 404 responses:
await page.setRequestInterception(true);
page.onRequest.listen((request) {
request.respond(status: 404, contentType: 'text/plain', body: 'Not Found!');
});
NOTE Mocking responses for dataURL requests is not supported. Calling
request.respondfor a dataURL request is a noop.
Parameters:
status: Response status code, defaults to200.headers: Optional response headerscontentType: If set, equals to settingContent-Typeresponse headerbody: Optional response body
Implementation
Future<void> respond({
int? status,
Map<String, String>? headers,
String? contentType,
body,
}) async {
// Mocking responses for dataURL requests is not currently supported.
if (url.startsWith('data:')) return;
assert(allowInterception, 'Request Interception is not enabled!');
assert(!_interceptionHandled, 'Request is already handled!');
_interceptionHandled = true;
headers ??= {};
if (contentType != null) {
headers['content-type'] = contentType;
}
List<int>? bodyBytes;
if (body is String) {
bodyBytes = utf8.encode(body);
}
if (body is List<int>) {
bodyBytes = body;
}
if (bodyBytes != null && !headers.containsKey('content-length')) {
headers['content-length'] = bodyBytes.length.toString();
}
await _fetchApi
.fulfillRequest(
fetch.RequestId(interceptionId!),
status ?? 200,
responseHeaders: headers.entries
.map(
(e) => fetch.HeaderEntry(
name: e.key.toLowerCase(),
value: e.value,
),
)
.toList(),
responsePhrase: _statusTexts[status ?? 200],
body: body != null ? base64.encode(bodyBytes!) : null,
)
.catchError((error) {
// In certain cases, protocol will return error if the request was already canceled
// or the page was closed. We should tolerate these errors.
_logger.finer('[Request.respond] swallow error: $error');
});
}