Skip to content

Instantly share code, notes, and snippets.

@karlhorky
Forked from jeroenvisser101/cookies.js
Created March 24, 2021 12:22
Show Gist options
  • Save karlhorky/2d5e49a33f4ccc82b8678a75caa9cbe6 to your computer and use it in GitHub Desktop.
Save karlhorky/2d5e49a33f4ccc82b8678a75caa9cbe6 to your computer and use it in GitHub Desktop.
Set browser-wide cookies with Puppeteer
export const setCookies = async (page, cookies) => {
const items = cookies
.map(cookie => {
const item = Object.assign({}, cookie);
if (!item.value) item.value = "";
console.assert(!item.url, `Cookies must have a URL defined`);
console.assert(
item.url !== "about:blank",
`Blank page can not have cookie "${item.name}"`
);
console.assert(
!String.prototype.startsWith.call(item.url || "", "data:"),
`Data URL page can not have cookie "${item.name}"`
);
return item;
})
.filter(cookie => cookie.name);
await page.deleteCookie(...items);
if (items.length)
await page._client.send("Network.setCookies", { cookies: items });
};
export const getCookies = async page => {
const { cookies } = await page._client.send("Network.getAllCookies", {});
return cookies;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment