Alexander Mills
Alexander Mills

Reputation: 100170

Adding cookies with Selenium Webdriver

I have the following sequence of Selenium code, written with Node.js:

   it('tests cookies', t => {
      driver.manage().getCookies().then(function (cookies) {
        console.log('all cookies => ', cookies);
      });
      driver.manage().addCookie({name:'foo', value: 'bar'});
      driver.manage().getCookies().then(function (cookies) {
        console.log('all cookies => ', cookies);
      });
      driver.manage().deleteCookie('foo');
      return driver.manage().getCookies().then(function (cookies) {
        console.log('all cookies => ', cookies);
      });
    });

and I get this output:

all cookies =>  []
all cookies =>  []
all cookies =>  []

anybody know why the addCookie functionality wouldn't work? I am not sure I understand why this wouldn't yield some cookies in the cookie jar.

Upvotes: 1

Views: 4128

Answers (1)

Ilia Frenkel
Ilia Frenkel

Reputation: 1977

The problem is that cookie domain is not defined. You need to navigate to some URL before you can work with cookies. Try adding driver.get('<some_url>') before getting all the cookies and after setting a new cookie.

it('tests cookies', t => {
      driver.get('127.0.0.1'); // <-- This will set the domain
      driver.manage().getCookies().then(function (cookies) {
        console.log('all cookies => ', cookies);
      });
      driver.manage().addCookie({name:'foo', value: 'bar'});
      driver.get('127.0.0.1'); // <-- Navigate again after setting a new cookie
      driver.manage().getCookies().then(function (cookies) {
        console.log('all cookies => ', cookies);
      });
      driver.manage().deleteCookie('foo');
      return driver.manage().getCookies().then(function (cookies) {
        console.log('all cookies => ', cookies);
      });
    });

See this as well: Selenium JS add cookie to request

Upvotes: 2

Related Questions