Playwright get cookie

Viewed 9146

I need to get a JSSESSIONID cookie from one page and pass it to another. But when I try to fetch cookie with a playwright I got an empty array. Any ideas?

const browser = await playwright[browserType].launch();
const context = await browser.newContext();
        
const page = await context.newPage();
await page.goto(link);
       
const elementHandle = await page.$('#putfocushere');
await elementHandle.type(searchNumber);
console.log(await context.cookies(page.url()))
3 Answers

Have you tried doing await context.cookies() without specifying any origin? More than likely, this is happening because the value returned by page.url() isn't an exact match. You can try getting all the cookies and then filtering by your domain.

There is also context.storageState() that is now available in playwright, which will return all cookies and localstorage. See here.

You don't have to make a new context because the browser already has a context. When you try to get the cookies, you need to give the index to the context like so:

var cookies = await browser.Contexts[0].CookiesAsync();

The index "0" selects the context and gets the cookies

Access it through BrowserContext, which you can get through page.context(), e.g.

await page.context().cookies();
Related