Best Puppeteer-sharp code snippet using PuppeteerSharp.LifecycleWatcher.NavigatedWithinDocument
FrameManager.cs
Source:FrameManager.cs
...35 #region Properties36 internal event EventHandler<FrameEventArgs> FrameAttached;37 internal event EventHandler<FrameEventArgs> FrameDetached;38 internal event EventHandler<FrameEventArgs> FrameNavigated;39 internal event EventHandler<FrameEventArgs> FrameNavigatedWithinDocument;40 internal event EventHandler<FrameEventArgs> LifecycleEvent;41 internal CDPSession Client { get; }42 internal NetworkManager NetworkManager { get; }43 internal Frame MainFrame { get; set; }44 internal Page Page { get; }45 internal TimeoutSettings TimeoutSettings { get; }46 #endregion47 #region Public Methods48 internal static async Task<FrameManager> CreateFrameManagerAsync(49 CDPSession client,50 Page page,51 bool ignoreHTTPSErrors,52 TimeoutSettings timeoutSettings)53 {54 var frameManager = new FrameManager(client, page, ignoreHTTPSErrors, timeoutSettings);55 var getFrameTreeTask = client.SendAsync<PageGetFrameTreeResponse>("Page.getFrameTree");56 await Task.WhenAll(57 client.SendAsync("Page.enable"),58 getFrameTreeTask).ConfigureAwait(false);59 await frameManager.HandleFrameTreeAsync(new FrameTree(getFrameTreeTask.Result.FrameTree)).ConfigureAwait(false);60 await Task.WhenAll(61 client.SendAsync("Page.setLifecycleEventsEnabled", new PageSetLifecycleEventsEnabledRequest { Enabled = true }),62 client.SendAsync("Runtime.enable"),63 frameManager.NetworkManager.InitializeAsync()).ConfigureAwait(false);64 await frameManager.EnsureIsolatedWorldAsync().ConfigureAwait(false);65 return frameManager;66 }67 internal ExecutionContext ExecutionContextById(int contextId)68 {69 _contextIdToContext.TryGetValue(contextId, out var context);70 if (context == null)71 {72 _logger.LogError("INTERNAL ERROR: missing context with id = {ContextId}", contextId);73 }74 return context;75 }76 public async Task<Response> NavigateFrameAsync(Frame frame, string url, NavigationOptions options)77 {78 var referrer = string.IsNullOrEmpty(options.Referer)79 ? NetworkManager.ExtraHTTPHeaders?.GetValueOrDefault(RefererHeaderName)80 : options.Referer;81 var requests = new Dictionary<string, Request>();82 var timeout = options?.Timeout ?? TimeoutSettings.NavigationTimeout;83 using (var watcher = new LifecycleWatcher(this, frame, options?.WaitUntil, timeout))84 {85 try86 {87 var navigateTask = NavigateAsync(Client, url, referrer, frame.Id);88 var task = await Task.WhenAny(89 watcher.TimeoutOrTerminationTask,90 navigateTask).ConfigureAwait(false);91 await task;92 task = await Task.WhenAny(93 watcher.TimeoutOrTerminationTask,94 _ensureNewDocumentNavigation ? watcher.NewDocumentNavigationTask : watcher.SameDocumentNavigationTask95 ).ConfigureAwait(false);96 await task;97 }98 catch (Exception ex)99 {100 throw new NavigationException(ex.Message, ex);101 }102 return watcher.NavigationResponse;103 }104 }105 private async Task NavigateAsync(CDPSession client, string url, string referrer, string frameId)106 {107 var response = await client.SendAsync<PageNavigateResponse>("Page.navigate", new PageNavigateRequest108 {109 Url = url,110 Referrer = referrer ?? string.Empty,111 FrameId = frameId112 }).ConfigureAwait(false);113 _ensureNewDocumentNavigation = !string.IsNullOrEmpty(response.LoaderId);114 if (!string.IsNullOrEmpty(response.ErrorText))115 {116 throw new NavigationException(response.ErrorText, url);117 }118 }119 public async Task<Response> WaitForFrameNavigationAsync(Frame frame, NavigationOptions options = null)120 {121 var timeout = options?.Timeout ?? TimeoutSettings.NavigationTimeout;122 using (var watcher = new LifecycleWatcher(this, frame, options?.WaitUntil, timeout))123 {124 var raceTask = await Task.WhenAny(125 watcher.NewDocumentNavigationTask,126 watcher.SameDocumentNavigationTask,127 watcher.TimeoutOrTerminationTask128 ).ConfigureAwait(false);129 await raceTask;130 return watcher.NavigationResponse;131 }132 }133 #endregion134 #region Private Methods135 private async void Client_MessageReceived(object sender, MessageEventArgs e)136 {137 try138 {139 switch (e.MessageID)140 {141 case "Page.frameAttached":142 OnFrameAttached(e.MessageData.ToObject<PageFrameAttachedResponse>());143 break;144 case "Page.frameNavigated":145 await OnFrameNavigatedAsync(e.MessageData.ToObject<PageFrameNavigatedResponse>(true).Frame).ConfigureAwait(false);146 break;147 case "Page.navigatedWithinDocument":148 OnFrameNavigatedWithinDocument(e.MessageData.ToObject<NavigatedWithinDocumentResponse>(true));149 break;150 case "Page.frameDetached":151 OnFrameDetached(e.MessageData.ToObject<BasicFrameResponse>(true));152 break;153 case "Page.frameStoppedLoading":154 OnFrameStoppedLoading(e.MessageData.ToObject<BasicFrameResponse>(true));155 break;156 case "Runtime.executionContextCreated":157 await OnExecutionContextCreatedAsync(e.MessageData.ToObject<RuntimeExecutionContextCreatedResponse>(true).Context);158 break;159 case "Runtime.executionContextDestroyed":160 OnExecutionContextDestroyed(e.MessageData.ToObject<RuntimeExecutionContextDestroyedResponse>(true).ExecutionContextId);161 break;162 case "Runtime.executionContextsCleared":163 OnExecutionContextsCleared();164 break;165 case "Page.lifecycleEvent":166 OnLifeCycleEvent(e.MessageData.ToObject<LifecycleEventResponse>(true));167 break;168 default:169 break;170 }171 }172 catch (Exception ex)173 {174 var message = $"Connection failed to process {e.MessageID}. {ex.Message}. {ex.StackTrace}";175 _logger.LogError(ex, message);176 Client.Close(message);177 }178 }179 private void OnFrameStoppedLoading(BasicFrameResponse e)180 {181 if (_frames.TryGetValue(e.FrameId, out var frame))182 {183 frame.OnLoadingStopped();184 LifecycleEvent?.Invoke(this, new FrameEventArgs(frame));185 }186 }187 private void OnLifeCycleEvent(LifecycleEventResponse e)188 {189 if (_frames.TryGetValue(e.FrameId, out var frame))190 {191 frame.OnLifecycleEvent(e.LoaderId, e.Name);192 LifecycleEvent?.Invoke(this, new FrameEventArgs(frame));193 }194 }195 private void OnExecutionContextsCleared()196 {197 while (_contextIdToContext.Count > 0)198 {199 var contextItem = _contextIdToContext.ElementAt(0);200 _contextIdToContext.Remove(contextItem.Key);201 if (contextItem.Value.World != null)202 {203 contextItem.Value.World.SetContext(null);204 }205 }206 }207 private void OnExecutionContextDestroyed(int executionContextId)208 {209 _contextIdToContext.TryGetValue(executionContextId, out var context);210 if (context != null)211 {212 _contextIdToContext.Remove(executionContextId);213 if (context.World != null)214 {215 context.World.SetContext(null);216 }217 }218 }219 private async Task OnExecutionContextCreatedAsync(ContextPayload contextPayload)220 {221 var frameId = contextPayload.AuxData?.FrameId;222 var frame = !string.IsNullOrEmpty(frameId) ? await GetFrameAsync(frameId).ConfigureAwait(false) : null;223 DOMWorld world = null;224 if (frame != null)225 {226 if (contextPayload.AuxData?.IsDefault == true)227 {228 world = frame.MainWorld;229 }230 else if (contextPayload.Name == UtilityWorldName && !frame.SecondaryWorld.HasContext)231 {232 // In case of multiple sessions to the same target, there's a race between233 // connections so we might end up creating multiple isolated worlds.234 // We can use either.235 world = frame.SecondaryWorld;236 }237 }238 if (contextPayload.AuxData?.Type == DOMWorldType.Isolated)239 {240 _isolatedWorlds.Add(contextPayload.Name);241 }242 var context = new ExecutionContext(Client, contextPayload, world);243 if (world != null)244 {245 world.SetContext(context);246 }247 _contextIdToContext[contextPayload.Id] = context;248 }249 private void OnFrameDetached(BasicFrameResponse e)250 {251 if (_frames.TryGetValue(e.FrameId, out var frame))252 {253 RemoveFramesRecursively(frame);254 }255 }256 private async Task OnFrameNavigatedAsync(FramePayload framePayload)257 {258 var isMainFrame = string.IsNullOrEmpty(framePayload.ParentId);259 var frame = isMainFrame ? MainFrame : await GetFrameAsync(framePayload.Id);260 Contract.Assert(isMainFrame || frame != null, "We either navigate top level or have old version of the navigated frame");261 // Detach all child frames first.262 if (frame != null)263 {264 while (frame.ChildFrames.Count > 0)265 {266 RemoveFramesRecursively(frame.ChildFrames[0]);267 }268 }269 // Update or create main frame.270 if (isMainFrame)271 {272 if (frame != null)273 {274 // Update frame id to retain frame identity on cross-process navigation.275 if (frame.Id != null)276 {277 _frames.TryRemove(frame.Id, out _);278 }279 frame.Id = framePayload.Id;280 }281 else282 {283 // Initial main frame navigation.284 frame = new Frame(this, Client, null, framePayload.Id);285 }286 _asyncFrames.AddItem(framePayload.Id, frame);287 MainFrame = frame;288 }289 // Update frame payload.290 frame.Navigated(framePayload);291 FrameNavigated?.Invoke(this, new FrameEventArgs(frame));292 }293 internal Frame[] GetFrames() => _frames.Values.ToArray();294 private void OnFrameNavigatedWithinDocument(NavigatedWithinDocumentResponse e)295 {296 if (_frames.TryGetValue(e.FrameId, out var frame))297 {298 frame.NavigatedWithinDocument(e.Url);299 var eventArgs = new FrameEventArgs(frame);300 FrameNavigatedWithinDocument?.Invoke(this, eventArgs);301 FrameNavigated?.Invoke(this, eventArgs);302 }303 }304 private void RemoveFramesRecursively(Frame frame)305 {306 while (frame.ChildFrames.Count > 0)307 {308 RemoveFramesRecursively(frame.ChildFrames[0]);309 }310 frame.Detach();311 _frames.TryRemove(frame.Id, out _);312 FrameDetached?.Invoke(this, new FrameEventArgs(frame));313 }314 private void OnFrameAttached(PageFrameAttachedResponse frameAttached)...
LifecycleWatcher.cs
Source:LifecycleWatcher.cs
...49 _newDocumentNavigationTaskWrapper = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);50 _lifecycleTaskWrapper = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);51 _terminationTaskWrapper = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);52 frameManager.LifecycleEvent += FrameManager_LifecycleEvent;53 frameManager.FrameNavigatedWithinDocument += NavigatedWithinDocument;54 frameManager.FrameDetached += OnFrameDetached;55 frameManager.NetworkManager.Request += OnRequest;56 frameManager.Client.Disconnected += OnClientDisconnected;57 CheckLifecycleComplete();58 }59 #region Properties60 public Task<Task> NavigationTask { get; internal set; }61 public Task<bool> SameDocumentNavigationTask => _sameDocumentNavigationTaskWrapper.Task;62 public Task<bool> NewDocumentNavigationTask => _newDocumentNavigationTaskWrapper.Task;63 public Response NavigationResponse => _navigationRequest?.Response;64 public Task TimeoutOrTerminationTask65 => _terminationTaskWrapper.Task.WithTimeout(_timeout);66 public Task LifecycleTask => _lifecycleTaskWrapper.Task;67 #endregion68 #region Private methods69 private void OnClientDisconnected(object sender, EventArgs e)70 => Terminate(new TargetClosedException("Navigation failed because browser has disconnected!", _frameManager.Client.CloseReason));71 void FrameManager_LifecycleEvent(object sender, FrameEventArgs e) => CheckLifecycleComplete();7273 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 }150 #endregion151 }152}...
NavigatedWithinDocument
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 MainAsync().Wait();9 }10 static async Task MainAsync()11 {12 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))13 {14 using (var page = await browser.NewPageAsync())15 {16 var watcher = page.GetLifecycleWatcher();17 watcher.NavigatedWithinDocument += Watcher_NavigatedWithinDocument;
NavigatedWithinDocument
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 });11 var page = await browser.NewPageAsync();12 var watcher = page.WaitForNavigationAsync(LifecycleEvent.NavigatedWithinDocument);13 await watcher;14 await browser.CloseAsync();15 }16 }17}
NavigatedWithinDocument
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var options = new LaunchOptions { Headless = true };9 using (var browser = await Puppeteer.LaunchAsync(options))10 using (var page = await browser.NewPageAsync())11 {12 page.LifecycleWatcher.NavigatedWithinDocument += (sender, e) => Console.WriteLine("NavigatedWithinDocument");13 }14 }15 }16}
NavigatedWithinDocument
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 MainAsync().GetAwaiter().GetResult();9 }10 static async Task MainAsync()11 {12 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);13 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))14 using (var page = await browser.NewPageAsync())15 {16 await page.WaitForSelectorAsync("input[title='Search']");17 await page.ClickAsync("input[title='Search']");18 await page.TypeAsync("input[title='Search']", "Puppeteer");19 await page.WaitForSelectorAsync("input[value='Google Search']");20 await page.ClickAsync("input[value='Google Search']");21 await page.WaitForSelectorAsync("h3");22 var h3 = await page.QuerySelectorAsync("h3");23 await h3.ClickAsync();24 await page.WaitForNavigationAsync(new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Networkidle0 } });25 await page.WaitForSelectorAsync("h1");26 var h1 = await page.QuerySelectorAsync("h1");27 Console.WriteLine(await h1.EvaluateFunctionAsync<string>("node => node.innerText"));28 }29 }30 }31}
NavigatedWithinDocument
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 Console.WriteLine("Hello World!");9 }10 public static async Task NavigatedWithinDocument()11 {12 var options = new LaunchOptions { Headless = false };13 using (var browser = await Puppeteer.LaunchAsync(options))14 using (var page = await browser.NewPageAsync())15 {16 var watcher = page.GetLifecycleWatcher();17 watcher.NavigatedWithinDocument += Watcher_NavigatedWithinDocument;18 }19 }20 private static void Watcher_NavigatedWithinDocument(object sender, EventArgs e)21 {22 Console.WriteLine("Navigated within document");23 }24 }25}
NavigatedWithinDocument
Using AI Code Generation
1var page = await browser.NewPageAsync();2await page.WaitForNavigationAsync();3await page.WaitForNavigationAsync();4await page.WaitForNavigationAsync();5await page.WaitForNavigationAsync(new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Networkidle0 } });6await page.WaitForNavigationAsync(new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Networkidle0 } });7await page.WaitForNavigationAsync(new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Networkidle0 } });8var page = await browser.NewPageAsync();9await page.WaitForNavigationAsync(new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Networkidle0 } });10await page.WaitForNavigationAsync(new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Networkidle0 } });11await page.WaitForNavigationAsync(new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Networkidle0 } });12var page = await browser.NewPageAsync();13await page.WaitForNavigationAsync(new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Networkidle0 } });14await page.WaitForNavigationAsync(new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Networkidle0 } });15await page.WaitForNavigationAsync(new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Networkidle0 } });16var page = await browser.NewPageAsync();17await page.WaitForNavigationAsync(new NavigationOptions { WaitUntil = new[] { WaitUntil
NavigatedWithinDocument
Using AI Code Generation
1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3 Args = new string[] { "--no-sandbox", "--disable-setuid-sandbox" }4});5var page = await browser.NewPageAsync();6await page.TypeAsync("input[name='q']", "puppeteer-sharp");7await page.Keyboard.PressAsync("Enter");8await page.WaitForNavigationAsync();9await page.ClickAsync("h3 a");10await page.WaitForNavigationAsync(new NavigationOptions11{12 WaitUntil = new[] { WaitUntilNavigation.Networkidle0 }13});14await page.ScreenshotAsync("screenshot.png");15var navigationTask = page.WaitForNavigationAsync();16await page.ClickAsync("a");17await navigationTask;18var navigationTask = page.WaitForNavigationAsync();19await page.ClickAsync("a");20await navigationTask;21var navigationTask = page.WaitForNavigationAsync();22await page.ClickAsync("a");23await navigationTask;24var navigationTask = page.WaitForNavigationAsync();25await page.ClickAsync("a");26await navigationTask;27var navigationTask = page.WaitForNavigationAsync();28await page.ClickAsync("a");29await navigationTask;30var navigationTask = page.WaitForNavigationAsync();31await page.ClickAsync("a");32await navigationTask;
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!!