Playwright setCookie

Hi everybody.

Can you help me with setCookie function. I use playwright driver, and when I try to call:
I.setCookie({cookie}). I have an error:

browserContext.addCookies: Cookie should have a url or a domain/path pair
at Connection.sendMessageToServer (node_modules\playwright\lib\client\connection.js:69:15)
at Proxy. (node_modules\playwright\lib\client\channelOwner.js:44:61)
at path\node_modules\playwright\lib\client\browserContext.js:109:33

Does someone know how to fix it?

Hey @HugWolf.

It would be useful to have a bit more context on this, but judging from your code and error it looks like you are trying to set a cookie before navigating to the website which is why you get that error.
Logically speaking to solve this you need to do the following steps:

  1. first navigate to your website without any cookie set
  2. set your cookies
  3. refresh the page
    You should now have your cookies setup and applied correctly.

You can do this as part of a helper and making use of hooks so that these actions are done before your actual test even starts.

Additionally, if this issue persists it might be something specific to Playwright and it will be worth opening a specific issue.
If you haven’t progressed too much you can always switch to something like WebDriverIO (WebDriver in CodeceptJS)

My code is part of custom-steps:

prepareBrowser: function (): void {
    I.amOnPage('/');
    I.setCookie({name: cookieName, value: cookieValue});
    I.refreshPage();
  },

I use it in Before step, it works on Puppeteer. I changed to Playwright and now I have the error.

Fixed by myself, maybe would be helpful for someone.

First try: A custom addCookie method as CodeceptJS:
But it doesn’t work for me. I mean no errors, but the cookie doesn’t appear.

interface TestCookie {
  name: string;
  value:   string;
}

addCookie(value: TestCookie) :void {
    const cookie: TestCookie[] = [];
    cookie.push(value);
    this.context.addCookies(cookie);
  }

Second try:
Success, it works for me, no errors and cookies add as normal

interface TestCookie {
  name: string;
  value:   string;
  domain?: string | undefined;
  path?: string | undefined;
}

addCookie(value: TestCookie) :void {
    value.path = "/";
    value.domain = "MyDomain";
    const cookie: TestCookie[] = [];
    cookie.push(value);
    this.context.addCookies(cookie);
  }
1 Like

Hi,
If we have this is object model framework, where are we expecting this code to sit?

interface TestCookie {
  name: string;
  value:   string;
  domain?: string | undefined;
  path?: string | undefined;
}

addCookie(value: TestCookie) :void {
    value.path = "/";
    value.domain = "MyDomain";
    const cookie: TestCookie[] = [];
    cookie.push(value);
    this.context.addCookies(cookie);
  }