Skip to content Skip to sidebar Skip to footer

Puppeteer Get 3rd-party Cookies

How can I get 3rd-party cookies from a website using Puppeteer? For first party, I know I can use: await page.cookies()

Solution 1:

I was interested to know the answer so have found a solution too, it works for the current versions of Chromium 75.0.3765.0 and puppeteer 1.15.0 (updated May 2nd 2019).

Using internal puppeteerpage._client methods we can make use of Chrome DevTools Protocol directly:

(async() => {
  const browser = await puppeteer.launch({});
  const page = await browser.newPage();
  await page.goto('https://stackoverflow.com', {waitUntil : 'networkidle2' });

  // Here we can get all of the cookies
  console.log(await page._client.send('Network.getAllCookies'));

})();

In the object returned there are cookies for google.com and imgur.com which we couldn't have obtained with normal browser javascript:

3d-party cookies!

Solution 2:

You can create a Chrome DevTools Protocol session on the page target using target.createCDPSession(). Then you can send Network.getAllCookies to obtain a list of all browser cookies.

The page.cookies() function will only return cookies for the current URL. So we can filter out the current page cookies from all of the browser cookies to obtain a list of third-party cookies only.

const client = await page.target().createCDPSession();
const all_browser_cookies = (await client.send('Network.getAllCookies')).cookies;
const current_url_cookies = await page.cookies();
const third_party_cookies = all_browser_cookies.filter(cookie => cookie.domain !== current_url_cookies[0].domain);

console.log(all_browser_cookies); // All Browser Cookiesconsole.log(current_url_cookies); // Current URL Cookiesconsole.log(third_party_cookies); // Third-Party Cookies

Solution 3:

const browser = await puppeteer.launch({});
  const page = await browser.newPage();
  await page.goto('https://www.stackoverflow.com/', {waitUntil : 'networkidle0' });
  // networkidle2, domcontentloaded, load are the options for wai until// Here we can get all of the cookiesvar content = await page._client.send('Network.getAllCookies');

  console.log(JSON.stringify(content, null, 4));

Post a Comment for "Puppeteer Get 3rd-party Cookies"