How to handle cookies in Puppeteer?

To handle cookies in Puppeteer, you can use the following methods:

  1. Set cookies: You can set cookies in Puppeteer using the page.setCookie() method. This method takes an array of cookie objects as an argument. Each cookie object should have the required properties like name, value, domain, path, etc.
await page.setCookie({name: 'session', value: '12345', domain: 'example.com', path: '/'});
  1. Get cookies: You can get all the cookies set on a page using the page.cookies() method. This method returns an array of cookie objects that you can use for further processing.
const cookies = await page.cookies(); console.log(cookies);
  1. Delete cookies: To delete a specific cookie or all cookies, you can use the page.deleteCookie() method. If you want to delete a specific cookie, you can pass the cookie object as an argument. If you want to delete all cookies, you can call this method without any arguments.
await page.deleteCookie({name: 'session'}); // or await page.deleteCookie();
  1. Clear cookies: To clear all cookies from the page, you can use the page.clearCookies() method.
await page.clearCookies();

By using these methods, you can effectively handle cookies in Puppeteer and manage the state of your browser session as needed.