How to use RedirectInfo class of PuppeteerSharp package

Best Puppeteer-sharp code snippet using PuppeteerSharp.RedirectInfo

NetworkManager.cs

Source:NetworkManager.cs Github

copy

Full Screen

...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                }...

Full Screen

Full Screen

NetworkEventManager.cs

Source:NetworkEventManager.cs Github

copy

Full Screen

...10        private readonly ConcurrentDictionary<string, RequestWillBeSentPayload> _requestWillBeSentMap = new();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);...

Full Screen

Full Screen

RedirectInfo.cs

Source:RedirectInfo.cs Github

copy

Full Screen

1using PuppeteerSharp.Messaging;2namespace PuppeteerSharp3{4    internal class RedirectInfo5    {6        public RequestWillBeSentPayload Event { get; set; }7        public string FetchRequestId { get; set; }8    }9}...

Full Screen

Full Screen

RedirectInfo

Using AI Code Generation

copy

Full Screen

1var browserFetcher = new BrowserFetcher();2await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);3var browser = await Puppeteer.LaunchAsync(new LaunchOptions4{5    ExecutablePath = browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision),6    Args = new[] { "--no-sandbox" }7});8var page = await browser.NewPageAsync();9Console.WriteLine(response.Url);10await browser.CloseAsync();11var browserFetcher = new BrowserFetcher();12await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);13var browser = await Puppeteer.LaunchAsync(new LaunchOptions14{15    ExecutablePath = browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision),16    Args = new[] { "--no-sandbox" }17});18var page = await browser.NewPageAsync();19Console.WriteLine(page.Url);20await browser.CloseAsync();21var browserFetcher = new BrowserFetcher();22await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);

Full Screen

Full Screen

RedirectInfo

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2var browser = await Puppeteer.LaunchAsync(new LaunchOptions3{4});5var page = await browser.NewPageAsync();6await page.WaitForNavigationAsync(new NavigationOptions7{8    WaitUntil = new[] { WaitUntilNavigation.Networkidle2 }9});10var redirectInfo = new RedirectInfo();11redirectInfo = page.RedirectInfo;12Console.WriteLine(redirectInfo.Url);13Console.WriteLine(redirectInfo.Status);14Console.WriteLine(redirectInfo.Headers);15Console.WriteLine(redirectInfo.Method);16Console.WriteLine(redirectInfo.RequestHeaders);17Console.WriteLine(redirectInfo.RequestPostData);18Console.WriteLine(redirectInfo.ResponseHeaders);19Console.WriteLine(redirectInfo.ResponseStatusCode);20Console.WriteLine(redirectInfo.ResponseStatusText);21Console.WriteLine(redirectInfo.ResponseUrl);22Console.WriteLine(redirectInfo.ResponseFromServiceWorker);23Console.WriteLine(redirectInfo.Failed);24Console.WriteLine(redirectInfo.ErrorText);25Console.WriteLine(redirectInfo.InterceptionId);26Console.WriteLine(redirectInfo.InterceptionHandled);27Console.WriteLine(redirectInfo.InterceptionHasUserGesture);28Console.WriteLine(redirectInfo.InterceptionIsNavigationRequest);29Console.WriteLine(redirectInfo.InterceptionRedirectChain);30Console.WriteLine(redirectInfo.InterceptionResponseStatusCode);31Console.WriteLine(redirectInfo.InterceptionResponseHeaders);32Console.WriteLine(redirectInfo.InterceptionResponseHeadersText);33Console.WriteLine(redirectInfo.InterceptionResponseUrl);34Console.WriteLine(redirectInfo.InterceptionResponseErrorText);35Console.WriteLine(redirectInfo.InterceptionResponseFromServiceWorker);36Console.WriteLine(redirectInfo.InterceptionResponseFromDiskCache);37Console.WriteLine(redirectInfo.InterceptionResponseFromMemoryCache);38Console.WriteLine(redirectInfo.InterceptionResponseFromPrefetchCache);39Console.WriteLine(redirectInfo.InterceptionResponseEncodedDataLength);40Console.WriteLine(redirectInfo.InterceptionResponseFromServiceWorker);41Console.WriteLine(redirectIn

Full Screen

Full Screen

RedirectInfo

Using AI Code Generation

copy

Full Screen

1{2    Args = new[] { "--disable-extensions" },3    ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",4    IgnoreDefaultArgs = new[] { "--enable-automation" }5};6using (var browser = await Puppeteer.LaunchAsync(options))7{8    var page = await browser.NewPageAsync();9    await page.TypeAsync("input[title='Search']", "example");10    await page.ClickAsync("input[value='Google Search']");11    await page.WaitForNavigationAsync();12    await page.ScreenshotAsync("example.png");13}14{15    Args = new[] { "--disable-extensions" },16    ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",17    IgnoreDefaultArgs = new[] { "--enable-automation" }18};19using (var browser = await Puppeteer.LaunchAsync(options))20{21    var page = await browser.NewPageAsync();22    await page.TypeAsync("input[title='Search']", "example");23    await page.ClickAsync("input[value='Google Search']");24    await page.WaitForNavigationAsync();25    await page.ScreenshotAsync("example.png");26}27{28    Args = new[] { "--disable-extensions" },29    ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",30    IgnoreDefaultArgs = new[] { "--enable-automation" }31};32using (var browser = await Puppeteer.LaunchAsync(options))33{34    var page = await browser.NewPageAsync();35    await page.TypeAsync("input[title='Search']", "example");36    await page.ClickAsync("input[value='Google Search']");37    await page.WaitForNavigationAsync();38    await page.ScreenshotAsync("

Full Screen

Full Screen

RedirectInfo

Using AI Code Generation

copy

Full Screen

1var redirectInfo = new RedirectInfo();2redirectInfo.StatusCode = 301;3redirectInfo.RequestHeaders = new Dictionary<string, string>();4redirectInfo.ResponseHeaders = new Dictionary<string, string>();5await page.GoToAsync(redirectInfo);6var redirectInfo = new RedirectInfo();7redirectInfo.StatusCode = 301;8redirectInfo.RequestHeaders = new Dictionary<string, string>();9redirectInfo.ResponseHeaders = new Dictionary<string, string>();10await page.GoToAsync(redirectInfo);11var redirectInfo = new RedirectInfo();12redirectInfo.StatusCode = 301;13redirectInfo.RequestHeaders = new Dictionary<string, string>();14redirectInfo.ResponseHeaders = new Dictionary<string, string>();15await page.GoToAsync(redirectInfo);16var redirectInfo = new RedirectInfo();17redirectInfo.StatusCode = 301;18redirectInfo.RequestHeaders = new Dictionary<string, string>();19redirectInfo.ResponseHeaders = new Dictionary<string, string>();20await page.GoToAsync(redirectInfo);21var redirectInfo = new RedirectInfo();22redirectInfo.StatusCode = 301;23redirectInfo.RequestHeaders = new Dictionary<string, string>();24redirectInfo.ResponseHeaders = new Dictionary<string, string>();25redirectInfo.ResponseHeaders.Add("Location

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful