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.
By following way cookies can be extracted out from the current session:
By 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();
- Bring the auto Sync magic of Protractor to Selenium with Java - October 23, 2015
- Restarting Appium Server could improve various server freezing issues and may improve execution time - January 20, 2015
- Appium with iOS 8 and XCode 6 : What’s new? - November 5, 2014
- REST API automation testing using Apache HttpClient – The Approach - October 3, 2014
- An Overview of mobile application : Moving forward to automation - October 1, 2014
- An introduction to REST - September 29, 2014
- Run ChromeDriver with Chrome Driver Service to reduce script execution time significantly - September 26, 2014
- Selenium WebDriver – Get Cookies from an existing session and add those to a newly instantiated WebDriver browser instance. - September 26, 2014
- Simulate Copy Paste action using Java Robot and Clipboard class - September 26, 2014
- Android : How to test if Android Application has memory leaks - August 11, 2014