Best Puppeteer-sharp code snippet using PuppeteerSharp.BrowserContext.Targets
Browser.cs
Source:Browser.cs
...55 {56 Connection = connection;57 IgnoreHTTPSErrors = ignoreHTTPSErrors;58 DefaultViewport = defaultViewport;59 TargetsMap = new Dictionary<string, Target>();60 ScreenshotTaskQueue = new TaskQueue();61 DefaultContext = new BrowserContext(Connection, this, null);62 _contexts = contextIds.ToDictionary(keySelector: contextId => contextId,63 elementSelector: contextId => new BrowserContext(Connection, this, contextId));64 Connection.Closed += (object sender, EventArgs e) => Disconnected?.Invoke(this, new EventArgs());65 Connection.MessageReceived += Connect_MessageReceived;66 _chromiumProcess = chromiumProcess;67 _logger = Connection.LoggerFactory.CreateLogger<Browser>();68 }69 #region Private members70 internal readonly Dictionary<string, Target> TargetsMap;71 private readonly Dictionary<string, BrowserContext> _contexts;72 private readonly ILogger<Browser> _logger;73 private readonly ChromiumProcess _chromiumProcess;74 private Task _closeTask;75 #endregion76 #region Properties77 /// <summary>78 /// 79 /// </summary>80 public event EventHandler Closed;81 /// <summary>82 /// Raised when puppeteer gets disconnected from the Chromium instance. This might happen because one of the following83 /// - Chromium is closed or crashed84 /// - <see cref="Disconnect"/> method was called85 /// </summary>86 public event EventHandler Disconnected;87 /// <summary>88 /// Raised when the url of a target changes89 /// </summary>90 public event EventHandler<TargetChangedArgs> TargetChanged;91 /// <summary>92 /// Raised when a target is created, for example when a new page is opened by <c>window.open</c> <see href="https://developer.mozilla.org/en-US/docs/Web/API/Window/open"/> or <see cref="NewPageAsync"/>.93 /// </summary>94 public event EventHandler<TargetChangedArgs> TargetCreated;95 /// <summary>96 /// Raised when a target is destroyed, for example when a page is closed97 /// </summary>98 public event EventHandler<TargetChangedArgs> TargetDestroyed;99 /// <summary>100 /// Gets the Browser websocket url101 /// </summary>102 /// <remarks>103 /// Browser websocket endpoint which can be used as an argument to <see cref="Puppeteer.ConnectAsync(ConnectOptions, ILoggerFactory)"/>.104 /// The format is <c>ws://${host}:${port}/devtools/browser/[id]</c>105 /// You can find the <c>webSocketDebuggerUrl</c> from <c>http://${host}:${port}/json/version</c>.106 /// Learn more about the devtools protocol <see href="https://chromedevtools.github.io/devtools-protocol"/> 107 /// and the browser endpoint <see href="https://chromedevtools.github.io/devtools-protocol/#how-do-i-access-the-browser-target"/>108 /// </remarks>109 public string WebSocketEndpoint => Connection.Url;110 /// <summary>111 /// Gets the spawned browser process. Returns <c>null</c> if the browser instance was created with <see cref="Puppeteer.ConnectAsync(ConnectOptions, ILoggerFactory)"/> method.112 /// </summary>113 public Process Process => _chromiumProcess?.Process;114 /// <summary>115 /// Gets or Sets whether to ignore HTTPS errors during navigation116 /// </summary>117 public bool IgnoreHTTPSErrors { get; set; }118 /// <summary>119 /// Gets a value indicating if the browser is closed120 /// </summary>121 public bool IsClosed => _closeTask != null && _closeTask.IsCompleted && _closeTask.Exception != null;122 /// <summary>123 /// Returns the default browser context. The default browser context can not be closed.124 /// </summary>125 /// <value>The default context.</value>126 public BrowserContext DefaultContext { get; }127 internal TaskQueue ScreenshotTaskQueue { get; set; }128 internal Connection Connection { get; }129 internal ViewPortOptions DefaultViewport { get; }130 #endregion131 #region Public Methods132 /// <summary>133 /// Creates a new page134 /// </summary>135 /// <returns>Task which resolves to a new <see cref="Page"/> object</returns>136 public Task<Page> NewPageAsync() => DefaultContext.NewPageAsync();137 /// <summary>138 /// Returns An Array of all active targets139 /// </summary>140 /// <returns>An Array of all active targets</returns>141 public Target[] Targets() => TargetsMap.Values.Where(target => target.IsInitialized).ToArray();142 /// <summary>143 /// A target associated with the browser.144 /// </summary>145 public Target Target => Targets().FirstOrDefault(t => t.Type == TargetType.Browser);146 /// <summary>147 /// Creates a new incognito browser context. This won't share cookies/cache with other browser contexts.148 /// </summary>149 /// <returns>Task which resolves to a new <see cref="BrowserContext"/> object</returns>150 /// <example>151 /// <code>152 /// <![CDATA[153 /// using(var browser = await Puppeteer.LaunchAsync(new LaunchOptions()))154 /// {155 /// // Create a new incognito browser context.156 /// var context = await browser.CreateIncognitoBrowserContextAsync();157 /// // Create a new page in a pristine context.158 /// var page = await context.NewPageAsync();159 /// // Do stuff160 /// await page.GoToAsync("https://example.com");161 /// }162 /// ]]>163 /// </code>164 /// </example>165 public async Task<BrowserContext> CreateIncognitoBrowserContextAsync()166 {167 var response = await Connection.SendAsync<CreateBrowserContextResponse>("Target.createBrowserContext", new { }).ConfigureAwait(false);168 var context = new BrowserContext(Connection, this, response.BrowserContextId);169 _contexts[response.BrowserContextId] = context;170 return context;171 }172 /// <summary>173 /// Returns an array of all open <see cref="BrowserContext"/>. In a newly created browser, this will return a single instance of <see cref="BrowserContext"/>174 /// </summary>175 /// <returns>An array of <see cref="BrowserContext"/> objects</returns>176 public BrowserContext[] BrowserContexts()177 {178 var allContexts = new BrowserContext[_contexts.Count + 1];179 allContexts[0] = DefaultContext;180 _contexts.Values.CopyTo(allContexts, 1);181 return allContexts;182 }183 /// <summary>184 /// Returns a Task which resolves to an array of all open pages.185 /// Non visible pages, such as <c>"background_page"</c>, will not be listed here. You can find them using <see cref="Target.PageAsync"/>186 /// </summary>187 /// <returns>Task which resolves to an array of all open pages inside the Browser. 188 /// In case of multiple browser contexts, the method will return an array with all the pages in all browser contexts.189 /// </returns>190 public async Task<Page[]> PagesAsync()191 => (await Task.WhenAll(192 BrowserContexts().Select(t => t.PagesAsync())).ConfigureAwait(false)193 ).SelectMany(p => p).ToArray();194 /// <summary>195 /// Gets the browser's version196 /// </summary>197 /// <returns>For headless Chromium, this is similar to <c>HeadlessChrome/61.0.3153.0</c>. For non-headless, this is similar to <c>Chrome/61.0.3153.0</c></returns>198 /// <remarks>199 /// the format of <see cref="GetVersionAsync"/> might change with future releases of Chromium200 /// </remarks>201 public async Task<string> GetVersionAsync()202 {203 var version = await Connection.SendAsync("Browser.getVersion").ConfigureAwait(false);204 return version[MessageKeys.Product].AsString();205 }206 /// <summary>207 /// Gets the browser's original user agent208 /// </summary>209 /// <returns>Task which resolves to the browser's original user agent</returns>210 /// <remarks>211 /// Pages can override browser user agent with <see cref="Page.SetUserAgentAsync(string)"/>212 /// </remarks>213 public async Task<string> GetUserAgentAsync()214 {215 var version = await Connection.SendAsync("Browser.getVersion").ConfigureAwait(false);216 return version[MessageKeys.UserAgent].AsString();217 }218 /// <summary>219 /// Disconnects Puppeteer from the browser, but leaves the Chromium process running. After calling <see cref="Disconnect"/>, the browser object is considered disposed and cannot be used anymore220 /// </summary>221 public void Disconnect() => Connection.Dispose();222 /// <summary>223 /// Closes Chromium and all of its pages (if any were opened). The browser object itself is considered disposed and cannot be used anymore224 /// </summary>225 /// <returns>Task</returns>226 public Task CloseAsync() => _closeTask ?? (_closeTask = CloseCoreAsync());227 private async Task CloseCoreAsync()228 {229 try230 {231 try232 {233 // Initiate graceful browser close operation but don't await it just yet,234 // because we want to ensure chromium process shutdown first.235 var browserCloseTask = Connection.SendAsync("Browser.close", null);236 if (_chromiumProcess != null)237 {238 // Notify chromium process that exit is expected, but should be enforced if it239 // doesn't occur withing the close timeout.240 var closeTimeout = TimeSpan.FromMilliseconds(CloseTimeout);241 await _chromiumProcess.EnsureExitAsync(closeTimeout).ConfigureAwait(false);242 }243 // Now we can safely await the browser close operation without risking keeping chromium244 // process running for indeterminate period.245 await browserCloseTask.ConfigureAwait(false);246 }247 finally248 {249 Disconnect();250 }251 }252 catch (Exception ex)253 {254 _logger.LogError(ex, ex.Message);255 if (_chromiumProcess != null)256 {257 await _chromiumProcess.KillAsync().ConfigureAwait(false);258 }259 }260 Closed?.Invoke(this, new EventArgs());261 }262 #endregion263 #region Private Methods264 internal void ChangeTarget(Target target)265 {266 var args = new TargetChangedArgs { Target = target };267 TargetChanged?.Invoke(this, args);268 target.BrowserContext.OnTargetChanged(this, args);269 }270 internal async Task<Page> CreatePageInContextAsync(string contextId)271 {272 var args = new Dictionary<string, object> { [MessageKeys.Url] = "about:blank" };273 if (contextId != null)274 {275 args[MessageKeys.BrowserContextId] = contextId;276 }277 var targetId = (await Connection.SendAsync("Target.createTarget", args).ConfigureAwait(false))[MessageKeys.TargetId].ToString();278 var target = TargetsMap[targetId];279 await target.InitializedTask.ConfigureAwait(false);280 return await target.PageAsync().ConfigureAwait(false);281 }282 internal async Task DisposeContextAsync(string contextId)283 {284 await Connection.SendAsync("Target.disposeBrowserContext", new { browserContextId = contextId }).ConfigureAwait(false);285 _contexts.Remove(contextId);286 }287 private async void Connect_MessageReceived(object sender, MessageEventArgs e)288 {289 switch (e.MessageID)290 {291 case "Target.targetCreated":292 await CreateTargetAsync(e.MessageData.ToObject<TargetCreatedResponse>()).ConfigureAwait(false);293 return;294 case "Target.targetDestroyed":295 await DestroyTargetAsync(e.MessageData.ToObject<TargetDestroyedResponse>()).ConfigureAwait(false);296 return;297 case "Target.targetInfoChanged":298 ChangeTargetInfo(e.MessageData.ToObject<TargetCreatedResponse>());299 return;300 }301 }302 private void ChangeTargetInfo(TargetCreatedResponse e)303 {304 if (!TargetsMap.ContainsKey(e.TargetInfo.TargetId))305 {306 throw new InvalidTargetException("Target should exists before ChangeTargetInfo");307 }308 var target = TargetsMap[e.TargetInfo.TargetId];309 target.TargetInfoChanged(e.TargetInfo);310 }311 private async Task DestroyTargetAsync(TargetDestroyedResponse e)312 {313 if (!TargetsMap.ContainsKey(e.TargetId))314 {315 throw new InvalidTargetException("Target should exists before DestroyTarget");316 }317 var target = TargetsMap[e.TargetId];318 TargetsMap.Remove(e.TargetId);319 target.CloseTaskWrapper.TrySetResult(true);320 if (await target.InitializedTask.ConfigureAwait(false))321 {322 var args = new TargetChangedArgs { Target = target };323 TargetDestroyed?.Invoke(this, args);324 target.BrowserContext.OnTargetDestroyed(this, args);325 }326 }327 private async Task CreateTargetAsync(TargetCreatedResponse e)328 {329 var targetInfo = e.TargetInfo;330 var browserContextId = targetInfo.BrowserContextId;331 if (!(browserContextId != null && _contexts.TryGetValue(browserContextId, out var context)))332 {333 context = DefaultContext;334 }335 var target = new Target(336 e.TargetInfo,337 info => Connection.CreateSessionAsync(info),338 context);339 if (TargetsMap.ContainsKey(e.TargetInfo.TargetId))340 {341 _logger.LogError("Target should not exist before targetCreated");342 }343 TargetsMap[e.TargetInfo.TargetId] = target;344 if (await target.InitializedTask.ConfigureAwait(false))345 {346 var args = new TargetChangedArgs { Target = target };347 TargetCreated?.Invoke(this, args);348 context.OnTargetCreated(this, args);349 }350 }351 internal static async Task<Browser> CreateAsync(352 Connection connection,353 string[] contextIds,354 bool ignoreHTTPSErrors,355 ViewPortOptions defaultViewPort,356 ChromiumProcess chromiumProcess)357 {358 var browser = new Browser(connection, contextIds, ignoreHTTPSErrors, defaultViewPort, chromiumProcess);359 await connection.SendAsync("Target.setDiscoverTargets", new360 {361 discover = true362 }).ConfigureAwait(false);363 return browser;364 }365 #endregion366 #region IDisposable367 /// <summary>368 /// Closes <see cref="Connection"/> and any Chromium <see cref="Process"/> that was369 /// created by Puppeteer.370 /// </summary>371 public void Dispose() => _ = CloseAsync();372 #endregion373 }...
BrowserContextTests.cs
Source:BrowserContextTests.cs
...39 Assert.Single(Browser.BrowserContexts());40 }41 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "should close all belonging targets once closing context")]42 [PuppeteerFact]43 public async Task ShouldCloseAllBelongingTargetsOnceClosingContext()44 {45 Assert.Single((await Browser.PagesAsync()));46 var context = await Browser.CreateIncognitoBrowserContextAsync();47 await context.NewPageAsync();48 Assert.Equal(2, (await Browser.PagesAsync()).Length);49 Assert.Single((await context.PagesAsync()));50 await context.CloseAsync();51 Assert.Single((await Browser.PagesAsync()));52 }53 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "window.open should use parent tab context")]54 [SkipBrowserFact(skipFirefox: true)]55 public async Task WindowOpenShouldUseParentTabContext()56 {57 var context = await Browser.CreateIncognitoBrowserContextAsync();58 var page = await context.NewPageAsync();59 await page.GoToAsync(TestConstants.EmptyPage);60 var popupTargetCompletion = new TaskCompletionSource<Target>();61 Browser.TargetCreated += (_, e) => popupTargetCompletion.SetResult(e.Target);62 await Task.WhenAll(63 popupTargetCompletion.Task,64 page.EvaluateFunctionAsync("url => window.open(url)", TestConstants.EmptyPage)65 );66 var popupTarget = await popupTargetCompletion.Task;67 Assert.Same(context, popupTarget.BrowserContext);68 await context.CloseAsync();69 }70 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "should fire target events")]71 [SkipBrowserFact(skipFirefox: true)]72 public async Task ShouldFireTargetEvents()73 {74 var context = await Browser.CreateIncognitoBrowserContextAsync();75 var events = new List<string>();76 context.TargetCreated += (_, e) => events.Add("CREATED: " + e.Target.Url);77 context.TargetChanged += (_, e) => events.Add("CHANGED: " + e.Target.Url);78 context.TargetDestroyed += (_, e) => events.Add("DESTROYED: " + e.Target.Url);79 var page = await context.NewPageAsync();80 await page.GoToAsync(TestConstants.EmptyPage);81 await page.CloseAsync();82 Assert.Equal(new[] {83 $"CREATED: {TestConstants.AboutBlank}",84 $"CHANGED: {TestConstants.EmptyPage}",85 $"DESTROYED: {TestConstants.EmptyPage}"86 }, events);87 await context.CloseAsync();88 }89 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "should isolate local storage and cookies")]90 [PuppeteerFact]91 public async Task ShouldIsolateLocalStorageAndCookies()92 {93 // Create two incognito contexts.94 var context1 = await Browser.CreateIncognitoBrowserContextAsync();95 var context2 = await Browser.CreateIncognitoBrowserContextAsync();96 Assert.Empty(context1.Targets());97 Assert.Empty(context2.Targets());98 // Create a page in first incognito context.99 var page1 = await context1.NewPageAsync();100 await page1.GoToAsync(TestConstants.EmptyPage);101 await page1.EvaluateExpressionAsync(@"{102 localStorage.setItem('name', 'page1');103 document.cookie = 'name=page1';104 }");105 Assert.Single(context1.Targets());106 Assert.Empty(context2.Targets());107 // Create a page in second incognito context.108 var page2 = await context2.NewPageAsync();109 await page2.GoToAsync(TestConstants.EmptyPage);110 await page2.EvaluateExpressionAsync(@"{111 localStorage.setItem('name', 'page2');112 document.cookie = 'name=page2';113 }");114 Assert.Single(context1.Targets());115 Assert.Equal(page1.Target, context1.Targets()[0]);116 Assert.Single(context2.Targets());117 Assert.Equal(page2.Target, context2.Targets()[0]);118 // Make sure pages don't share localstorage or cookies.119 Assert.Equal("page1", await page1.EvaluateExpressionAsync<string>("localStorage.getItem('name')"));120 Assert.Equal("name=page1", await page1.EvaluateExpressionAsync<string>("document.cookie"));121 Assert.Equal("page2", await page2.EvaluateExpressionAsync<string>("localStorage.getItem('name')"));122 Assert.Equal("name=page2", await page2.EvaluateExpressionAsync<string>("document.cookie"));123 // Cleanup contexts.124 await Task.WhenAll(context1.CloseAsync(), context2.CloseAsync());125 Assert.Single(Browser.BrowserContexts());126 }127 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "should work across sessions")]128 [SkipBrowserFact(skipFirefox: true)]129 public async Task ShouldWorkAcrossSessions()130 {131 Assert.Single(Browser.BrowserContexts());...
PageEventsConsoleTests.cs
Source:PageEventsConsoleTests.cs
...163 await new Promise(x => frame.onload = x);164 // 3. After that, remove the iframe.165 frame.remove();166 }");167 var popupTarget = Page.BrowserContext.Targets().First(target => target != Page.Target);168 // 4. Connect to the popup and make sure it doesn't throw.169 await popupTarget.PageAsync();170 }171 }172}...
ConsoleTests.cs
Source:ConsoleTests.cs
...147 await new Promise(x => frame.onload = x);148 // 3. After that, remove the iframe.149 frame.remove();150 }");151 var popupTarget = Page.BrowserContext.Targets().First(target => target != Page.Target);152 // 4. Connect to the popup and make sure it doesn't throw.153 await popupTarget.PageAsync();154 }155 }156}...
BrowserContext.cs
Source:BrowserContext.cs
...46 /// <summary>47 /// Gets an array of all active targets inside the browser context 48 /// </summary>49 /// <returns>An array of all active targets inside the browser context</returns>50 public Target[] Targets() => Array.FindAll(Browser.Targets(), target => target.BrowserContext == this);51 /// <summary>52 /// This searches for a target in this specific browser context.53 /// <example>54 /// <code>55 /// <![CDATA[56 /// await page.EvaluateAsync("() => window.open('https://www.example.com/')");57 /// var newWindowTarget = await browserContext.WaitForTargetAsync((target) => target.Url == "https://www.example.com/");58 /// ]]>59 /// </code>60 /// </example>61 /// </summary>62 /// <param name="predicate">A function to be run for every target</param>63 /// <param name="options">options</param>64 /// <returns>Resolves to the first target found that matches the predicate function.</returns>65 public Task<Target> WaitForTargetAsync(Func<Target, bool> predicate, WaitForOptions options = null)66 => Browser.WaitForTargetAsync((target) => target.BrowserContext == this && predicate(target), options);67 /// <summary>68 /// An array of all pages inside the browser context.69 /// </summary>70 /// <returns>Task which resolves to an array of all open pages. 71 /// Non visible pages, such as <c>"background_page"</c>, will not be listed here. 72 /// You can find them using <see cref="Target.PageAsync"/>.</returns>73 public async Task<Page[]> PagesAsync()74 => (await Task.WhenAll(75 Targets().Where(t => t.Type == TargetType.Page).Select(t => t.PageAsync())).ConfigureAwait(false)76 ).Where(p => p != null).ToArray();77 /// <summary>78 /// Creates a new page79 /// </summary>80 /// <returns>Task which resolves to a new <see cref="Page"/> object</returns>81 public Task<Page> NewPageAsync() => Browser.CreatePageInContextAsync(_id);82 /// <summary>83 /// Closes the browser context. All the targets that belong to the browser context will be closed84 /// </summary>85 /// <returns>Task</returns>86 public Task CloseAsync()87 {88 if (_id == null)89 {...
Target.cs
Source:Target.cs
...57 /// <remarks>58 /// Top-level targets return <c>null</c>.59 /// </remarks>60 public Target Opener => _targetInfo.OpenerId != null ?61 Browser.TargetsMap.GetValueOrDefault(_targetInfo.OpenerId) : null;62 /// <summary>63 /// Get the browser the target belongs to.64 /// </summary>65 public Browser Browser => BrowserContext.Browser;66 /// <summary>67 /// Get the browser context the target belongs to.68 /// </summary>69 public BrowserContext BrowserContext { get; }70 internal Task<bool> InitializedTask => InitilizedTaskWrapper.Task;71 internal TaskCompletionSource<bool> InitilizedTaskWrapper { get; }72 internal Task CloseTask => CloseTaskWrapper.Task;73 internal TaskCompletionSource<bool> CloseTaskWrapper { get; }74 #endregion75 /// <summary>...
Targets
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 static async Task Main(string[] args)6 {7 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 Args = new string[] { "--no-sandbox" }11 });12 var page = await browser.NewPageAsync();13 var targets = await page.TargetsAsync();14 foreach (var target in targets)15 {16 Console.WriteLine(target.Url);17 }18 await browser.CloseAsync();19 }20}21public async Task<Target[]> TargetsAsync()22using System;23using System.Threading.Tasks;24using PuppeteerSharp;25{26 static async Task Main(string[] args)27 {28 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);29 var browser = await Puppeteer.LaunchAsync(new LaunchOptions30 {31 Args = new string[] { "--no-sandbox" }32 });33 var page = await browser.NewPageAsync();34 var targets = await page.TargetsAsync();35 foreach (var target in targets)36 {37 Console.WriteLine(target.Url);38 }39 await browser.CloseAsync();40 }41}42PuppeteerSharp.BrowserContext.TargetsAsync() Method returns the targets for the browser context. A target is
Targets
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 = false };9 using var browser = await Puppeteer.LaunchAsync(options);10 var page = await browser.NewPageAsync();11 var targets = await browser.TargetsAsync();12 foreach (var target in targets)13 {14 Console.WriteLine(target.Url);15 }16 Console.ReadLine();17 }18 }19}20using System;21using System.Threading.Tasks;22using PuppeteerSharp;23{24 {25 static async Task Main(string[] args)26 {27 var options = new LaunchOptions { Headless = false };28 using var browser = await Puppeteer.LaunchAsync(options);29 var page = await browser.NewPageAsync();30 var targets = await browser.TargetsAsync();
Targets
Using AI Code Generation
1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",4});5var page = await browser.NewPageAsync();6await page.TargetsAsync();7await page.ScreenshotAsync("google.png");8await browser.CloseAsync();9var browser = await Puppeteer.LaunchAsync(new LaunchOptions10{11 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",12});13var page = await browser.NewPageAsync();14await page.SetViewportAsync(new ViewPortOptions { Width = 1200, Height = 800 });15await page.ScreenshotAsync("google.png");16await browser.CloseAsync();17var browser = await Puppeteer.LaunchAsync(new LaunchOptions18{19 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",20});21var page = await browser.NewPageAsync();22await page.EmulateAsync(new EmulateOptions { ViewPort = new ViewPortOptions { Width = 1200, Height = 800 } });23await page.ScreenshotAsync("google.png");24await browser.CloseAsync();25var browser = await Puppeteer.LaunchAsync(new LaunchOptions26{27 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",28});29var page = await browser.NewPageAsync();
Targets
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;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 targets = await page.TargetsAsync();13 foreach (var target in targets)14 {15 Console.WriteLine(target.Url);16 }17 await browser.CloseAsync();18 }19 }20}21using PuppeteerSharp;22using System;23using System.Threading.Tasks;24{25 {26 static async Task Main(string[] args)27 {28 var browser = await Puppeteer.LaunchAsync(new LaunchOptions29 {30 });31 var page = await browser.NewPageAsync();32 page.TargetChanged += async (sender, e) =>33 {34 Console.WriteLine(e.Target.Url);35 };36 await browser.CloseAsync();37 }38 }39}40using PuppeteerSharp;41using System;42using System.Threading.Tasks;43{44 {45 static async Task Main(string[] args)46 {
Targets
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static void Main(string[] args)7 {8 MainAsync().Wait();9 }10 static async Task MainAsync()11 {12 var options = new LaunchOptions { Headless = false };13 using (var browser = await Puppeteer.LaunchAsync(options))14 {15 var page = await browser.NewPageAsync();16 var target = await browser.TargetsAsync();17 foreach (var item in target)18 {19 if (item.Type == TargetType.Page)20 {21 var page1 = await item.PageAsync();22 }23 }24 }25 }26 }27}28using PuppeteerSharp;29using System;30using System.Threading.Tasks;31{32 {33 static void Main(string[] args)34 {35 MainAsync().Wait();36 }37 static async Task MainAsync()38 {39 var options = new LaunchOptions { Headless = false };40 using (var browser = await Puppeteer.LaunchAsync(options))41 {42 var page = await browser.NewPageAsync();43 var target = await browser.TargetsAsync();44 foreach (var item in target)45 {46 if (item.Type == TargetType.Page)47 {48 var page1 = await item.PageAsync();49 }50 }51 }52 }53 }54}
Targets
Using AI Code Generation
1using PuppeteerSharp;2{3 static void Main(string[] args)4 {5 Run().Wait();6 }7 static async System.Threading.Tasks.Task Run()8 {9 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);10 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))11 using (var page = await browser.NewPageAsync())12 {13 var targets = await browser.TargetsAsync();14 foreach (var target in targets)15 {16 if (target.Type == TargetType.Page)17 {18 using (var targetPage = await target.PageAsync())19 {20 await targetPage.WaitForNavigationAsync();21 }22 }23 }24 }25 }26}
Targets
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9 var browser = await Puppeteer.LaunchAsync(new LaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 await page.ScreenshotAsync("google.png");14 var targets = await browser.TargetsAsync();15 foreach (var target in targets)16 {
Targets
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))10 {11 var page = await browser.NewPageAsync();12 var targets = await browser.TargetsAsync();13 foreach (var target in targets)14 {15 if (target.Type == TargetType.Page)16 {17 var targetPage = await target.PageAsync();18 Console.WriteLine(targetPage.Url);19 }20 }21 }22 }23 }24}
Targets
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 = false };9 using (var browser = await Puppeteer.LaunchAsync(options))10 {11 var page = await browser.NewPageAsync();12 var targets = await browser.TargetsAsync();13 foreach (var target in targets)14 {15 Console.WriteLine("Target URL: " + target.Url);16 Console.WriteLine("Target Type: " + target.Type);17 Console.WriteLine("Target TargetId: " + target.TargetId);18 Console.WriteLine("Target BrowserContext: " + target.BrowserContext);19 Console.WriteLine("Target Page: " + target.Page);20 Console.WriteLine("21");22 }23 }24 }25 }26}
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!!