Best Puppeteer-sharp code snippet using PuppeteerSharp.Messaging.ResponseReceivedExtraInfoResponse
NetworkManager.cs
Source:NetworkManager.cs
...138 case "Network.loadingFailed":139 OnLoadingFailed(e.MessageData.ToObject<LoadingFailedEventResponse>(true));140 break;141 case "Network.responseReceivedExtraInfo":142 await OnResponseReceivedExtraInfoAsync(e.MessageData.ToObject<ResponseReceivedExtraInfoResponse>(true)).ConfigureAwait(false);143 break;144 }145 }146 catch (Exception ex)147 {148 var message = $"NetworkManager failed to process {e.MessageID}. {ex.Message}. {ex.StackTrace}";149 _logger.LogError(ex, message);150 _client.Close(message);151 }152 }153 private async Task OnResponseReceivedExtraInfoAsync(ResponseReceivedExtraInfoResponse e)154 {155 var redirectInfo = _networkEventManager.TakeQueuedRedirectInfo(e.RequestId);156 if (redirectInfo != null)157 {158 _networkEventManager.ResponseExtraInfo(e.RequestId).Add(e);159 await OnRequestAsync(redirectInfo.Event, redirectInfo.FetchRequestId).ConfigureAwait(false);160 return;161 }162 // We may have skipped response and loading events because we didn't have163 // this ExtraInfo event yet. If so, emit those events now.164 var queuedEvents = _networkEventManager.GetQueuedEventGroup(e.RequestId);165 if (queuedEvents != null)166 {167 EmitResponseEvent(queuedEvents.ResponseReceivedEvent, e);168 if (queuedEvents.LoadingFinishedEvent != null) {169 OnLoadingFinished(queuedEvents.LoadingFinishedEvent);170 }171 if (queuedEvents.LoadingFailedEvent != null) {172 OnLoadingFailed(queuedEvents.LoadingFailedEvent);173 }174 // We need this in .NET to avoid race conditions175 _networkEventManager.ForgetQueuedEventGroup(e.RequestId);176 return;177 }178 // Wait until we get another event that can use this ExtraInfo event.179 _networkEventManager.ResponseExtraInfo(e.RequestId).Add(e);180 }181 private void OnLoadingFailed(LoadingFailedEventResponse e)182 {183 var queuedEvents = _networkEventManager.GetQueuedEventGroup(e.RequestId);184 if (queuedEvents != null)185 {186 queuedEvents.LoadingFailedEvent = e;187 }188 else189 {190 EmitLoadingFailed(e);191 }192 }193 private void EmitLoadingFailed(LoadingFailedEventResponse e)194 {195 var request = _networkEventManager.GetRequest(e.RequestId);196 if (request == null)197 {198 return;199 }200 request.Failure = e.ErrorText;201 request.Response?.BodyLoadedTaskWrapper.TrySetResult(true);202 ForgetRequest(request, true);203 RequestFailed?.Invoke(this, new RequestEventArgs204 {205 Request = request206 });207 }208 private void OnLoadingFinished(LoadingFinishedEventResponse e)209 {210 var queuedEvents = _networkEventManager.GetQueuedEventGroup(e.RequestId);211 if (queuedEvents != null)212 {213 queuedEvents.LoadingFinishedEvent = e;214 }215 else216 {217 EmitLoadingFinished(e);218 }219 }220 private void EmitLoadingFinished(LoadingFinishedEventResponse e)221 {222 var request = _networkEventManager.GetRequest(e.RequestId);223 if (request == null)224 {225 return;226 }227 request.Response?.BodyLoadedTaskWrapper.TrySetResult(true);228 ForgetRequest(request, true);229 RequestFinished?.Invoke(this, new RequestEventArgs230 {231 Request = request232 });233 }234 private void ForgetRequest(Request request, bool events)235 {236 _networkEventManager.ForgetRequest(request.RequestId);237 if (request.InterceptionId != null)238 {239 _attemptedAuthentications.Remove(request.InterceptionId);240 }241 if (events)242 {243 _networkEventManager.Forget(request.RequestId);244 }245 }246 private void OnResponseReceived(ResponseReceivedResponse e)247 {248 var request = _networkEventManager.GetRequest(e.RequestId);249 ResponseReceivedExtraInfoResponse extraInfo = null;250 if (request != null && !request.FromMemoryCache && e.HasExtraInfo)251 {252 extraInfo = _networkEventManager.ShiftResponseExtraInfo(e.RequestId);253 if (extraInfo == null)254 {255 _networkEventManager.QueuedEventGroup(e.RequestId, new()256 {257 ResponseReceivedEvent = e258 });259 return;260 }261 }262 EmitResponseEvent(e, extraInfo);263 }264 private void EmitResponseEvent(ResponseReceivedResponse e, ResponseReceivedExtraInfoResponse extraInfo)265 {266 var request = _networkEventManager.GetRequest(e.RequestId);267 // FileUpload sends a response without a matching request.268 if (request == null)269 {270 return;271 }272 var response = new Response(273 _client,274 request,275 e.Response,276 extraInfo);277 request.Response = response;278 Response?.Invoke(this, new ResponseCreatedEventArgs279 {280 Response = response281 });282 }283 private async Task OnAuthRequiredAsync(FetchAuthRequiredResponse e)284 {285 var response = "Default";286 if (_attemptedAuthentications.Contains(e.RequestId))287 {288 response = "CancelAuth";289 }290 else if (_credentials != null)291 {292 response = "ProvideCredentials";293 _attemptedAuthentications.Add(e.RequestId);294 }295 var credentials = _credentials ?? new Credentials();296 try297 {298 await _client.SendAsync("Fetch.continueWithAuth", new ContinueWithAuthRequest299 {300 RequestId = e.RequestId,301 AuthChallengeResponse = new ContinueWithAuthRequestChallengeResponse302 {303 Response = response,304 Username = credentials.Username,305 Password = credentials.Password306 }307 }).ConfigureAwait(false);308 }309 catch (PuppeteerException ex)310 {311 _logger.LogError(ex.ToString());312 }313 }314 private async Task OnRequestPausedAsync(FetchRequestPausedResponse e)315 {316 if (!_userRequestInterceptionEnabled && _protocolRequestInterceptionEnabled)317 {318 try319 {320 await _client.SendAsync("Fetch.continueRequest", new FetchContinueRequestRequest321 {322 RequestId = e.RequestId323 }).ConfigureAwait(false);324 }325 catch (PuppeteerException ex)326 {327 _logger.LogError(ex.ToString());328 }329 }330 if (string.IsNullOrEmpty(e.NetworkId))331 {332 return;333 }334 var requestWillBeSentEvent =335 _networkEventManager.GetRequestWillBeSent(e.NetworkId);336 // redirect requests have the same `requestId`,337 if (338 requestWillBeSentEvent != null &&339 (requestWillBeSentEvent.Request.Url != e.Request.Url ||340 requestWillBeSentEvent.Request.Method != e.Request.Method))341 {342 _networkEventManager.ForgetRequestWillBeSent(e.NetworkId);343 requestWillBeSentEvent = null;344 }345 if (requestWillBeSentEvent != null)346 {347 PatchRequestEventHeaders(requestWillBeSentEvent, e);348 await OnRequestAsync(requestWillBeSentEvent, e.RequestId).ConfigureAwait(false);349 }350 else351 {352 _networkEventManager.StoreRequestPaused(e.NetworkId, e);353 }354 }355 private async Task OnRequestAsync(RequestWillBeSentPayload e, string fetchRequestId)356 {357 Request request;358 var redirectChain = new List<Request>();359 if (e.RedirectResponse != null)360 {361 ResponseReceivedExtraInfoResponse redirectResponseExtraInfo = null;362 if (e.RedirectHasExtraInfo)363 {364 redirectResponseExtraInfo = _networkEventManager.ShiftResponseExtraInfo(e.RequestId);365 if (redirectResponseExtraInfo == null)366 {367 _networkEventManager.QueueRedirectInfo(e.RequestId, new()368 {369 Event = e,370 FetchRequestId = fetchRequestId,371 });372 return;373 }374 }375 request = _networkEventManager.GetRequest(e.RequestId);376 // If we connect late to the target, we could have missed the requestWillBeSent event.377 if (request != null)378 {379 HandleRequestRedirect(request, e.RedirectResponse, redirectResponseExtraInfo);380 redirectChain = request.RedirectChainList;381 }382 }383 var frame = !string.IsNullOrEmpty(e.FrameId) ? await FrameManager.TryGetFrameAsync(e.FrameId).ConfigureAwait(false) : null;384 request = new Request(385 _client,386 frame,387 fetchRequestId,388 _userRequestInterceptionEnabled,389 e,390 redirectChain);391 _networkEventManager.StoreRequest(e.RequestId, request);392 Request?.Invoke(this, new RequestEventArgs393 {394 Request = request395 });396 }397 private void OnRequestServedFromCache(RequestServedFromCacheResponse response)398 {399 var request = _networkEventManager.GetRequest(response.RequestId);400 if (request != null)401 {402 request.FromMemoryCache = true;403 }404 RequestServedFromCache?.Invoke(this, new RequestEventArgs { Request = request });405 }406 private void HandleRequestRedirect(Request request, ResponsePayload responseMessage, ResponseReceivedExtraInfoResponse extraInfo)407 {408 var response = new Response(409 _client,410 request,411 responseMessage,412 extraInfo);413 request.Response = response;414 request.RedirectChainList.Add(request);415 response.BodyLoadedTaskWrapper.TrySetException(416 new PuppeteerException("Response body is unavailable for redirect responses"));417 ForgetRequest(request, false);418 Response?.Invoke(this, new ResponseCreatedEventArgs419 {420 Response = response...
Response.cs
Source:Response.cs
...26 internal Response(27 CDPSession client,28 Request request,29 ResponsePayload responseMessage,30 ResponseReceivedExtraInfoResponse extraInfo)31 {32 _client = client;33 Request = request;34 Status = extraInfo != null ? extraInfo.StatusCode : responseMessage.Status;35 StatusText = ParseStatusTextFromExtrInfo(extraInfo) ?? responseMessage.StatusText;36 Url = request.Url;37 _fromDiskCache = responseMessage.FromDiskCache;38 FromServiceWorker = responseMessage.FromServiceWorker;39 Headers = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);40 var headers = extraInfo != null ? extraInfo.Headers : responseMessage.Headers;41 if (headers != null)42 {43 foreach (var keyValue in responseMessage.Headers)44 {45 Headers[keyValue.Key] = keyValue.Value;46 }47 }48 SecurityDetails = responseMessage.SecurityDetails;49 RemoteAddress = new RemoteAddress50 {51 IP = responseMessage.RemoteIPAddress,52 Port = responseMessage.RemotePort53 };54 BodyLoadedTaskWrapper = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);55 }56 /// <summary>57 /// Contains the URL of the response.58 /// </summary>59 public string Url { get; }60 /// <summary>61 /// An object with HTTP headers associated with the response. All header names are lower-case.62 /// </summary>63 /// <value>The headers.</value>64 public Dictionary<string, string> Headers { get; }65 /// <summary>66 /// Contains the status code of the response67 /// </summary>68 /// <value>The status.</value>69 public HttpStatusCode Status { get; }70 /// <summary>71 /// Contains a boolean stating whether the response was successful (status in the range 200-299) or not.72 /// </summary>73 /// <value><c>true</c> if ok; otherwise, <c>false</c>.</value>74 public bool Ok => Status == 0 || ((int)Status >= 200 && (int)Status <= 299);75 /// <summary>76 /// A matching <see cref="Request"/> object.77 /// </summary>78 /// <value>The request.</value>79 public Request Request { get; }80 /// <summary>81 /// True if the response was served from either the browser's disk cache or memory cache.82 /// </summary>83 public bool FromCache => _fromDiskCache || (Request?.FromMemoryCache ?? false);84 /// <summary>85 /// Gets or sets the security details.86 /// </summary>87 /// <value>The security details.</value>88 public SecurityDetails SecurityDetails { get; }89 /// <summary>90 /// Gets a value indicating whether the <see cref="Response"/> was served by a service worker.91 /// </summary>92 /// <value><c>true</c> if the <see cref="Response"/> was served by a service worker; otherwise, <c>false</c>.</value>93 public bool FromServiceWorker { get; }94 /// <summary>95 /// Contains the status text of the response (e.g. usually an "OK" for a success).96 /// </summary>97 /// <value>The status text.</value>98 public string StatusText { get; }99 /// <summary>100 /// Remove server address.101 /// </summary>102 public RemoteAddress RemoteAddress { get; }103 internal TaskCompletionSource<bool> BodyLoadedTaskWrapper { get; }104 /// <summary>105 /// A <see cref="Frame"/> that initiated this request. Or null if navigating to error pages.106 /// </summary>107 public Frame Frame => Request.Frame;108 private string ParseStatusTextFromExtrInfo(ResponseReceivedExtraInfoResponse extraInfo)109 {110 if (extraInfo == null || extraInfo.HeadersText == null)111 {112 return null;113 }114 var lines = extraInfo.HeadersText.Split('\r');115 if (lines.Length == 0)116 {117 return null;118 }119 var firstLine = lines[0];120 var match = ExtraInfoLines.Match(firstLine);121 if (!match.Success)122 {...
NetworkEventManager.cs
Source:NetworkEventManager.cs
...11 private readonly ConcurrentDictionary<string, FetchRequestPausedResponse> _requestPausedMap = new();12 private readonly ConcurrentDictionary<string, Request> _httpRequestsMap = new();13 private readonly ConcurrentDictionary<string, QueuedEventGroup> _queuedEventGroupMap = new();14 private readonly ConcurrentDictionary<string, List<RedirectInfo>> _queuedRedirectInfoMap = new();15 private readonly ConcurrentDictionary<string, List<ResponseReceivedExtraInfoResponse>> _responseReceivedExtraInfoMap = new();16 public int NumRequestsInProgress17 => _httpRequestsMap.Values.Count(r => r.Response == null);18 internal void Forget(string requestId)19 {20 _requestWillBeSentMap.TryRemove(requestId, out _);21 _requestPausedMap.TryRemove(requestId, out _);22 _queuedEventGroupMap.TryRemove(requestId, out _);23 _queuedRedirectInfoMap.TryRemove(requestId, out _);24 _responseReceivedExtraInfoMap.TryRemove(requestId, out _);25 }26 internal List<ResponseReceivedExtraInfoResponse> ResponseExtraInfo(string networkRequestId)27 {28 if (!_responseReceivedExtraInfoMap.ContainsKey(networkRequestId))29 {30 _responseReceivedExtraInfoMap.AddOrUpdate(31 networkRequestId,32 new List<ResponseReceivedExtraInfoResponse>(),33 (_, __) => new List<ResponseReceivedExtraInfoResponse>());34 }35 _responseReceivedExtraInfoMap.TryGetValue(networkRequestId, out var result);36 return result;37 }38 private List<RedirectInfo> QueuedRedirectInfo(string fetchRequestId)39 {40 if (!_queuedRedirectInfoMap.ContainsKey(fetchRequestId))41 {42 _queuedRedirectInfoMap.TryAdd(fetchRequestId, new List<RedirectInfo>());43 }44 _queuedRedirectInfoMap.TryGetValue(fetchRequestId, out var result);45 return result;46 }47 internal void QueueRedirectInfo(string fetchRequestId, RedirectInfo redirectInfo)48 => QueuedRedirectInfo(fetchRequestId).Add(redirectInfo);49 internal RedirectInfo TakeQueuedRedirectInfo(string fetchRequestId)50 {51 var list = QueuedRedirectInfo(fetchRequestId);52 var result = list.FirstOrDefault();53 if (result != null)54 {55 list.Remove(result);56 }57 return result;58 }59 internal ResponseReceivedExtraInfoResponse ShiftResponseExtraInfo(string networkRequestId)60 {61 if (!_responseReceivedExtraInfoMap.ContainsKey(networkRequestId))62 {63 _responseReceivedExtraInfoMap.TryAdd(networkRequestId, new List<ResponseReceivedExtraInfoResponse>());64 }65 _responseReceivedExtraInfoMap.TryGetValue(networkRequestId, out var list);66 var result = list.FirstOrDefault();67 if (result != null)68 {69 list.Remove(result);70 }71 return result;72 }73 internal void StoreRequestWillBeSent(string networkRequestId, RequestWillBeSentPayload e)74 => _requestWillBeSentMap.AddOrUpdate(networkRequestId, e, (_, __) => e);75 internal RequestWillBeSentPayload GetRequestWillBeSent(string networkRequestId)76 {77 _requestWillBeSentMap.TryGetValue(networkRequestId, out var result);...
ResponseReceivedExtraInfoResponse.cs
Source:ResponseReceivedExtraInfoResponse.cs
1using System.Collections.Generic;2using System.Net;3namespace PuppeteerSharp.Messaging4{5 internal class ResponseReceivedExtraInfoResponse6 {7 public string RequestId { get; set; }8 public HttpStatusCode StatusCode { get; set; }9 public Dictionary<string, string> Headers { get; set; }10 public string HeadersText { get; set; }11 }12}...
ResponseReceivedExtraInfoResponse
Using AI Code Generation
1var responseReceivedExtraInfoResponse = new ResponseReceivedExtraInfoResponse();2responseReceivedExtraInfoResponse.RequestId = "requestId";3responseReceivedExtraInfoResponse.Headers = new Dictionary<string, string>();4responseReceivedExtraInfoResponse.Headers.Add("headerName", "headerValue");5responseReceivedExtraInfoResponse.HeadersText = "headersText";6responseReceivedExtraInfoResponse.BlockReason = "blockReason";7var responseReceivedExtraInfoResponse = new ResponseReceivedExtraInfoResponse();8responseReceivedExtraInfoResponse.RequestId = "requestId";9responseReceivedExtraInfoResponse.Headers = new Dictionary<string, string>();10responseReceivedExtraInfoResponse.Headers.Add("headerName", "headerValue");11responseReceivedExtraInfoResponse.HeadersText = "headersText";12responseReceivedExtraInfoResponse.BlockReason = "blockReason";13var responseReceivedExtraInfoResponse = new ResponseReceivedExtraInfoResponse();14responseReceivedExtraInfoResponse.RequestId = "requestId";15responseReceivedExtraInfoResponse.Headers = new Dictionary<string, string>();16responseReceivedExtraInfoResponse.Headers.Add("headerName", "headerValue");17responseReceivedExtraInfoResponse.HeadersText = "headersText";18responseReceivedExtraInfoResponse.BlockReason = "blockReason";19var responseReceivedExtraInfoResponse = new ResponseReceivedExtraInfoResponse();20responseReceivedExtraInfoResponse.RequestId = "requestId";21responseReceivedExtraInfoResponse.Headers = new Dictionary<string, string>();22responseReceivedExtraInfoResponse.Headers.Add("headerName", "headerValue");23responseReceivedExtraInfoResponse.HeadersText = "headersText";24responseReceivedExtraInfoResponse.BlockReason = "blockReason";25var responseReceivedExtraInfoResponse = new ResponseReceivedExtraInfoResponse();26responseReceivedExtraInfoResponse.RequestId = "requestId";27responseReceivedExtraInfoResponse.Headers = new Dictionary<string, string>();28responseReceivedExtraInfoResponse.Headers.Add("headerName", "headerValue");29responseReceivedExtraInfoResponse.HeadersText = "headersText";30responseReceivedExtraInfoResponse.BlockReason = "blockReason";
ResponseReceivedExtraInfoResponse
Using AI Code Generation
1var response = await Page.ResponseReceivedExtraInfoAsync(new ResponseReceivedExtraInfoRequest2{3 {4 { "key", "value" }5 },6 {7 {8 { "key", "value" }9 },10 {11 {12 },13 },14 }15});16var response = await Page.ResponseReceivedExtraInfoAsync(new ResponseReceivedExtraInfoRequest17{18 {19 { "key", "value" }20 },21 {22 {23 { "key", "value" }24 },25 {26 {27 },28 },29 }30});
ResponseReceivedExtraInfoResponse
Using AI Code Generation
1{2 WaitUntil = new[] { WaitUntilNavigation.Networkidle0 }3});4var responseInfo = await response.ResponseReceivedExtraInfoResponse;5Console.WriteLine("Response info: " + responseInfo);6{7 WaitUntil = new[] { WaitUntilNavigation.Networkidle0 }8});9var responseInfo = await response.ResponseReceivedExtraInfoResponse;10Console.WriteLine("Response info: " + responseInfo);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!