Cookies Handling in Selenium WebDriver

Cookies Handling in Selenium WebDriver

Table of Contents

An HTTP cookie contains information about a User and their preferences on the client-side. In other words, cookies are user’s identities that are used to track the pages of the website which are navigated by the user. By using a key-value pair stores the information.

What are an HTTP Cookie and its working?

HTTP Cookie is also called a browser cookie, a web cookie, or an Internet cookie. It is a text file present in the web browser of the PC or the client machine that contains information about a user and their preferences on the client-side. Whenever the website loads, the browser will send back the Handling cookies that are stored to the server that notifies the user’s past activities. 

Need for Handling Cookies in Automation

During automation, we need to handle cookies for the following reasons-

  • There will be scenarios that are specific to cookies which are needed to be automated and requires entries in cookie files
  • During automation, we can create and load cookie files, in such situations, we can skip some scenarios for each test case like login to the application as the same gets Handling cookies. For example in an application like Gmail, we need to login only once, after that the login information gets stored in cookies and each time we open the Gmail link the login details get loaded. This saves the test execution time.

Selenium WebDriver Query Commands For Cookies

Using Selenium WebDriver built-in methods, we can query and interact concerning browser cookies. By bypassing the name we can add, delete the particular cookie by passing the name.

Get Cookies: This statement is used to get all the cookies for the current domains that are stored in the web browser.

Method Name: getCookies()
Syntax: driver.manage().getCookies();

Returns: It returns a set of cookies for the current domain.

Get the Cookie by Specific Name: This statement is used to get the specific cookie with a given name.

Method Name: getCookieNamed(java.lang.String name)
Syntax: driver.manage().getCookieNamed(arg0);

Parameters: name – It specifies the name of the cookie
This statement will return the specific cookie value for the name specified, or null if no cookie is found with the given name.

Add Cookie: This statement is used to add and create the cookie into cookies.
Method Name: addCookie(Cookie cookie)
Syntax:driver.manage().addCookie(arg0);
Parameters: cookie – It specifies the name of the cookie to add.

Example: Adding a Cookie

public void addCookie()
{
System.setProperty("webdriver.chrome.driver", "F:\\drivers\\chromedriver.exe");
    //create chrome instance
    driver = new ChromeDriver();
String URL="http://flipkart.com/";
driver.navigate().to(URL);
                //For cookie we should pass name and value as parameters
                // Here we pass, name=cookie and value=987654321
Cookie cname = new Cookie("cookie", "987654321");
driver.manage().addCookie(cname);

                // After adding the cookie we will check all the cookies by displaying them.
Set<Cookie> cookiesList =  driver.manage().getCookies();
for(Cookie getcookies :cookiesList) {
    System.out.println(getcookies );
}
}

Delete Cookie: This statement is used to delete a cookie from the browsers “cookie jar”.
Method Name: deleteCookie(Cookie cookie)
Syntax: driver.manage().deleteCookie(arg0);
Parameter: Cookie

Delete All Cookies: This statement will delete all the cookies for the current domain.
Method Name: deleteAllCookies()
Syntax: driver.manage().deleteAllCookies();
Parameters: N/A

Delete Cookie with Name: This statement is used to delete a named cookie from the current domain.
Method Name: deleteCookieNamed(java.lang.String name)
Syntax: driver.manage().deleteCookieNamed(arg0);
Parameters: name – The name of the cookie to delete according to its name.Example: Consider the below example for deleting the specific cookie with cookie name as “–utmb”

public void deleteSpecificCookieName()
{
System.setProperty("webdriver.chrome.driver", "F:\\drivers\\chromedriver.exe");
  //create chrome instance
    driver = new ChromeDriver();
String URL="http://www.flipkart.com";
driver.navigate().to(URL);
driver.manage().deleteCookieNamed("__utmb");
}

Deleting all the cookies of the domain

public void deleteAllCookies()
{
System.setProperty("webdriver.chrome.driver", "F:\\drivers\\chromedriver.exe");
  //create a chrome instance
    driver = new ChromeDriver();
String URL="http://www.flipkart.com";
driver.navigate().to(URL);
driver.manage().deleteAllCookies();
}

Demo: Cookie handling in Selenium.

We will use “facebook.com for our demo purpose.

Step 1: Login into the application and store the authentication cookie.

 
Step 2: Use the stored cookie to login into the application without using a username and password.

Step 1: Storing cookie information.

Here, we load a website for storing the username into cookies. Using Selenium Webdriver, we will load the below website and enter the username, password, and click on the submit button. 

package CookieExample;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.Cookie;


    public class StoreCookie{

    public static void main(String[] args)
    {
     WebDriver driver;
     System.setProperty("webdriver.chrome.driver", "F:\\drivers\\chromedriver.exe");
         //create a chrome instance
         driver = new ChromeDriver();
        
         driver.get("http://www.facebook.com/");
       
        // If you are already registered just input the Email id and Password
        driver.findElement(By.name("username")).sendKeys("abc123");
        driver.findElement(By.name("password")).sendKeys("123xyz");
        driver.findElement(By.name("submit")).click();
        
        // To store the Login Information create file named Cookies
        File file = new File("Cookie.data");
        try
        {   
            // Delete if old file exists
file.delete();
            file.createNewFile();
            FileWriter fileWrite = new FileWriter(file);
            BufferedWriter Bwrite = new BufferedWriter(fileWrite);
            for(Cookie ck : driver.manage().getCookies())
             String writeup = cook.getName()+";"+cook.getValue()+";"+cook.getDomain()+";"+cook.getPath()+""
             + ";"+cook.getExpiry()+";"+cook.isSecure();
             bufferwrite.write(writeup);
             System.out.println(writeup);
             bufferwrite.newLine();
             }
             bufferwrite.flush();bufferwrite.close();fileWriter.close();
             }catch(Exception exp){
             exp.printStackTrace();
        }
    }
}

Output

When you run the above test it displays the encrypted cookie details stored in a web browser in the console.

Step 2: Using the stored cookie in step 1 to login to the application.

Below test script will retrieve the details from the cookies which is stored in a file ‘Cookie.data’. Here, we retrieve the tokens with the help of a semicolon as a separator. After this, we create a Cookie in the Chrome browser, and with the help of ‘addCookie’, we add these details to the cookie.

package CookieExample;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Date;
import java.util.StringTokenizer;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class CookieRetriev
{
 WebDriver driver;
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", "F:\\drivers\\chromedriver.exe");
    //create chrome instance
    driver = new ChromeDriver();
   
try{
File file = new File("Cookie.data");
FileReader fileReader = new FileReader(file);
BufferedReader Buffreader = new BufferedReader(fileReader);
String strline;
while((strline=Buffreader.readLine())!=null){
StringTokenizer token = new StringTokenizer(strline,";");
while(token.hasMoreTokens()){
String name = token.nextToken();String value = token.nextToken();
String domain = token.nextToken();String path = token.nextToken();
Date expiry = null;
String val;
if(!(val=token.nextToken()).equals("null")){
expiry = new Date(val);
}
Boolean isSecure = new Boolean(token.nextToken()).booleanValue();
Cookie ck = new Cookie(name,value,domain,path,expiry,isSecure);
driver.manage().addCookie(ck);
}
}
}catch(Exception ex){
ex.printStackTrace();
}
driver.get("http://www.facebook.com/");
}
}

Output: 

When you execute the above code you will directly take to the login success screen without entering the user name and password.

Conclusion

With the help of Selenium Webdriver for each test, you can avoid entering the username and password on the server again and again and thereby saves a lot of time.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share this article
Subscribe
By pressing the Subscribe button, you confirm that you have read our Privacy Policy.
Need a Free Demo Class?
Join H2K Infosys IT Online Training
Enroll Free demo class