Selenium WebDriver – Get Cookies from an existing session and add those to a newly instantiated WebDriver browser instance.

Sometimes we need to verify the session – by closing the browser and reopening it using Selenium WebDriver. But by closing the browser and reopening it –  does not hold the Cookies from the previous WebDriver instance/session. Hence we need to extract the current cookies before closing the browser and add them to the newly instantiated WebDriver instance.
SeleniumBy following way cookies can be extracted out from the current session:

Lets say ‘driver’ is the WebDriver instance.
Set<Cookie> cookies=null;
try
{
cookies=driver.manage().getCookies();
}
catch(Throwable e)
{
System.err.println(“Error While getting Cookies: “+ e.getMessage());}
Now we can close the browser and reopen it, navigate to the URL.To add the extracted cookies to the new session/ WebDriver instance :

try
   {
      for(Cookie cookie:cookies)
  {
driver.manage().addCookie(cookie);
 }
   }
catch(Throwable e)
   {
System.err.println(“Error While setting Cookies: “+ e.getMessage());
   }
If we are checking the log in status or similar stuff – e.g : In the later instace of browser we want to verify that user is in logged in state, a browser refresh is needed to load the sessions etc from added cookies. This can be achieved by :

driver.navigate().refresh();