Cookies

Cookies are small pieces of data that a website or online service stores on a user's device (usually within their web browser) while the user is browsing or interacting with the site.

Posted by MCRSR on August 30, 2023

Cookies

Cookies let you store user information in web pages.

What are Cookies?

Cookies are small pieces of data that a website or online service stores on a user's device (usually within their web browser) while the user is browsing or interacting with the site. Cookies can contain various types of information, such as user preferences, session identifiers, shopping cart contents, and more. When the user visits the website again, the browser sends these cookies back to the server, allowing the website to recognize the user and retrieve their stored information.

Cookies are data, stored in small text files, on your computer. When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user. Cookies were invented to solve the problem "how to remember information about the user": When a user visits a web page, his/her name can be stored in a cookie. Next time the user visits the page, the cookie "remembers" his/her name. Cookies are saved in name-value pairs like: username = John Doe When a browser requests a web page from a server, cookies belonging to the page are added to the request. This way the server gets the necessary data to "remember" information about users.

HTTP cookies (also called web cookies, Internet cookies, browser cookies, or simply cookies) are small blocks of data created by a web server while a user is browsing a website and placed on the user's computer or other device by the user's web browser. Cookies are placed on the device used to access a website, and more than one cookie may be placed on a user's device during a session.

Types of Cookies:

Session Cookies: These cookies are temporary and are erased from the device's memory once the user closes the web browser. They are typically used to maintain session information, such as login status or items in a shopping cart during a single browsing session.

Persistent Cookies: These cookies are stored on the user's device even after the browser is closed. They have an expiration date and remain active until that date is reached, or until the user manually deletes them. Persistent cookies are often used for remembering user preferences and login information across multiple sessions.

First-party Cookies: These cookies are set by the website that the user is currently visiting. They are primarily used to remember user settings and preferences for that specific website.

Third-party Cookies: These cookies are set by domains other than the one the user is currently visiting. They are often used for tracking users across different websites for purposes like targeted advertising.

Importance of Cookies:

User Convenience: Cookies play a significant role in enhancing user experience. They allow websites to remember user preferences and settings, such as language preferences, layout choices, and font sizes. This means that users don't have to reconfigure these settings every time they visit a site.

Authentication and Session Management: Cookies are essential for managing user sessions. When you log into a website, a session cookie is often used to maintain your logged-in status as you navigate different pages. Without cookies, you would need to log in again for each page you visit.

Personalization: Cookies enable websites to offer personalized content and recommendations. They track user behavior and interactions, allowing websites to tailor content to individual users' interests.

Shopping Carts and E-commerce: Cookies are often used to store items in a shopping cart. This way, users can continue shopping and adding items to their cart even if they navigate to different pages. Persistent cookies also remember items in the cart for future visits.

Tracking and Analytics: Websites use cookies to collect data on user behavior, such as pages visited, time spent on pages, and interactions. This data is then used for analytics to understand user engagement and improve website performance.

Targeted Advertising: Third-party cookies are frequently used by advertisers to track users across various websites and deliver targeted ads based on their browsing habits and interests.

to test cookies functionality Login Screen username: user and password: pass

Working with cookies:

  • void addCookie(Cookie cookie);

    Add a specific cookie.

  • void deleteAllCookies();

    Delete all the cookies for the current domain.

  • void deleteCookieNamed(String name);

    Delete the named cookie from the current domain. This is equivalent to setting the named cookie's expiry date to some time in the past.

  • void deleteCookie(Cookie cookie);

    Delete a cookie from the browser's "cookie jar". The domain of the cookie will be ignored.

  • Cookie getCookieNamed(String name);

    Get a cookie with a given name.

  • Set<Cookie> getCookies();

    Get all the cookies for the current domain.



                      
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class addCookie {

    public static void main(String[] args) {
        
        WebDriver driver = new ChromeDriver();
        driver.get("http://127.0.0.1:5502/cookies/login.html");
        driver.manage().window().maximize();
        driver.findElement(By.id("username")).sendKeys("user");
        driver.findElement(By.id("password")).sendKeys("pass");
        driver.findElement(By.xpath("//button[@type='submit']")).click();
        System.out.println(driver.findElement(By.className("dashboard-heading")).getText());
        System.out.println("Before Adding the cookies: "+driver.manage().getCookies());
        driver.manage().addCookie(new Cookie("username", "user"));
        Cookie password = new Cookie("password","pass");
        driver.manage().addCookie(password);
        System.out.println("After Adding the cookies: "+driver.manage().getCookies());
        driver.findElement(By.id("logoutButton")).click();
        driver.quit();

    }

}
                      
                    
                        
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class deleteAllCookies {

    public static void main(String[] args) {
        
        WebDriver driver = new ChromeDriver();
        driver.get("http://127.0.0.1:5502/cookies/login.html");
        driver.manage().window().maximize();
        driver.findElement(By.id("username")).sendKeys("user");
        driver.findElement(By.id("password")).sendKeys("pass");
        driver.findElement(By.xpath("//button[@type='submit']")).click();
        
        driver.manage().addCookie(new Cookie("test1", "cookie1"));
        Cookie cookie1 = new Cookie("test2", "cookie2");
        driver.manage().addCookie(cookie1);
        
        System.out.println("Available Cookies: "+driver.manage().getCookies());
        
        driver.manage().deleteAllCookies();
        
        System.out.println("Available Cookies: "+driver.manage().getCookies());
       
        driver.quit();

    }

}
                        
                    
                        
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class deleteCookie {

    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("http://127.0.0.1:5502/cookies/login.html");
        driver.manage().window().maximize();
        driver.findElement(By.id("username")).sendKeys("user");
        driver.findElement(By.id("password")).sendKeys("pass");
        driver.findElement(By.xpath("//button[@type='submit']")).click();
        
        driver.manage().addCookie(new Cookie("test1", "cookie1"));
        Cookie cookie1 = new Cookie("test2", "cookie2");
        driver.manage().addCookie(cookie1);
        
        System.out.println("Available Cookies: "+driver.manage().getCookies());
        
        driver.manage().deleteCookie(cookie1);
        driver.manage().deleteCookieNamed("test1");
        
        System.out.println("Available Cookies: "+driver.manage().getCookies());
       
        driver.quit();
    }

}
                        
                    
                        
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class getAllCookies {

    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("http://127.0.0.1:5502/cookies/login.html");
        driver.manage().window().maximize();
        driver.findElement(By.id("username")).sendKeys("user");
        driver.findElement(By.id("password")).sendKeys("pass");
        driver.findElement(By.id("remember")).click();
        driver.findElement(By.xpath("//button[@type='submit']")).click();
        System.out.println("Cookies available: "+driver.manage().getCookies());
        driver.quit();
    }

}
                        
                    
                        
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class getCookieNamed {

    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("http://127.0.0.1:5502/cookies/login.html");
        driver.manage().window().maximize();
        driver.findElement(By.id("username")).sendKeys("user");
        driver.findElement(By.id("password")).sendKeys("pass");
        driver.findElement(By.id("remember")).click();
        driver.findElement(By.xpath("//button[@type='submit']")).click();
        System.out.println(driver.findElement(By.className("dashboard-heading")).getText());
        System.out.println("Cookies available: "+driver.manage().getCookies());
        System.out.println("username cookie: "+driver.manage().getCookieNamed("username"));
        driver.quit();
    }

}
                        
                    

Same-Site Cookie Attribute

It allows a user to instruct browsers to control whether cookies are sent along with the request initiated by third party sites. It is introduced to prevent CSRF (Cross-Site Request Forgery) attacks.

Same-Site cookie attribute accepts two parameters as instructions

Strict:

When the sameSite attribute is set as Strict, the cookie will not be sent along with requests initiated by third party websites.

Lax:

When you set a cookie sameSite attribute to Lax, the cookie will be sent along with the GET request initiated by third party website.

Note:As of now this feature is landed in chrome(80+version), Firefox(79+version) and works with Selenium 4 and later versions.

                        
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

public class cookieTest {
  public static void main(String[] args) {
    WebDriver driver = new ChromeDriver();
    try {
      driver.get("http://www.example.com");
      Cookie cookie = new Cookie.Builder("key", "value").sameSite("Strict").build();
      Cookie cookie1 = new Cookie.Builder("key", "value").sameSite("Lax").build();
      driver.manage().addCookie(cookie);
      driver.manage().addCookie(cookie1);
      System.out.println(cookie.getSameSite());
      System.out.println(cookie1.getSameSite());
    } finally {
      driver.quit();
    }
  }
}