How to reliably set cookies on localhost using webdriver and Chrome? How to reliably set cookies on localhost using webdriver and Chrome? selenium selenium

How to reliably set cookies on localhost using webdriver and Chrome?


There are two workarounds that will work with Chrome and will not break Firefox.

First, use null instead of localhost as the cookie domain. Chrome will treat this as meaning "the same page as the current page's domain". Which is fine, since you need to make the browser visit a page before you're allowed to set the cookies anyway.

Second, clear the existing cookie before setting the new cookie (browser.manager().deleteCookie()). Chrome disallows (silently) changes to some cookies via the webdriver API. By deleting the cookie, you're then allowed to set it.

// cookieObj is a "tough.Cookie" instance in my casefunction setCookie(cookieObj) {   var domain = cookieObj.domain;   if (domain === 'localhost') {      domain = null;   }   var mgr = browser.manage();   var cName = cookieObj.key;   var cookieProm = mgr.deleteCookie(cName).then(function() {      return mgr.addCookie(         cName,         cookieObj.value,         cookieObj.path,         domain,         cookieObj.secure,         cookieObj.expiryTime());   });   cookieProm.then(function() {      mgr.getCookie(cName).then(function(cookie) {         console.log("Actual cookie", cName, "::", cookie);         expect(cookie.value).toBe(cookieObj.value);      });   });   return cookieProm;}