Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing multiple cookies to puppeteer

By doing what user Md. Abu Taher suggested, i used a plugin called EditThisCookie to download the cookies from my browser.

The exported cookies are in JSON format, in fact it is an array of objects.

Is it possible to pass this array as a parameter to puppeteer? Can i pass an array of objects to page.setCookies() function?

like image 892
user1584421 Avatar asked May 29 '18 12:05

user1584421


2 Answers

You can use spread syntax await page.setCookie(...cookies);, where cookies is an array of cookie objects. https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagesetcookiecookies

Try it on https://try-puppeteer.appspot.com/

const browser = await puppeteer.launch();
const url = 'https://example.com';
const page = await browser.newPage();
await page.goto(url);

const cookies = [{
  'name': 'cookie1',
  'value': 'val1'
},{
  'name': 'cookie2',
  'value': 'val2'
},{
  'name': 'cookie3',
  'value': 'val3'
}];

await page.setCookie(...cookies);
const cookiesSet = await page.cookies(url);
console.log(JSON.stringify(cookiesSet));
await browser.close();
like image 99
lima_fil Avatar answered Oct 23 '22 03:10

lima_fil


You can call page.setCookie() with a spread operator to set multiple cookies at once.

However, make sure you call it before calling page.goto(url) because if you call it afterwards, the cookies will be set after the page has been loaded.

Calling page.setCookie() before page.goto(url) will require you to add a domain key to each cookie.

const cookies = [
  {name: 'cookie1', value: 'val1', domain: 'example.com'},
  {name: 'cookie2', value: 'val2', domain: 'example.com'},
  {name: 'cookie3', value: 'val3', domain: 'example.com'},
];

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setCookie(...cookies);
await page.goto('https://example.com');
await browser.close();
like image 20
Yoav Kadosh Avatar answered Oct 23 '22 01:10

Yoav Kadosh