Restoring Cookies in a new Browser Tab while Working with WebDriver

Restoring Cookies in a new Browser Tab while Working with WebDriverConsider the following test scenario:

  1. Open a browser and login to the application through the login page.
  2. Close the login page and the browser.
  3. Re-open the login page to see if you are automatically logged in.

Usually, browser stores the cookies on the first login. However, in WebDriver all session data and cookies are deleted as the window is closed. So, the testing becomes little complex in such scenarios.

But, WebDriver allows you to restore the cookies in the new window, as it can read the information from the browser before closing it, as shown below.

package com.testing.webdriver

import org.openqa.selenium.By;

import org.openqa.selenium.Cookie;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.testng.Assert;

import java.util.Set;

public class CookieTest {

WebDriver driver;


public void login_state_should_be_restored() {

driver = new FirefoxDriver();







    // Read the cookies before closing the browser

        Set<Cookie> allCookies = driver.manage().getCookies();


   //Open a new browser window

  driver = new FirefoxDriver();

  //Restore all cookies from previous session

        for(Cookie cookie : allCookies) {




 //Login page should not be displayed






You might also like: How to Add, Retrieve, and Delete Cookies in WebDriver?


Get A Free Quote

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.