Best Puppeteer-sharp code snippet using PuppeteerSharp.Frame.Navigated
FetchDynamicResource.xaml.cs
Source:FetchDynamicResource.xaml.cs  
...219                ShowRecordIE(index);220        }221222223        private void ieBrowser_Navigated(object sender, System.Windows.Forms.WebBrowserNavigatedEventArgs e)224        {225            countIE++;226            string url = "";227            string title = "";228            ShowCountMessageIE(countIE);229            string html = ieBrowser.Document.GetElementsByTagName("html")[0].OuterHtml;230            this.Dispatcher.Invoke(() => {231                url = ieBrowser.Url.ToString();232                title = ieBrowser.Document.Title;233            });234            ShowHtmlIE(html, url, title);235        }236        #endregion237
...Authorization.cs
Source:Authorization.cs  
...130            p.WorkerCreated += (s, e) => P_Close("WorkerCreated");131            p.WorkerDestroyed += (s, e) => P_Close("WorkerDestroyed");132            p.FrameAttached += P_FrameAttached;133            p.FrameDetached += P_FrameAttached;134            p.FrameNavigated += P_FrameAttached;135            p.FrameNavigated += P_FrameAttached;*/136        }137        private static async Task<Page> GetPage(Browser browser, string url)138        {139            Page[] pages;140            do141            {142                pages = await browser.PagesAsync();143                await System.Threading.Tasks.Task.Delay(1000);144            } while (!pages.Any(p2 => p2.Url.StartsWith(url)));145            var page = pages.Single(p2 => p2.Url.StartsWith(url));146            page.DefaultTimeout = DefaultTimeout;147            page.DefaultNavigationTimeout = DefaultTimeout;148            await page.SetRequestInterceptionAsync(true);149            page.Request += (sender, e) =>...BrowserInstance.cs
Source:BrowserInstance.cs  
...44            }45            // remove user closed browser action46            CurrentBrowserInstance.Closed -= OnUserClosedBrowser;47            // remove Methods on actions48            CurrentPageInstance.FrameNavigated -= OnCurrentPageInstanceOnFrameNavigated;49            CurrentPageInstance.Load -= OnCurrentPageInstanceOnLoad;50            CurrentPageInstance.Error -= OnCurrentPageInstanceOnError;51            CurrentPageInstance.DOMContentLoaded -= OnCurrentPageInstanceOnDomContentLoaded;52            CurrentPageInstance.RequestFailed -= OnCurrentPageInstanceOnRequestFailed;53            CurrentPageInstance.Close -= OnCurrentPageInstanceOnClose;54            CurrentPageInstance.PageError -= OnCurrentPageInstanceOnPageInstanceError;55            CurrentPageInstance.Dialog -= OnCurrentPageInstanceOnDialog;56            CurrentBrowserInstance.Closed -= OnCurrentBrowserInstanceOnClosed;57            await CurrentPageInstance.CloseAsync();58            await CurrentBrowserInstance.CloseAsync();59            await CurrentPageInstance.DisposeAsync();60            CurrentPageInstance = null;61            await CurrentBrowserInstance.DisposeAsync();62            CurrentBrowserInstance = null;63        }64        public async Task LaunchIfClosed()65        {66            if (CurrentBrowserInstance == null)67            {68                string executableLocalPath = null;69                // prioritize last used browser70                var useBrowser = _localBrowsers.FirstOrDefault(b => b.BrowserID == _settings.UsedBrowser);71                //var useBrowser = _localBrowsers.FirstOrDefault(b => b is BundledChromium);72                if (useBrowser != null)73                {74                    _localBrowsers.Remove(useBrowser);75                    _localBrowsers.Insert(0, useBrowser);76                }77                foreach (ILocalBrowser localBrowser in _localBrowsers)78                {79                    executableLocalPath = await localBrowser.GetExecutable();80                    if (executableLocalPath == null)81                    {82                        continue;83                    }84                    // Sign out if browser is changed85                    if (localBrowser.BrowserID != _settings.UsedBrowser)86                    {87                        _gUser.IsSignedIn = false;88                        DeleteUserData();89                        _settings.UsedBrowser = localBrowser.BrowserID;90                    }91                    break;92                }93                if (string.IsNullOrEmpty(executableLocalPath))94                {95                    // Failed to run any Browser96                    return;97                }98                CurrentBrowserInstance = await LaunchBrowser(UserDataDirPath(), executableLocalPath);99                // user closes browser scenario100                CurrentBrowserInstance.Closed += OnUserClosedBrowser;101            }102            if (CurrentPageInstance == null)103            {104                var pages = await CurrentBrowserInstance.PagesAsync();105                CurrentPageInstance = null;106                if (pages.Any() && pages.Last().Url == "about:blank")107                {108                    CurrentPageInstance = pages.Last();109                }110                else111                {112                    CurrentPageInstance = await CurrentBrowserInstance.NewPageAsync();113                }114                // configure Logger115                CurrentPageInstance.FrameNavigated += OnCurrentPageInstanceOnFrameNavigated;116                CurrentPageInstance.Load += OnCurrentPageInstanceOnLoad;117                CurrentPageInstance.Error += OnCurrentPageInstanceOnError;118                CurrentPageInstance.DOMContentLoaded += OnCurrentPageInstanceOnDomContentLoaded;119                CurrentPageInstance.RequestFailed += OnCurrentPageInstanceOnRequestFailed;120                CurrentPageInstance.Close += OnCurrentPageInstanceOnClose;121                CurrentPageInstance.PageError += OnCurrentPageInstanceOnPageInstanceError;122                CurrentPageInstance.Dialog += OnCurrentPageInstanceOnDialog;123                CurrentBrowserInstance.Closed += OnCurrentBrowserInstanceOnClosed;124                //CurrentPageInstance.Request += (sender, args) =>125                //{126                //    App.PuppeteerLogger.Information($"{args.Request.Method.Method} {args.Request.Url}");127                //};128                //CurrentPageInstance.Response += (sender, args) =>129                //{130                //    App.PuppeteerLogger.Information($"{args.Response.Ok} {args.Response.Url}");131                //};132                //await CurrentPageInstance.SetViewportAsync();133            }134        }135        private async void OnUserClosedBrowser(object? sender, EventArgs e) => await Close();136        private static async Task<Browser> LaunchBrowser(string userDataDirPath, string executableLocalPath) =>137            await Puppeteer.LaunchAsync(new LaunchOptions138            {139                Headless = false,140                UserDataDir = userDataDirPath,141                ExecutablePath = executableLocalPath,142                //Args = new []{143                //    "--disable-background-timer-throttling",144                //    "--disable-backgrounding-occluded-windows",145                //    "--disable-renderer-backgrounding"146                //},147                IgnoredDefaultArgs = new[] {"--disable-extensions"},148                DefaultViewport = new ViewPortOptions() {Height = 600, Width = 1000}149            });150        private void OnCurrentBrowserInstanceOnClosed(object? sender, EventArgs args) =>151            App.PuppeteerLogger.Information($"Browser closed.");152        private void OnCurrentPageInstanceOnDialog(object? sender, DialogEventArgs args) =>153            App.PuppeteerLogger.Information($"{args.Dialog.DialogType} {args.Dialog.Message}");154        private void OnCurrentPageInstanceOnPageInstanceError(object? sender, PageErrorEventArgs args) =>155            App.PuppeteerLogger.Error($"PageError {args.Message}");156        private void OnCurrentPageInstanceOnClose(object? sender, EventArgs args) =>157            App.PuppeteerLogger.Information($"Page closed.");158        private void OnCurrentPageInstanceOnRequestFailed(object? sender, RequestEventArgs args) =>159            App.PuppeteerLogger.Error($"{args.Request.Method.Method} {args.Request.Url}");160        private void OnCurrentPageInstanceOnDomContentLoaded(object? sender, EventArgs args) =>161            App.PuppeteerLogger.Information($"DOMLoaded {CurrentPageInstance.Url}");162        private void OnCurrentPageInstanceOnError(object? sender, ErrorEventArgs args) =>163            App.PuppeteerLogger.Error($"{args.Error}");164        private void OnCurrentPageInstanceOnLoad(object? sender, EventArgs args) =>165            App.PuppeteerLogger.Information($"OnLoaded {CurrentPageInstance.Url}");166        private void OnCurrentPageInstanceOnFrameNavigated(object? sender, FrameEventArgs args) =>167            App.PuppeteerLogger.Information($"Navigated to {args.Frame.Url}");168        public void DeleteUserData()169        {170            try171            {172                Directory.Delete(UserDataDirPath(), true);173            }174            catch (Exception e)175            {176                // there might be also files that can't be touched177            }178        }179    }180}...FrameManagementTests.cs
Source:FrameManagementTests.cs  
...34            Assert.Single(attachedFrames);35            Assert.Contains("/Assets/frame.html", attachedFrames[0].Url);36            // validate framenavigated events37            var navigatedFrames = new List<Frame>();38            Page.FrameNavigated += (_, e) => navigatedFrames.Add(e.Frame);39            await FrameUtils.NavigateFrameAsync(Page, "frame1", "./empty.html");40            Assert.Single(navigatedFrames);41            Assert.Equal(TestConstants.EmptyPage, navigatedFrames[0].Url);42            // validate framedetached events43            var detachedFrames = new List<Frame>();44            Page.FrameDetached += (_, e) => detachedFrames.Add(e.Frame);45            await FrameUtils.DetachFrameAsync(Page, "frame1");46            Assert.Single(navigatedFrames);47            Assert.True(navigatedFrames[0].Detached);48        }49        [PuppeteerTest("frame.spec.ts", "Frame Management", "should send \"framenavigated\" when navigating on anchor URLs")]50        [SkipBrowserFact(skipFirefox: true)]51        public async Task ShouldSendFrameNavigatedWhenNavigatingOnAnchorURLs()52        {53            await Page.GoToAsync(TestConstants.EmptyPage);54            var frameNavigated = new TaskCompletionSource<bool>();55            Page.FrameNavigated += (_, _) => frameNavigated.TrySetResult(true);56            await Task.WhenAll(57                Page.GoToAsync(TestConstants.EmptyPage + "#foo"),58                frameNavigated.Task59            );60            Assert.Equal(TestConstants.EmptyPage + "#foo", Page.Url);61        }62        [PuppeteerTest("frame.spec.ts", "Frame Management", "should support url fragment")]63        [PuppeteerFact]64        public async Task ShouldReturnUrlFragmentAsPartOfUrl()65        {66            await Page.GoToAsync(TestConstants.ServerUrl + "/frames/one-frame-url-fragment.html");67            Assert.Equal(2, Page.Frames.Length);68            Assert.Equal(TestConstants.ServerUrl + "/frames/frame.html?param=value#fragment", Page.FirstChildFrame().Url);69        }70        [PuppeteerTest("frame.spec.ts", "Frame Management", "should persist mainFrame on cross-process navigation")]71        [PuppeteerFact]72        public async Task ShouldPersistMainFrameOnCrossProcessNavigation()73        {74            await Page.GoToAsync(TestConstants.EmptyPage);75            var mainFrame = Page.MainFrame;76            await Page.GoToAsync(TestConstants.CrossProcessUrl + "/empty.html");77            Assert.Equal(mainFrame, Page.MainFrame);78        }79        [PuppeteerTest("frame.spec.ts", "Frame Management", "should not send attach/detach events for main frame")]80        [PuppeteerFact]81        public async Task ShouldNotSendAttachDetachEventsForMainFrame()82        {83            var hasEvents = false;84            Page.FrameAttached += (_, _) => hasEvents = true;85            Page.FrameDetached += (_, _) => hasEvents = true;86            await Page.GoToAsync(TestConstants.EmptyPage);87            Assert.False(hasEvents);88        }89        [PuppeteerTest("frame.spec.ts", "Frame Management", "should detach child frames on navigation")]90        [SkipBrowserFact(skipFirefox: true)]91        public async Task ShouldDetachChildFramesOnNavigation()92        {93            var attachedFrames = new List<Frame>();94            var detachedFrames = new List<Frame>();95            var navigatedFrames = new List<Frame>();96            Page.FrameAttached += (_, e) => attachedFrames.Add(e.Frame);97            Page.FrameDetached += (_, e) => detachedFrames.Add(e.Frame);98            Page.FrameNavigated += (_, e) => navigatedFrames.Add(e.Frame);99            await Page.GoToAsync(TestConstants.ServerUrl + "/frames/nested-frames.html");100            Assert.Equal(4, attachedFrames.Count);101            Assert.Empty(detachedFrames);102            Assert.Equal(5, navigatedFrames.Count);103            attachedFrames.Clear();104            detachedFrames.Clear();105            navigatedFrames.Clear();106            await Page.GoToAsync(TestConstants.EmptyPage);107            Assert.Empty(attachedFrames);108            Assert.Equal(4, detachedFrames.Count);109            Assert.Single(navigatedFrames);110        }111        [PuppeteerTest("frame.spec.ts", "Frame Management", "should report frame from-inside shadow DOM")]112        [PuppeteerFact]...FrameManager.cs
Source:FrameManager.cs  
...25        }26        #region Properties27        internal event EventHandler<FrameEventArgs> FrameAttached;28        internal event EventHandler<FrameEventArgs> FrameDetached;29        internal event EventHandler<FrameEventArgs> FrameNavigated;30        internal event EventHandler<FrameEventArgs> LifecycleEvent;31        internal Dictionary<string, Frame> Frames { get; set; }32        internal Frame MainFrame { get; set; }33        #endregion34        #region Private Methods35        void _client_MessageReceived(object sender, PuppeteerSharp.MessageEventArgs e)36        {37            switch (e.MessageID)38            {39                case "Page.frameAttached":40                    OnFrameAttached(e.MessageData.frameId.ToString(), e.MessageData.parentFrameId.ToString());41                    break;42                case "Page.frameNavigated":43                    OnFrameNavigated(((JObject)e.MessageData.frame).ToObject<FramePayload>());44                    break;45                case "Page.frameDetached":46                    OnFrameDetached(e.MessageData.frameId.ToString());47                    break;48                case "Runtime.executionContextCreated":49                    OnExecutionContextCreated(new ContextPayload(e.MessageData.context));50                    break;51                case "Runtime.executionContextDestroyed":52                    OnExecutionContextDestroyed((int)e.MessageData.executionContextId);53                    break;54                case "Runtime.executionContextsCleared":55                    OnExecutionContextsCleared();56                    break;57                case "Page.lifecycleEvent":58                    OnLifeCycleEvent(e);59                    break;60                default:61                    break;62            }63        }64        private void OnLifeCycleEvent(MessageEventArgs e)65        {66            if (Frames.ContainsKey(e.MessageData.frameId.ToString()))67            {68                Frame frame = Frames[e.MessageData.frameId.ToString()];69                frame.OnLifecycleEvent(e.MessageData.loaderId.ToString(), e.MessageData.name.ToString());70                LifecycleEvent?.Invoke(this, new FrameEventArgs(frame));71            }72        }73        private void OnExecutionContextsCleared()74        {75            foreach (var context in _contextIdToContext.Values)76            {77                RemoveContext(context);78            }79            _contextIdToContext.Clear();80        }81        private void OnExecutionContextDestroyed(int executionContextId)82        {83            _contextIdToContext.TryGetValue(executionContextId, out var context);84            if (context != null)85            {86                _contextIdToContext.Remove(executionContextId);87                RemoveContext(context);88            }89        }90        public JSHandle CreateJsHandle(int contextId, dynamic remoteObject)91        {92            _contextIdToContext.TryGetValue(contextId, out var storedContext);93            if (storedContext == null)94            {95                _logger.LogError("INTERNAL ERROR: missing context with id = {ContextId}", contextId);96            }97            if (remoteObject.subtype == "node")98            {99                return new ElementHandle(storedContext, _client, remoteObject, _page);100            }101            return new JSHandle(storedContext, _client, remoteObject);102        }103        private void OnExecutionContextCreated(ContextPayload contextPayload)104        {105            var context = new ExecutionContext(_client, contextPayload,106                remoteObject => CreateJsHandle(contextPayload.Id, remoteObject));107            _contextIdToContext[contextPayload.Id] = context;108            var frame = !string.IsNullOrEmpty(context.FrameId) ? Frames[context.FrameId] : null;109            if (frame != null && context.IsDefault)110            {111                frame.SetDefaultContext(context);112            }113        }114        private void OnFrameDetached(string frameId)115        {116            if (Frames.ContainsKey(frameId))117            {118                RemoveFramesRecursively(Frames[frameId]);119            }120        }121        private void OnFrameNavigated(FramePayload framePayload)122        {123            var isMainFrame = string.IsNullOrEmpty(framePayload.ParentId);124            var frame = isMainFrame ? MainFrame : Frames[framePayload.Id];125            Contract.Assert(isMainFrame || frame != null, "We either navigate top level or have old version of the navigated frame");126            // Detach all child frames first.127            if (frame != null)128            {129                while (frame.ChildFrames.Count > 0)130                {131                    RemoveFramesRecursively(frame.ChildFrames[0]);132                }133            }134            // Update or create main frame.135            if (isMainFrame)136            {137                if (frame != null)138                {139                    // Update frame id to retain frame identity on cross-process navigation.140                    if (frame.Id != null)141                    {142                        Frames.Remove(frame.Id);143                    }144                    frame.Id = framePayload.Id;145                }146                else147                {148                    // Initial main frame navigation.149                    frame = new Frame(this._client, this._page, null, framePayload.Id);150                }151                Frames[framePayload.Id] = frame;152                MainFrame = frame;153            }154            // Update frame payload.155            frame.Navigated(framePayload);156            FrameNavigated?.Invoke(this, new FrameEventArgs(frame));157        }158        private void RemoveContext(ExecutionContext context)159        {160            var frame = !string.IsNullOrEmpty(context.FrameId) ? Frames[context.FrameId] : null;161            if (frame != null && context.IsDefault)162            {163                frame.SetDefaultContext(null);164            }165        }166        private void RemoveFramesRecursively(Frame frame)167        {168            while (frame.ChildFrames.Count > 0)169            {170                RemoveFramesRecursively(frame.ChildFrames[0]);171            }172            frame.Detach();173            Frames.Remove(frame.Id);174            FrameDetached?.Invoke(this, new FrameEventArgs(frame));175        }176        private void OnFrameAttached(string frameId, string parentFrameId)177        {178            if (!Frames.ContainsKey(frameId) && Frames.ContainsKey(parentFrameId))179            {180                var parentFrame = Frames[parentFrameId];181                var frame = new Frame(_client, _page, parentFrame, frameId);182                Frames[frame.Id] = frame;183                FrameAttached?.Invoke(this, new FrameEventArgs(frame));184            }185        }186        private void HandleFrameTree(FrameTree frameTree)187        {188            if (!string.IsNullOrEmpty(frameTree.Frame.ParentId))189            {190                OnFrameAttached(frameTree.Frame.Id, frameTree.Frame.ParentId);191            }192            OnFrameNavigated(frameTree.Frame);193            if (frameTree.Childs != null)194            {195                foreach (var child in frameTree.Childs)196                {197                    HandleFrameTree(child);198                }199            }200        }201        #endregion202    }203}...PageWaitForNavigationTests.cs
Source:PageWaitForNavigationTests.cs  
...152            {153                frameAttachedTaskSource.SetResult(e.Frame);154            };155            var frame = await frameAttachedTaskSource.Task;156            var frameNavigatedTaskSource = new TaskCompletionSource<bool>();157            Page.FrameNavigated += (_, e) =>158            {159                if (e.Frame == frame)160                {161                    frameNavigatedTaskSource.TrySetResult(true);162                }163            };164            await frameNavigatedTaskSource.Task;165            await Task.WhenAll(166                frame.EvaluateFunctionAsync("() => window.stop()"),167                navigationTask168            );169        }170    }171}...LifecycleWatcher.cs
Source:LifecycleWatcher.cs  
...52            _lifecycleTaskWrapper = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);53            _terminationTaskWrapper = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);54            _terminationCancellationToken = new CancellationTokenSource();55            frameManager.LifecycleEvent += FrameManager_LifecycleEvent;56            frameManager.FrameNavigatedWithinDocument += NavigatedWithinDocument;57            frameManager.FrameDetached += OnFrameDetached;58            frameManager.NetworkManager.Request += OnRequest;59            frameManager.Client.Disconnected += OnClientDisconnected;60            CheckLifecycleComplete();61        }62        #region Properties63        public Task<bool> SameDocumentNavigationTask => _sameDocumentNavigationTaskWrapper.Task;64        public Task<bool> NewDocumentNavigationTask => _newDocumentNavigationTaskWrapper.Task;65        public Response NavigationResponse => _navigationRequest?.Response;66        public Task TimeoutOrTerminationTask => _terminationTaskWrapper.Task.WithTimeout(_timeout, cancellationToken: _terminationCancellationToken.Token);67        public Task LifecycleTask => _lifecycleTaskWrapper.Task;68        #endregion69        #region Private methods70        private void OnClientDisconnected(object sender, EventArgs e)71            => Terminate(new TargetClosedException("Navigation failed because browser has disconnected!", _frameManager.Client.CloseReason));72        private void FrameManager_LifecycleEvent(object sender, FrameEventArgs e) => CheckLifecycleComplete();73        private void OnFrameDetached(object sender, FrameEventArgs e)74        {75            var frame = e.Frame;76            if (_frame == frame)77            {78                Terminate(new PuppeteerException("Navigating frame was detached"));79                return;80            }81            CheckLifecycleComplete();82        }83        private void CheckLifecycleComplete()84        {85            // We expect navigation to commit.86            if (!CheckLifecycle(_frame, _expectedLifecycle))87            {88                return;89            }90            _lifecycleTaskWrapper.TrySetResult(true);91            if (_frame.LoaderId == _initialLoaderId && !_hasSameDocumentNavigation)92            {93                return;94            }95            if (_hasSameDocumentNavigation)96            {97                _sameDocumentNavigationTaskWrapper.TrySetResult(true);98            }99            if (_frame.LoaderId != _initialLoaderId)100            {101                _newDocumentNavigationTaskWrapper.TrySetResult(true);102            }103        }104        private void Terminate(PuppeteerException ex) => _terminationTaskWrapper.TrySetException(ex);105        private void OnRequest(object sender, RequestEventArgs e)106        {107            if (e.Request.Frame != _frame || !e.Request.IsNavigationRequest)108            {109                return;110            }111            _navigationRequest = e.Request;112        }113        private void NavigatedWithinDocument(object sender, FrameEventArgs e)114        {115            if (e.Frame != _frame)116            {117                return;118            }119            _hasSameDocumentNavigation = true;120            CheckLifecycleComplete();121        }122        private bool CheckLifecycle(Frame frame, IEnumerable<string> expectedLifecycle)123        {124            foreach (var item in expectedLifecycle)125            {126                if (!frame.LifecycleEvents.Contains(item))127                {128                    return false;129                }130            }131            foreach (var child in frame.ChildFrames)132            {133                if (!CheckLifecycle(child, expectedLifecycle))134                {135                    return false;136                }137            }138            return true;139        }140        public void Dispose() => Dispose(true);141        ~LifecycleWatcher() => Dispose(false);142        public void Dispose(bool disposing)143        {144            _frameManager.LifecycleEvent -= FrameManager_LifecycleEvent;145            _frameManager.FrameNavigatedWithinDocument -= NavigatedWithinDocument;146            _frameManager.FrameDetached -= OnFrameDetached;147            _frameManager.NetworkManager.Request -= OnRequest;148            _frameManager.Client.Disconnected -= OnClientDisconnected;149            _terminationCancellationToken.Cancel();150        }151        #endregion152    }153}...NavigatorWatcher.cs
Source:NavigatorWatcher.cs  
...52            _initialLoaderId = mainFrame.LoaderId;53            _timeout = timeout;54            _hasSameDocumentNavigation = false;55            frameManager.LifecycleEvent += CheckLifecycleComplete;56            frameManager.FrameNavigatedWithinDocument += NavigatedWithinDocument;57            frameManager.FrameDetached += OnFrameDetached;58            networkManager.Request += OnRequest;59            Connection.FromSession(client).Closed += (sender, e)60                => Terminate(new TargetClosedException("Navigation failed because browser has disconnected!"));61            _sameDocumentNavigationTaskWrapper = new TaskCompletionSource<bool>();62            _newDocumentNavigationTaskWrapper = new TaskCompletionSource<bool>();63            _terminationTaskWrapper = new TaskCompletionSource<bool>();64            _timeoutTask = TaskHelper.CreateTimeoutTask(timeout);65        }66        #region Properties67        public Task<Task> NavigationTask { get; internal set; }68        public Task<bool> SameDocumentNavigationTask => _sameDocumentNavigationTaskWrapper.Task;69        public Task<bool> NewDocumentNavigationTask => _newDocumentNavigationTaskWrapper.Task;70        public Response NavigationResponse => _navigationRequest?.Response;71        public Task<Task> TimeoutOrTerminationTask => Task.WhenAny(_timeoutTask, _terminationTaskWrapper.Task);72        #endregion73        #region Private methods74        private void OnFrameDetached(object sender, FrameEventArgs e)75        {76            var frame = e.Frame;77            if (_frame == frame)78            {79                Terminate(new PuppeteerException("Navigating frame was detached"));80                return;81            }82            CheckLifecycleComplete(sender, e);83        }84        private void CheckLifecycleComplete(object sender, FrameEventArgs e)85        {86            // We expect navigation to commit.87            if (_frame.LoaderId == _initialLoaderId && !_hasSameDocumentNavigation)88            {89                return;90            }91            if (!CheckLifecycle(_frame, _expectedLifecycle))92            {93                return;94            }95            if (_hasSameDocumentNavigation)96            {97                _sameDocumentNavigationTaskWrapper.TrySetResult(true);98            }99            if (_frame.LoaderId != _initialLoaderId)100            {101                _newDocumentNavigationTaskWrapper.TrySetResult(true);102            }103        }104        private void Terminate(PuppeteerException ex) => _terminationTaskWrapper.TrySetException(ex);105        private void OnRequest(object sender, RequestEventArgs e)106        {107            if (e.Request.Frame != _frame || !e.Request.IsNavigationRequest)108            {109                return;110            }111            _navigationRequest = e.Request;112        }113        private void NavigatedWithinDocument(object sender, FrameEventArgs e)114        {115            if (e.Frame != _frame)116            {117                return;118            }119            _hasSameDocumentNavigation = true;120            CheckLifecycleComplete(sender, e);121        }122        private bool CheckLifecycle(Frame frame, IEnumerable<string> expectedLifecycle)123        {124            foreach (var item in expectedLifecycle)125            {126                if (!frame.LifecycleEvents.Contains(item))127                {...Navigated
Using AI Code Generation
1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3    Args = new string[] { "--no-sandbox" }4});5var page = await browser.NewPageAsync();6await page.EvaluateExpressionAsync("document.querySelector('input').value = 'puppeteer-sharp'");7await page.EvaluateExpressionAsync("document.querySelector('form').submit()");8await page.WaitForNavigationAsync();9var result = await page.EvaluateExpressionAsync("document.querySelector('.srg').children.length");10Console.WriteLine(result);11await browser.CloseAsync();12var browser = await Puppeteer.LaunchAsync(new LaunchOptions13{14    Args = new string[] { "--no-sandbox" }15});16var page = await browser.NewPageAsync();17await page.EvaluateExpressionAsync("document.querySelector('input').value = 'puppeteer-sharp'");18await page.EvaluateExpressionAsync("document.querySelector('form').submit()");19page.FrameManager.Navigated += (sender, args) =>20{21    Console.WriteLine("Page navigated to: " + args.Frame.Url);22};23await page.WaitForNavigationAsync();24var result = await page.EvaluateExpressionAsync("document.querySelector('.srg').children.length");25Console.WriteLine(result);26await browser.CloseAsync();Navigated
Using AI Code Generation
1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3    Args = new string[] { "--start-maximized" }4});5var page = await browser.NewPageAsync();6var frame = page.MainFrame;7await frame.WaitForSelectorAsync("input[title='Search']");8await frame.TypeAsync("input[title='Search']", "Puppeteer Sharp", new TypeOptions { Delay = 100 });9await frame.ClickAsync("input[value='Google Search']");10await frame.WaitForNavigationAsync();11await frame.WaitForSelectorAsync("a[href='Navigated
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5    {6        static async Task Main(string[] args)7        {8            {9                Args = new string[] { "--no-sandbox" }10            };11            using (var browser = await Puppeteer.LaunchAsync(options))12            {13                var page = await browser.NewPageAsync();14                page.FrameManager.Navigated += (sender, e) =>15                {16                    Console.WriteLine(e.Frame.Url);17                };18            }19        }20    }21}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!!
