How To Selenium: Handling Cookies In Selenium

This is the latest post as part of the Huddle Selenium series.

Each month on the first Tuesday of the month, we will post a new blog post to take you through a step-by-step guide on how to address a particular aspect of using Selenium as part of our How To series. Our guest blogger Alex will showcase and demonstrate how to solve a new problem in detail. This week Alex looks at handling cookies in Selenium Webdriver.

How To…Select Elements In Selenium WebDriver Scripts

How To…Use Explicit Waits In Selenium WebDriver

How To…Manage Exceptions In Selenium WebDriver

How To…Execute Javascript In Selenium

How To…take Screenshots in Selenium

How To…Interact with sliders in Selenium

How to…Interact with Modal Windows

How to…Use Expected Conditions

How To..Find Elements

————————————————————————————————————————————-

Browsers use cookies to store user preferences such as

  • user location
  • number of results per page
  • sort order
  • language

Next time the user visits the site, the user preferences saved in the cookies are set automatically for the site.

Each cookie is defined by the following fields:

  • name
  • value
  • domain
  • path
  • expires
  • size
  • http
  • isSecure
  • sameSite

To take an example, for the https://vpl.bibliocommons.com/search?q=java&t=keyword web page, the selected language is saved in the language cookie with the following fields:

  • name = language
  • value = en-CA
  • domain = vpl.bibliocommons.com
  • path = /
  • expires = the expiration date set by the site
  • size = 13
  • http =
  • isSecure = true
  • sameSite =

If the language is changed from English to French, the value of the cookie changes to fr-CA.

Info

Handling Cookies in Selenium

It is important to be able to work with cookies in Selenium scripts for scenarios such as

  1. user changes the language and verifies that the change is done correctly
  2. user changes the sort order and verifies that the change is done correctly
  3. user changes the results per page and verifies that the change is done correctly

The cookies support is provided by the WebDriver.Options interface that has the following methods:

void addCookie(Cookie cookie)

Add a specific cookie.

void deleteAllCookies()

Delete all the cookies for the current domain.

void deleteCookie(Cookie cookie)

Delete a cookie from the browser’s “cookie jar”.

void deleteCookieNamed(java.lang.String name)

Delete the named cookie from the current domain.

Cookie getCookieNamed(java.lang.String name)

Get a cookie with a given name.

java.util.Set getCookies()

Get all cookies for the current domain.

An example will clarify how to use these methods.

The following code sample does the following

  1. open a web page: https://vpl.bibliocommons.com/search?q=java&t=keyword
  2. verify that the default language is english (en-CA) by checking the value of the language cookie
  3. verify that the page title is correct for english
  4. change the language to french
  5. verify that the language is french (fr-CA) by checking the value of the language cookie
  6. verify that the page title is correct for french

 

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.Date;

public class Class1 {

WebDriver driver;
WebDriverWait wait;

@Before
public void setUp() {
  System.setProperty("webdriver.chrome.driver", "c:/selenium/selenium3/chromedriver.exe");
  driver = new ChromeDriver();
  wait = new WebDriverWait(driver, 30);
}

@After
public void tearDown() {
  driver.quit();
}

@Test
public void testChangeLanguage() throws InterruptedException {
  openSite();
  assertEquals(currentLanguage(), "en-CA");
  assertTrue(isTitleCorrect()));

  selectLanguage("fr-CA");

  goToPage(2);
  assertEquals(currentLanguage(), "fr-CA");
  assertTrue(isTitleCorrect());
}

private void openSite() {
  driver.get("https://vpl.bibliocommons.com/search?q=java&t=keyword");
}

private void goToPage(int pageNumber) {
  By pageLocator = By.xpath("//a[@testid='link_page" + pageNumber + "']");
  wait.until(ExpectedConditions.elementToBeClickable(pageLocator)).click();
}

private void selectLanguage(String language) {
  By changeLanguageMenuLocator = By.id("biblio_language_trigger");
  By languageLocator = By.xpath("//a[contains(@href,'" + language + "')]");
  wait.until(ExpectedConditions.elementToBeClickable(changeLanguageMenuLocator)).click();
  wait.until(ExpectedConditions.visibilityOfElementLocated(languageLocator));
  wait.until(ExpectedConditions.elementToBeClickable(languageLocator)).click();
}

private boolean isTitleCorrect() {
  if (currentLanguage().equalsIgnoreCase("en-CA") )
   return wait.until(ExpectedConditions
     .titleIs("Rechercher | Vancouver Public Library | BiblioCommons"));
  else
   return wait.until(ExpectedConditions
     .titleIs("Search | Vancouver Public Library | BiblioCommons"));
}

private String currentLanguage() {
  return getCookieValue("language");
}

private String getCookieValue(String cookieName) {
  return driver.manage().getCookieNamed(cookieName).getValue();
}

}

The code should be very easy to understand.

It interacts with cookies in 1 place only to get the value of a cookie (getCookieValue() method.

Info

Is this all we can do with cookies?

In addition to getting the value of a cookie, we can also delete a cookie or even create a new one.

The previous script is very slow as it has to change the language manually.

We could change the language value by modifying the cookie value instead of clicking the language element.

The benefit of doing this is that the script will be faster than before as it has to go through less pages.

See below the changed code.

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.Date;

public class Class1 {

WebDriver driver;
WebDriverWait wait;

@Before
public void setUp() {
  System.setProperty("webdriver.chrome.driver", "c:/selenium/selenium3/chromedriver.exe");
  driver = new ChromeDriver();
  wait = new WebDriverWait(driver, 30);
}

@After
public void tearDown() {
  driver.quit();
}

@Test
public void testChangeLanguageByAddingCookie() throws InterruptedException {
  openSite();
  assertEquals(getCookieValue("language"), "en-CA");
  assertTrue(wait.until(ExpectedConditions.titleIs("Search | Vancouver Public Library | BiblioCommons")));

  addCookie("language", "fr-CA");

  goToPage(2);
  assertEquals(getCookieValue("language"), "fr-CA");
  assertTrue(wait.until(ExpectedConditions.titleIs("Rechercher | Vancouver Public Library | BiblioCommons")));
}

private void openSite() {
  driver.get("https://vpl.bibliocommons.com/search?q=java&t=keyword");
}

private void goToPage(int pageNumber) {
  By pageLocator = By.xpath("//a[@testid='link_page" + pageNumber + "']");
  wait.until(ExpectedConditions.elementToBeClickable(pageLocator)).click();
}

private void selectLanguage(String language) {
  By changeLanguageMenuLocator = By.id("biblio_language_trigger");
  By languageLocator = By.xpath("//a[contains(@href,'" + language + "')]");
  wait.until(ExpectedConditions.elementToBeClickable(changeLanguageMenuLocator)).click();
  wait.until(ExpectedConditions.visibilityOfElementLocated(languageLocator));
  wait.until(ExpectedConditions.elementToBeClickable(languageLocator)).click();
}

private void deleteCookie(String cookieName) {
  driver.manage().deleteCookieNamed(cookieName);
}

private String currentLanguage() {
  return getCookieValue("language");
}

private boolean isTitleCorrect() {
  if (currentLanguage().equalsIgnoreCase("en-CA") )
   return wait.until(ExpectedConditions
    .titleIs("Rechercher | Vancouver Public Library | BiblioCommons"));
  else
   return wait.until(ExpectedConditions
    .titleIs("Search | Vancouver Public Library | BiblioCommons"));
}

private String getCookieValue(String cookieName) {
  return driver.manage().getCookieNamed(cookieName).getValue();
}

private void addCookie(String name, String value) {
  deleteCookie(name);

  Cookie cookie = new Cookie.Builder(name, value)
   .domain(".bibliocommons.com")
   .expiresOn(new Date(2022, 03, 13))
   .isHttpOnly(false)
   .isSecure(true)
   .path("/")
   .build();

  driver.manage().addCookie(cookie);
}

}

The script is very similar with the previous one.

The only change is that instead of using the site to change the language, the language cookie is first deleted and then recreated for the new language.

See more articles in the How To Selenium Series

About the Author

Alex

Software Tester from Vancouver, Canada. Blogs on test automation topics for manual testers on http://test-able.blogspot.ca When not testing or creating test automation scripts for my clients, I teach manual testers programming with Java and test automation with Selenium WebDriver.
Find out more about @alexsiminiuc