How to use LifecycleWatcher class of PuppeteerSharp package

Best Puppeteer-sharp code snippet using PuppeteerSharp.LifecycleWatcher

FrameManager.cs

Source:FrameManager.cs Github

copy

Full Screen

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

Full Screen

Full Screen

DOMWorld.cs

Source:DOMWorld.cs Github

copy

Full Screen

...104 document.open();105 document.write(html);106 document.close();107 }", html).ConfigureAwait(false);108 using (var watcher = new LifecycleWatcher(_frameManager, Frame, waitUntil, timeout))109 {110 var watcherTask = await Task.WhenAny(111 watcher.TimeoutOrTerminationTask,112 watcher.LifecycleTask).ConfigureAwait(false);113 await watcherTask.ConfigureAwait(false);114 }115 }116 internal async Task<ElementHandle> AddScriptTagAsync(AddTagOptions options)117 {118 const string addScriptUrl = @"async function addScriptUrl(url, type) {119 const script = document.createElement('script');120 script.src = url;121 if(type)122 script.type = type;...

Full Screen

Full Screen

LifecycleWatcher.cs

Source:LifecycleWatcher.cs Github

copy

Full Screen

...5using System.Diagnostics.Contracts;6using PuppeteerSharp.Helpers;7namespace PuppeteerSharp8{9 internal class LifecycleWatcher : IDisposable10 {11 private static readonly Dictionary<WaitUntilNavigation, string> _puppeteerToProtocolLifecycle =12 new Dictionary<WaitUntilNavigation, string>13 {14 [WaitUntilNavigation.Load] = "load",15 [WaitUntilNavigation.DOMContentLoaded] = "DOMContentLoaded",16 [WaitUntilNavigation.Networkidle0] = "networkIdle",17 [WaitUntilNavigation.Networkidle2] = "networkAlmostIdle"18 };19 private static readonly WaitUntilNavigation[] _defaultWaitUntil = { WaitUntilNavigation.Load };20 private readonly FrameManager _frameManager;21 private readonly Frame _frame;22 private readonly IEnumerable<string> _expectedLifecycle;23 private readonly int _timeout;24 private readonly string _initialLoaderId;25 private Request _navigationRequest;26 private bool _hasSameDocumentNavigation;27 private TaskCompletionSource<bool> _newDocumentNavigationTaskWrapper;28 private TaskCompletionSource<bool> _sameDocumentNavigationTaskWrapper;29 private TaskCompletionSource<bool> _lifecycleTaskWrapper;30 private TaskCompletionSource<bool> _terminationTaskWrapper;31 public LifecycleWatcher(32 FrameManager frameManager,33 Frame frame,34 WaitUntilNavigation[] waitUntil,35 int timeout)36 {37 _expectedLifecycle = (waitUntil ?? _defaultWaitUntil).Select(w =>38 {39 var protocolEvent = _puppeteerToProtocolLifecycle.GetValueOrDefault(w);40 Contract.Assert(protocolEvent != null, $"Unknown value for options.waitUntil: {w}");41 return protocolEvent;42 });43 _frameManager = frameManager;44 _frame = frame;45 _initialLoaderId = frame.LoaderId;46 _timeout = timeout;47 _hasSameDocumentNavigation = false;48 _sameDocumentNavigationTaskWrapper = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);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}...

Full Screen

Full Screen

LifecycleWatcher

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3{4 {5 static void Main(string[] args)6 {7 Console.WriteLine("Hello World!");8 var options = new LaunchOptions();9 options.Headless = true;10 options.IgnoreHTTPSErrors = true;11 options.DefaultViewport = null;12 var browser = Puppeteer.LaunchAsync(options).GetAwaiter().GetResult();13 var page = browser.NewPageAsync().GetAwaiter().GetResult();14 var content = page.GetContentAsync().GetAwaiter().GetResult();15 Console.WriteLine(content);16 page.CloseAsync().GetAwaiter().GetResult();17 browser.CloseAsync().GetAwaiter().GetResult();18 }19 }20}21using PuppeteerSharp;22using System;23{24 {25 static void Main(string[] args)26 {27 Console.WriteLine("Hello World!");28 var options = new LaunchOptions();29 options.Headless = true;30 options.IgnoreHTTPSErrors = true;31 options.DefaultViewport = null;32 var browser = Puppeteer.LaunchAsync(options).GetAwaiter().GetResult();33 var page = browser.NewPageAsync().GetAwaiter().GetResult();34 var content = page.GetContentAsync().GetAwaiter().GetResult();35 Console.WriteLine(content);36 page.CloseAsync().GetAwaiter().GetResult();37 browser.CloseAsync().GetAwaiter().GetResult();38 }39 }40}41using PuppeteerSharp;42using System;43{44 {45 static void Main(string[] args)46 {47 Console.WriteLine("Hello World!");48 var options = new LaunchOptions();49 options.Headless = true;50 options.IgnoreHTTPSErrors = true;51 options.DefaultViewport = null;52 var browser = Puppeteer.LaunchAsync(options).GetAwaiter().GetResult();53 var page = browser.NewPageAsync().GetAwaiter().GetResult();

Full Screen

Full Screen

LifecycleWatcher

Using AI Code Generation

copy

Full Screen

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 Args = new string[] { "--no-sandbox" }11 });12 var page = await browser.NewPageAsync();13 await page.WaitForSelectorAsync("input[title='Search']");14 await page.TypeAsync("input[title='Search']", "Puppeteer");15 await page.ClickAsync("input[value='Google Search']");16 await page.WaitForSelectorAsync("h3");17 var searchResult = await page.QuerySelectorAsync("h3");18 Console.WriteLine(await searchResult.GetContentAsync());19 await browser.CloseAsync();20 }21 }22}

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