How to set cookies in selenium WebDriver. | Selenium Forum
M
Posted on 05/10/2016
How to set cookies in selenium WebDriver.

Say you have scenario

Open Application
Fill credentials
User logged into application
Close the browser
Open the browser
Now user should be directly logged in as not cleared session / cookies

To automate this scenario, how to add cookies to the browser.

Below is the code which I wrote how ever, after closing and browser of logged in user and opening new browser again, user still displaying with enter credentials page, expected to display user logged in

import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Cookies {

static WebDriver obj;
@Test
public void Gmail() throws InterruptedException {
System.setProperty(“webdriver.gecko.driver”,”D:\\SELENIUM\\geckodriver.exe”);
obj=new FirefoxDriver();
obj.manage().window().maximize();
obj.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
obj.get(“https://mail.google.com”);
obj.findElement(By.id(“Email”)).sendKeys(“UserEmail”);
obj.findElement(By.id(“next”)).click();
Thread.sleep(2000);
obj.findElement(By.id(“Passwd”)).sendKeys(“password$167?);
obj.findElement(By.id(“signIn”)).click();
Thread.sleep(3000);
Set<Cookie> allCookies=obj.manage().getCookies();
obj.quit();
obj=new FirefoxDriver();
obj.get(“https://mail.google.com”);
for(Cookie cookie : allCookies){
obj.manage().addCookie(cookie);
}
}
}

M
Replied on 06/10/2016

try this way

https://www.seleniumeasy.com/selenium-tutorials/how-to-add-cookie-with-selenium-webdriver


M
Replied on 06/10/2016

Have gone through the post. Thanks for sharing it

However below are few issues

1) There is no myCookie in console result when I executed. Similar to it we have SSID assuming which is Session ID.
2) Also how we would know the ID value upfront before executing
3) When tried capturing the session ID, it says time expiry adjacent to it as very immediately closed

Please help me on same


M
Replied on 07/10/2016

try using firefox profile. no cookies needed in that case.