How to use DeleteCookieAsync method of PuppeteerSharp.Page class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Page.DeleteCookieAsync

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

DeleteCookieFunction.cs

Source: DeleteCookieFunction.cs Github

copy
1using System.Threading.Tasks;
2using Ertis.Scraper.Extensions;
3using PuppeteerSharp;
4
5namespace Ertis.Scraper.Interactions
6{
7	public class DeleteCookieFunction : FunctionBase, IInteractionFunction
8	{
9		#region Properties
10
11		public override string Name => "delete_cookie";
12
13		protected override FunctionParameter[] DefaultParameters
14		{
15			get
16			{
17				return new FunctionParameter[]
18				{
19					new FunctionParameter<string>
20					{
21						Name = "domain"
22					},
23					new FunctionParameter<int?>
24					{
25						Name = "expires"
26					},
27					new FunctionParameter<string>
28					{
29						Name = "name"
30					},
31					new FunctionParameter<string>
32					{
33						Name = "path"
34					},
35					new FunctionParameter<bool?>
36					{
37						Name = "secure"
38					},
39					new FunctionParameter<bool?>
40					{
41						Name = "session"
42					},
43					new FunctionParameter<int?>
44					{
45						Name = "size"
46					},
47					new FunctionParameter<string>
48					{
49						Name = "url"
50					},
51					new FunctionParameter<string>
52					{
53						Name = "value"
54					},
55					new FunctionParameter<bool?>
56					{
57						Name = "httpOnly"
58					},
59					new FunctionParameter<CookiePolicy?>
60					{
61						Name = "sameSite"
62					},
63				};
64			}
65		}
66
67		#endregion
68
69		#region Methods
70
71		public async Task ExecuteAsync(Page page)
72		{
73			await page.DeleteCookieAsync(this.GetCookieParam());
74		}
75
76		#endregion
77	}
78}
Full Screen

Web.cs

Source: Web.cs Github

copy
1//Open Tasks: Find a Way to use the headless Browser
2
3using System;
4using System.Threading.Tasks;
5using System.Collections.Generic;
6
7using PuppeteerSharp;
8
9namespace Schlauchboot.Ripper.Crunchyroll.Manager.Methods
10{
11    public class Web
12    {
13        /// <summary>
14        /// Fetches a Browser (Downloads one if no one is present).
15        /// </summary>
16        /// <returns>The Revision of the fetched Browser.</returns>
17        public async Task<RevisionInfo> GetBrowser()
18        {
19            return await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
20        }
21
22        /// <summary>
23        /// Fetches the Html for an Episode-Page.
24        /// </summary>
25        /// <param name="browserExecutablePath">The Path to a fetched Browser.</param>
26        /// <param name="webPage">The Url to an Episode-Page.</param>
27        /// <returns>The Html of the Page in Form of a String.</returns>
28        public async Task<string> GetWebPage(string browserExecutablePath, string webPage)
29        {
30            var browser = await CreateBrowser(browserExecutablePath);
31            try
32            {
33                var openPages = await browser.PagesAsync();
34                await openPages[0].GoToAsync(webPage);
35                var pageContent = await openPages[0].GetContentAsync();
36                return pageContent;
37            }
38            catch (Exception)
39            {
40                return String.Empty;
41            }
42            finally
43            {
44                await browser.CloseAsync();
45            }
46        }
47
48        /// <summary>
49        /// Fetches the Html for an Episode-Page.
50        /// </summary>
51        /// <param name="browserExecutablePath">The Path to a fetched Browser.</param>
52        /// <param name="webPage">The Url to an Episode-Page.</param>
53        /// <param name="cookie">A KeyValuePair which includes a Cookie Name/Value which will be inserted in the Browser.</param>
54        /// <returns>The Html of the Page in Form of a String.</returns>
55        public async Task<string> GetWebPage(string browserExecutablePath, string webPage, KeyValuePair<string, string> cookie)
56        {
57            var browser = await CreateBrowser(browserExecutablePath);
58            try
59            {
60                var openPages = await browser.PagesAsync();
61                await openPages[0].GoToAsync(webPage);
62                await openPages[0].DeleteCookieAsync();
63                await openPages[0].SetCookieAsync(new CookieParam()
64                {
65                    Domain = ".crunchyroll.com",
66                    Name = cookie.Key,
67                    Value = cookie.Value,
68                    HttpOnly = true
69                });
70                await openPages[0].ReloadAsync();
71                var pageContent = await browser.PagesAsync().Result[0].GetContentAsync();
72                return pageContent;
73            }
74            catch (Exception)
75            {
76                return String.Empty;
77            }
78            finally
79            {
80                await browser.CloseAsync();
81            }
82        }
83
84        /// <summary>
85        /// Creates and Launches a Browser.
86        /// </summary>
87        /// <param name="browserExecutablePath">Path to the executable File of the Browser.</param>
88        /// <returns>A Task for a Browser-Object.</returns>
89        private async Task<Browser> CreateBrowser(string browserExecutablePath)
90        {
91            return await Puppeteer.LaunchAsync(new LaunchOptions
92            {
93                ExecutablePath = browserExecutablePath,
94                Headless = false,
95                Args = new string[] { "--window-position=0,0", "--window-size=1,1" }
96            });
97        }
98    }
99}
100
Full Screen

AuthIntegrationTests.cs

Source: AuthIntegrationTests.cs Github

copy
1using System;
2using System.Linq;
3using System.Threading.Tasks;
4
5using FluentAssertions;
6
7using Microsoft.EntityFrameworkCore;
8using Microsoft.Extensions.DependencyInjection;
9
10using NUnit.Framework;
11
12using PuppeteerSharp;
13
14namespace Brighid.Identity.Auth
15{
16    [TestFixture]
17    [Category("Integration")]
18    public class AuthIntegrationTests
19    {
20        private const string Email = "[email protected]";
21        private const string Password = "Password123!";
22
23        [Test]
24        [Auto]
25        public async Task LoginRedirect(
26            AppFactory app,
27            Browser browser
28        )
29        {
30            var page = await browser.NewPageAsync();
31            await page.GoToAsync(app.RootUri.ToString());
32
33            // We should be redirected to login
34            new Uri(page.Url).AbsolutePath.Should().Be("/login");
35        }
36
37        [Test]
38        [Auto]
39        public async Task SignupThenLogin(
40            AppFactory app,
41            Browser browser
42        )
43        {
44            var page = await browser.NewPageAsync();
45            await page.GoToAsync($"{app.RootUri}signup");
46            {
47                var emailField = await page.MainFrame.QuerySelectorAsync("#Email");
48                await emailField.TypeAsync(Email);
49
50                var passwordField = await page.MainFrame.QuerySelectorAsync("#Password");
51                await passwordField.TypeAsync(Password);
52
53                var confirmPasswordField = await page.MainFrame.QuerySelectorAsync("#ConfirmPassword");
54                await confirmPasswordField.TypeAsync(Password);
55
56                var submitButton = await page.MainFrame.QuerySelectorAsync("input[type=submit]");
57                await submitButton.ClickAsync();
58
59                await page.MainFrame.WaitForNavigationAsync();
60            }
61
62            {
63                using var scope = app.Services.CreateScope();
64                var dbContext = scope.ServiceProvider.GetRequiredService<DatabaseContext>();
65                var query = from user in dbContext.Users.AsQueryable() where user.Email == Email select user;
66                var exists = await query.AnyAsync();
67
68                exists.Should().Be(true);
69            }
70
71            {
72                var cookies = await page.GetCookiesAsync();
73                await page.DeleteCookieAsync(cookies);
74                await page.GoToAsync($"{app.RootUri}login", waitUntil: WaitUntilNavigation.DOMContentLoaded);
75            }
76
77            {
78                var emailField = await page.MainFrame.QuerySelectorAsync("#Email");
79                await emailField.TypeAsync(Email);
80
81                var passwordField = await page.MainFrame.QuerySelectorAsync("#Password");
82                await passwordField.TypeAsync(Password);
83
84                var submitButton = await page.MainFrame.QuerySelectorAsync("input[type=submit]");
85                await submitButton.ClickAsync();
86
87                await page.MainFrame.WaitForNavigationAsync();
88
89                var url = new Uri(page.Url);
90                url.AbsolutePath.Should().Be("/");
91            }
92        }
93    }
94}
95
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used method in Page

Trigger DeleteCookieAsync code on LambdaTest Cloud Grid

Execute automation tests with DeleteCookieAsync on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)