8

No matter what I do I get an error (either X.cookies is not a function or X.addCookies is not a function). I tried with context, page.context. browserContext etc. and it always ends up in the same way (ok, page.context as well as browserContext are undefined so error is different).

Context:

  • Playwright Version: 1.4.2
  • Operating System: Ubuntu 20.4
  • Node.js version: 10.15.1
  • Browser: Chromium

Code:

beforeEach(async function fn() {
this.timeout(20000);
browser = await chromium.launch({ headless: false });

const context = await browser.newContext();
page = await context.newPage();

await page
  .goto("http://localhost:4200/#/login", {
    waitUntil: "networkidle0",
  })
  .catch(() => {});

});

and in test:

      // await context.addCookies([
  //   { name: "csrftoken", value: cookieToken, path: "/" },
  //   { name: "sessionid", value: cookieSession, path: "/" },
  // ]);
  // await context.cookies();
ugabuga77
  • 681
  • 2
  • 11
  • 19

5 Answers5

6

right after you have your context, you should be able to use it as an example below: await context.addCookies([{name:"csrftoken", value: "mytokenvalue123", url: "your.application.url"}]);

keshav
  • 116
  • 1
  • 5
4

Setting cookies is pretty straightforward. You can to take advantage of the browser fixture.

test("Go Test An Application", async ({ page, browser }) => {

    // Using the browser fixture, you can get access to the BrowserContext
    const browserContext = await browser.newContext();

    // Add cookies to the browserContext
    const cookieVals = await setCookieVals();
    browserContext.addCookies(cookieVals)

    // First we will go to the Applicaiton URL
    const appURL = "https://stackoverflow.com/"
    page.goto(`${appURL}`);

    await page.waitForTimeout(3000);

});

export async function setCookieVals() {

    const cookies = [
        {name:"cookie1", value:"349", path:"/", domain:"stackoverflow"},
        {name:"cookie2", value:"1", path:"/", domain:"stackoverflow"},
        {name:"cookie3", value:"4000", path:"/", domain:"stackoverflow"},
    ]

    return cookies;
}
SoonerLR
  • 41
  • 2
  • 1
    How do I set `localhost` as domain ? For cookies in general the domain [should be omitted](https://stackoverflow.com/questions/1134290/cookies-on-localhost-with-explicit-domain), for playwright it is required. Or is playwright not supposed to be used on a local machine (i.e. before the deployment) ? – kca Dec 02 '22 at 11:05
3

I had to use context directly instead of browser context, otherwise some data would not load correctly (specifically in a SvelteKit app):

test('index page has expected content when logged in', async ({ page, context }) => {
    await context.addCookies([
        { name: 'sessionid', value: 'random', path: '/', domain: 'localhost' }
    ]);

    await page.goto('/');
    expect(await page.textContent('h1')).toBe('My title');
    console.log(await context.cookies());
});
  • Alternatively, I started with `browser`, created a new context, and then created a `newPage` off that context to get it working. I like this solution better although I haven't tried it. – frattaro Jan 24 '23 at 21:48
  • This works for me, thanks so much! – Rodyb Jul 29 '23 at 21:21
1

In order to set cookies with playwright, you would need to add both path & domain or url. Cf. the commented code in addCookies docs

**browserContext.addCookies(cookies)**

cookies <Array<Object>>
name <string>
value <string>
url <string> either url or domain / path are required. Optional. // ***** NOTE *****
domain <string> either url or domain / path are required Optional. // ***** NOTE *****
path <string> either url or domain / path are required Optional. // ***** NOTE *****
expires <number> Unix time in seconds. Optional.
httpOnly <boolean> Optional.
secure <boolean> Optional.
sameSite <"Strict"|"Lax"|"None"> Optional.

returns: <Promise<void>>

This is different behavior than standard behavior where domain is optional.

nrako
  • 2,952
  • 17
  • 30
-3

const context is set only inside the beforeEach method and it's not avilable in your test.

Define it as a global variable