Best Puppeteer-sharp code snippet using PuppeteerSharp.Page.GetCookiesAsync
CookiesTests.cs
Source:CookiesTests.cs  
...16        [PuppeteerFact]17        public async Task ShouldReturnNoCookiesInPristineBrowserContext()18        {19            await Page.GoToAsync(TestConstants.EmptyPage);20            Assert.Empty(await Page.GetCookiesAsync());21        }22        [PuppeteerTest("cookies.spec.ts", "Page.cookies", "should get a cookie")]23        [SkipBrowserFact(skipFirefox: true)]24        public async Task ShouldGetACookie()25        {26            await Page.GoToAsync(TestConstants.EmptyPage);27            Assert.Empty(await Page.GetCookiesAsync());28            await Page.EvaluateExpressionAsync("document.cookie = 'username=John Doe'");29            var cookie = Assert.Single(await Page.GetCookiesAsync());30            Assert.Equal("username", cookie.Name);31            Assert.Equal("John Doe", cookie.Value);32            Assert.Equal("localhost", cookie.Domain);33            Assert.Equal("/", cookie.Path);34            Assert.Equal(cookie.Expires, -1);35            Assert.Equal(16, cookie.Size);36            Assert.False(cookie.HttpOnly);37            Assert.False(cookie.Secure);38            Assert.True(cookie.Session);39        }40        [PuppeteerTest("cookies.spec.ts", "Page.cookies", "should properly report httpOnly cookie")]41        [PuppeteerFact]42        public async Task ShouldProperlyReportHttpOnlyCookie()43        {44            Server.SetRoute("/empty.html", context =>45            {46                context.Response.Headers["Set-Cookie"] = "a=b; HttpOnly; Path=/";47                return Task.CompletedTask;48            });49            await Page.GoToAsync(TestConstants.EmptyPage);50            var cookies = await Page.GetCookiesAsync();51            Assert.Single(cookies);52            Assert.True(cookies[0].HttpOnly);53        }54        [PuppeteerTest("cookies.spec.ts", "Page.cookies", "should properly report \"Strict\" sameSite cookie")]55        [PuppeteerFact]56        public async Task ShouldProperlyReportSStrictSameSiteCookie()57        {58            Server.SetRoute("/empty.html", context =>59            {60                context.Response.Headers["Set-Cookie"] = "a=b; SameSite=Strict";61                return Task.CompletedTask;62            });63            await Page.GoToAsync(TestConstants.EmptyPage);64            var cookies = await Page.GetCookiesAsync();65            Assert.Single(cookies);66            Assert.Equal(SameSite.Strict, cookies[0].SameSite);67        }68        [PuppeteerTest("cookies.spec.ts", "Page.cookies", "should properly report \"Lax\" sameSite cookie")]69        [PuppeteerFact]70        public async Task ShouldProperlyReportLaxSameSiteCookie()71        {72            Server.SetRoute("/empty.html", context =>73            {74                context.Response.Headers["Set-Cookie"] = "a=b; SameSite=Lax";75                return Task.CompletedTask;76            });77            await Page.GoToAsync(TestConstants.EmptyPage);78            var cookies = await Page.GetCookiesAsync();79            Assert.Single(cookies);80            Assert.Equal(SameSite.Lax, cookies[0].SameSite);81        }82        [PuppeteerTest("cookies.spec.ts", "Page.cookies", "should get multiple cookies")]83        [SkipBrowserFact(skipFirefox: true)]84        public async Task ShouldGetMultipleCookies()85        {86            await Page.GoToAsync(TestConstants.EmptyPage);87            Assert.Empty(await Page.GetCookiesAsync());88            await Page.EvaluateFunctionAsync(@"() => {89                document.cookie = 'username=John Doe';90                document.cookie = 'password=1234';91            }");92            var cookies = (await Page.GetCookiesAsync()).OrderBy(c => c.Name).ToList();93            var cookie = cookies[0];94            Assert.Equal("password", cookie.Name);95            Assert.Equal("1234", cookie.Value);96            Assert.Equal("localhost", cookie.Domain);97            Assert.Equal("/", cookie.Path);98            Assert.Equal(cookie.Expires, -1);99            Assert.Equal(12, cookie.Size);100            Assert.False(cookie.HttpOnly);101            Assert.False(cookie.Secure);102            Assert.True(cookie.Session);103            cookie = cookies[1];104            Assert.Equal("username", cookie.Name);105            Assert.Equal("John Doe", cookie.Value);106            Assert.Equal("localhost", cookie.Domain);107            Assert.Equal("/", cookie.Path);108            Assert.Equal(cookie.Expires, -1);109            Assert.Equal(16, cookie.Size);110            Assert.False(cookie.HttpOnly);111            Assert.False(cookie.Secure);112            Assert.True(cookie.Session);113        }114        [PuppeteerTest("cookies.spec.ts", "Page.cookies", "should get cookies from multiple urls")]115        [SkipBrowserFact(skipFirefox: true)]116        public async Task ShouldGetCookiesFromMultipleUrls()117        {118            await Page.SetCookieAsync(119                new CookieParam120                {121                    Url = "https://foo.com",122                    Name = "doggo",123                    Value = "woofs"124                },125                new CookieParam126                {127                    Url = "https://bar.com",128                    Name = "catto",129                    Value = "purrs"130                },131                new CookieParam132                {133                    Url = "https://baz.com",134                    Name = "birdo",135                    Value = "tweets"136                }137            );138            var cookies = (await Page.GetCookiesAsync("https://foo.com", "https://baz.com")).OrderBy(c => c.Name).ToList();139            Assert.Equal(2, cookies.Count);140            var cookie = cookies[0];141            Assert.Equal("birdo", cookie.Name);142            Assert.Equal("tweets", cookie.Value);143            Assert.Equal("baz.com", cookie.Domain);144            Assert.Equal("/", cookie.Path);145            Assert.Equal(cookie.Expires, -1);146            Assert.Equal(11, cookie.Size);147            Assert.False(cookie.HttpOnly);148            Assert.True(cookie.Secure);149            Assert.True(cookie.Session);150            cookie = cookies[1];151            Assert.Equal("doggo", cookie.Name);152            Assert.Equal("woofs", cookie.Value);...DefaultBrowserContextTests.cs
Source:DefaultBrowserContextTests.cs  
...19            Page = await Context.NewPageAsync();20        }21        [PuppeteerTest("defaultbrowsercontext.spec.ts", "DefaultBrowserContext", "page.cookies() should work")]22        [PuppeteerFact]23        public async Task PageGetCookiesAsyncShouldWork()24        {25            await Page.GoToAsync(TestConstants.EmptyPage);26            await Page.EvaluateExpressionAsync("document.cookie = 'username=John Doe'");27            var cookie = (await Page.GetCookiesAsync()).First();28            Assert.Equal("username", cookie.Name);29            Assert.Equal("John Doe", cookie.Value);30            Assert.Equal("localhost", cookie.Domain);31            Assert.Equal("/", cookie.Path);32            Assert.Equal(-1, cookie.Expires);33            Assert.Equal(16, cookie.Size);34            Assert.False(cookie.HttpOnly);35            Assert.False(cookie.Secure);36            Assert.True(cookie.Session);37        }38        [PuppeteerTest("defaultbrowsercontext.spec.ts", "DefaultBrowserContext", "page.setCookie() should work")]39        [PuppeteerFact]40        public async Task PageSetCookiesAsyncShouldWork()41        {42            await Page.GoToAsync(TestConstants.EmptyPage);43            await Page.SetCookieAsync(new CookieParam44            {45                Name = "username",46                Value = "John Doe"47            });48            var cookie = (await Page.GetCookiesAsync()).First();49            Assert.Equal("username", cookie.Name);50            Assert.Equal("John Doe", cookie.Value);51            Assert.Equal("localhost", cookie.Domain);52            Assert.Equal("/", cookie.Path);53            Assert.Equal(-1, cookie.Expires);54            Assert.Equal(16, cookie.Size);55            Assert.False(cookie.HttpOnly);56            Assert.False(cookie.Secure);57            Assert.True(cookie.Session);58        }59        [PuppeteerTest("defaultbrowsercontext.spec.ts", "DefaultBrowserContext", "page.deleteCookie() should work")]60        [PuppeteerFact]61        public async Task PageDeleteCookieAsyncShouldWork()62        {63            await Page.GoToAsync(TestConstants.EmptyPage);64            await Page.SetCookieAsync(65                new CookieParam66                {67                    Name = "cookie1",68                    Value = "1"69                },70                new CookieParam71                {72                    Name = "cookie2",73                    Value = "2"74                });75            Assert.Equal("cookie1=1; cookie2=2", await Page.EvaluateExpressionAsync<string>("document.cookie"));76            await Page.DeleteCookieAsync(new CookieParam77            {78                Name = "cookie2"79            });80            Assert.Equal("cookie1=1", await Page.EvaluateExpressionAsync<string>("document.cookie"));81            var cookie = (await Page.GetCookiesAsync()).First();82            Assert.Equal("cookie1", cookie.Name);83            Assert.Equal("1", cookie.Value);84            Assert.Equal("localhost", cookie.Domain);85            Assert.Equal("/", cookie.Path);86            Assert.Equal(-1, cookie.Expires);87            Assert.Equal(8, cookie.Size);88            Assert.False(cookie.HttpOnly);89            Assert.False(cookie.Secure);90            Assert.True(cookie.Session);91        }92    }93}...ChromiumHelper.cs
Source:ChromiumHelper.cs  
...112        public async Task<string> GetS_Key()113        {114            if(page != null)115            {116                var cookies = await page.GetCookiesAsync();117                var sKey = cookies.Where(x => x.Name == "skey").FirstOrDefault();118                if (sKey == null)119                    return "";120                else121                    return sKey.Value;122            }123            return "";124        }125        public async void FreeChromiumHelper()126        {127            if (browser != null)128            {129                await browser.CloseAsync();130                browser.Disconnect();...WebPage.cs
Source:WebPage.cs  
...44            Request request = await _page.WaitForRequestAsync(predicate, options);45            IWebRequest webRequest = new WebRequest(request);46            return webRequest;47        }48        public async Task<CookieParam[]> GetCookiesAsync(params string[] urls)49        {50            return await _page.GetCookiesAsync(urls);51        }52        public async Task CloseAsync(PageCloseOptions options = null)53        {54            await _page.CloseAsync(options);55        }56        /// <summary>57        /// Perform required configuration for a page. (avoid cloudflare triggering, do not load images, etc)58        /// </summary>59        /// <returns></returns>60        private async Task ConfigurePage()61        {62            if (!_configured)63            {64                Dictionary<string, string> headerDictionary = new Dictionary<string, string>();...Browser.cs
Source:Browser.cs  
...48                await un.TypeAsync(AppConfig.un);49                await pw.TypeAsync(AppConfig.pw);50                await lgn.ClickAsync();51                await page.WaitForNavigationAsync();52                var cks = await page.GetCookiesAsync();53                AppConfig.cks = cks.ToList();//.Where(c => c.Domain == new Uri(page.Url).Host).ToList();54                AppConfig.sessId = AppConfig.cks.Where(c => c.Name == AppConfig.sessIdName).FirstOrDefault().Value;55                AppConfig.WriteOut($">> session id for crawl set to {AppConfig.sessId}");56                AppConfig.crawlStartUri = page.Url;57                return true;58            }59            catch(NavigationException ex)60            {61                AppConfig.ErrHand(ex, $"XX failed to navigate to url");62                return false;63            }64            catch (Exception ex)65            {66                AppConfig.ErrHand(ex);...Program.cs
Source:Program.cs  
...26            {27                using (var page = await browser.NewPageAsync())28                {29                    await page.GoToAsync("https://www.facebook.com", WaitUntilNavigation.Networkidle0);30                    var cookies = await page.GetCookiesAsync("https://facebook.com");31                    List<string> serializedCookies = new List<string>();32                    foreach (var cookie in cookies)33                    {34                        serializedCookies.Add(JsonConvert.SerializeObject(cookie));35                    }36                    File.WriteAllLines("cookies.dat", serializedCookies.ToArray());37                    Console.WriteLine("Cookies saved to cookies.dat!");38                }39            }40        }41    }42}...IWebPage.cs
Source:IWebPage.cs  
...13        Task<IWebResponse> GoToAsync(string url, int? timeout = null, WaitUntilNavigation[] waitUntil = null);14        Task SetUserAgentAsync(string userAgent);15        Task<string> GetContentAsync();16        Task<IWebRequest> WaitForRequestAsync(Func<Request, bool> predicate, WaitForOptions options = null);17        Task<CookieParam[]> GetCookiesAsync(params string[] urls);18        Task CloseAsync(PageCloseOptions options = null);19    }20}...PageStateFactory.cs
Source:PageStateFactory.cs  
...10    {11        public static async Task<PageState> Create(Page page)12        {13            var localStorage = await page.EvaluateExpressionAsync<IDictionary<string, string>>("(() => { var storage = {}; for(var i = 0; i < localStorage.length; i++) { storage[localStorage.key(i)] = localStorage.getItem(localStorage.key(i)); } return storage; })()");14            var cookies = (await page.GetCookiesAsync("https://web.whatsapp.com")).Select(cp => new Cookie(cp)).ToList();15            return new PageState(localStorage, cookies);16        }17    }18}...GetCookiesAsync
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using PuppeteerSharp;7{8    {9        static void Main(string[] args)10        {11            MainAsync().Wait();12        }13        static async Task MainAsync()14        {15            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);16            var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });17            var page = await browser.NewPageAsync();18            var cookies = await page.GetCookiesAsync();19            foreach (var cookie in cookies)20            {21                Console.WriteLine(cookie.Name + " " + cookie.Value);22            }23            await browser.CloseAsync();24        }25    }26}GetCookiesAsync
Using AI Code Generation
1var page = await browser.NewPageAsync();2foreach (var cookie in cookies)3{4    Console.WriteLine(cookie.Name);5}6var page = await browser.NewPageAsync();7var cookies = await page.GetCookiesAsync();8foreach (var cookie in cookies)9{10    Console.WriteLine(cookie.Name);11}12var page = await browser.NewPageAsync();13foreach (var cookie in cookies)14{15    Console.WriteLine(cookie.Name);16}17var page = await browser.NewPageAsync();18foreach (var cookie in cookies)19{20    Console.WriteLine(cookie.Name);21}22var page = await browser.NewPageAsync();23foreach (var cookie in cookies)24{25    Console.WriteLine(cookie.Name);26}27var page = await browser.NewPageAsync();28foreach (var cookie in cookies)29{30    Console.WriteLine(cookie.Name);31}32var page = await browser.NewPageAsync();GetCookiesAsync
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            var cookies = await page.GetCookiesAsync();14            foreach (var cookie in cookies)15            {16                Console.WriteLine(cookie);17            }18            await browser.CloseAsync();19        }20    }21}22using System;23using System.Threading.Tasks;24using PuppeteerSharp;25{26    {27        static async Task Main(string[] args)28        {29            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);30            var browser = await Puppeteer.LaunchAsync(new LaunchOptions31            {32            });33            var page = await browser.NewPageAsync();34            foreach (var cookie in cookies)35            {36                Console.WriteLine(cookie);37            }38            await browser.CloseAsync();39        }40    }41}42using System;43using System.Threading.Tasks;44using PuppeteerSharp;45{46    {47        static async Task Main(string[] args)48        {49            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);50            var browser = await Puppeteer.LaunchAsync(new LaunchOptions51            {52            });53            var page = await browser.NewPageAsync();54            await page.DeleteCookieAsync(new CookieParam55            {56            });57            await browser.CloseAsync();58        }59    }60}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!!
