Best Puppeteer-sharp code snippet using PuppeteerSharp.Browser.BrowserContexts
Browser.cs
Source:Browser.cs
...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>...
BrowserContextTests.cs
Source:BrowserContextTests.cs
...18 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "should have default context")]19 [PuppeteerFact]20 public async Task ShouldHaveDefaultContext()21 {22 Assert.Single(Browser.BrowserContexts());23 var defaultContext = Browser.BrowserContexts()[0];24 Assert.False(defaultContext.IsIncognito);25 var exception = await Assert.ThrowsAsync<PuppeteerException>(defaultContext.CloseAsync);26 Assert.Same(defaultContext, Browser.DefaultContext);27 Assert.Contains("cannot be closed", exception.Message);28 }29 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "should create new incognito context")]30 [PuppeteerFact]31 public async Task ShouldCreateNewIncognitoContext()32 {33 Assert.Single(Browser.BrowserContexts());34 var context = await Browser.CreateIncognitoBrowserContextAsync();35 Assert.True(context.IsIncognito);36 Assert.Equal(2, Browser.BrowserContexts().Length);37 Assert.Contains(context, Browser.BrowserContexts());38 await context.CloseAsync();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());132 var context = await Browser.CreateIncognitoBrowserContextAsync();133 Assert.Equal(2, Browser.BrowserContexts().Length);134 var remoteBrowser = await Puppeteer.ConnectAsync(new ConnectOptions135 {136 BrowserWSEndpoint = Browser.WebSocketEndpoint137 });138 var contexts = remoteBrowser.BrowserContexts();139 Assert.Equal(2, contexts.Length);140 remoteBrowser.Disconnect();141 await context.CloseAsync();142 }143 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "should wait for target")]144 [SkipBrowserFact(skipFirefox: true)]145 public async Task ShouldWaitForTarget()146 {147 var context = await Browser.CreateIncognitoBrowserContextAsync();148 var targetPromise = context.WaitForTargetAsync((target) => target.Url == TestConstants.EmptyPage);149 var page = await context.NewPageAsync();150 await page.GoToAsync(TestConstants.EmptyPage);151 var promiseTarget = await targetPromise;152 var targetPage = await promiseTarget.PageAsync();...
BrowserContext.cs
Source:BrowserContext.cs
...5using PuppeteerSharp.Messaging;6namespace PuppeteerSharp7{8 /// <summary>9 /// BrowserContexts provide a way to operate multiple independent browser sessions. When a browser is launched, it has10 /// a single <see cref="BrowserContext"/> used by default. The method <see cref="Browser.NewPageAsync"/> creates a <see cref="Page"/> in the default <see cref="BrowserContext"/>11 /// </summary>12 public class BrowserContext13 {14 private readonly Connection _connection;15 private readonly string _id;16 internal BrowserContext(Connection connection, Browser browser, string contextId)17 {18 _connection = connection;19 Browser = browser;20 _id = contextId;21 }22 /// <summary>23 /// Raised when the url of a target changes...
BrowserContexts
Using AI Code Generation
1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3});4var context = await browser.CreateIncognitoBrowserContextAsync();5var page = await context.NewPageAsync();6await page.ScreenshotAsync("google.png");7await browser.CloseAsync();8var browser = await Puppeteer.LaunchAsync(new LaunchOptions9{10});11var page = await browser.NewPageAsync();12await page.ScreenshotAsync("google.png");13await browser.CloseAsync();14var browser = await Puppeteer.LaunchAsync(new LaunchOptions15{16});17var page = await browser.NewPageAsync();18await page.ScreenshotAsync("google.png");19await browser.CloseAsync();20var browser = await Puppeteer.LaunchAsync(new LaunchOptions21{22});23var page = await browser.NewPageAsync();24await page.ScreenshotAsync("google.png");25await browser.CloseAsync();26var browser = await Puppeteer.LaunchAsync(new LaunchOptions27{28});29var page = await browser.NewPageAsync();30await page.ScreenshotAsync("google.png");31await browser.CloseAsync();32var browser = await Puppeteer.LaunchAsync(new LaunchOptions33{34});35var page = await browser.NewPageAsync();36await page.ScreenshotAsync("google.png");37await browser.CloseAsync();38var browser = await Puppeteer.LaunchAsync(new LaunchOptions39{
BrowserContexts
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 await page.ScreenshotAsync("1.png");13 await page.SetViewportAsync(new ViewPortOptions14 {15 });16 await page.ScreenshotAsync("2.png");17 await browser.CloseAsync();18 }19 }20}21public Task<BrowserContext[]> BrowserContextsAsync();22using System;23using System.Threading.Tasks;24using PuppeteerSharp;25{26 {27 static async Task Main(string[] args)28 {29 var browser = await Puppeteer.LaunchAsync(new LaunchOptions30 {31 });32 var page = await browser.NewPageAsync();33 await page.ScreenshotAsync("1.png");34 await page.SetViewportAsync(new ViewPortOptions35 {36 });37 await page.ScreenshotAsync("2.png");38 var browserContexts = await browser.BrowserContextsAsync();39 foreach (var browserContext in browserContexts)40 {41 Console.WriteLine(browserContext.Targets());42 }43 await browser.CloseAsync();44 }45 }46}
BrowserContexts
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 context = await browser.CreateIncognitoBrowserContextAsync();12 var page = await context.NewPageAsync();13 Console.WriteLine("Hello World!");14 }15 }16 }17}18using System;19using System.Threading.Tasks;20using PuppeteerSharp;21{22 {23 static async Task Main(string[] args)24 {25 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);26 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))27 {28 var page = await browser.NewPageAsync();29 Console.WriteLine("Hello World!");30 }31 }32 }33}34using System;35using System.Threading.Tasks;36using PuppeteerSharp;37{38 {39 static async Task Main(string[] args)40 {41 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);42 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))43 {44 var context = await browser.CreateIncognitoBrowserContextAsync();45 var page = await context.NewPageAsync();46 Console.WriteLine("Hello World!");47 }48 }49 }50}51using System;52using System.Threading.Tasks;53using PuppeteerSharp;54{55 {56 static async Task Main(string[] args)57 {58 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);59 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions
BrowserContexts
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 {15 var context = await browser.CreateIncognitoBrowserContextAsync();16 var page = await context.NewPageAsync();17 await page.ScreenshotAsync("screenshot.png");18 await page.CloseAsync();19 }20 }21 }22}
BrowserContexts
Using AI Code Generation
1using System;2using System.Threading.Tasks;3{4 {5 static async Task Main(string[] args)6 {7 var browser = await Puppeteer.LaunchAsync(new LaunchOptions8 {9 {10 }11 });12 var context = await browser.CreateIncognitoBrowserContextAsync();13 var page = await context.NewPageAsync();14 await page.ScreenshotAsync("google.png");15 }16 }17}18using System;19using System.Threading.Tasks;20{21 {22 static async Task Main(string[] args)23 {24 var browser = await Puppeteer.LaunchAsync(new LaunchOptions25 {26 {27 }28 });29 var page = await browser.NewPageAsync();30 await page.ScreenshotAsync("google.png");31 }32 }33}34using System;35using System.Threading.Tasks;36{37 {38 static async Task Main(string[] args)39 {40 var browser = await Puppeteer.LaunchAsync(new LaunchOptions41 {42 {43 }44 });45 var context = await browser.CreateIncognitoBrowserContextAsync();46 var page = await context.NewPageAsync();47 await page.ScreenshotAsync("google.png");48 }49 }50}51using System;
BrowserContexts
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4using System.Collections.Generic;5using System.Linq;6{7 {8 static async Task Main(string[] args)9 {10 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);11 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions12 {13 }))14 {15 var pages = await browser.PagesAsync();16 var page = pages.FirstOrDefault();17 var context = await browser.CreateIncognitoBrowserContextAsync();18 var page2 = await context.NewPageAsync();19 var contexts = await browser.BrowserContextsAsync();20 foreach(var context in contexts)21 {22 Console.WriteLine(context.Targets);23 }
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!!