How to Add Cookie with Selenium
How to Add Cookie with Selenium
Using Selenium we can add the cookie to the domain. To add a cookie, we should use a method named “addCookie(cookie)”
Cookie Parameters
Key | Description |
---|---|
name |
Cookie identifier (required) |
value |
Cookie data (required) |
domain |
Associated domain |
path |
URL path (default: ‘/’) |
secure |
HTTPS-only flag |
expiry |
Expiration timestamp |
addCookie() Method
Method Name: addCookie(Cookie cookie)
Syntax:driver.manage().addCookie(arg0);
Purpose: To add a specific cookie into cookies. If the cookie’s domain name is left blank, it is assumed that the cookie is meant for the domain of the current document.
Parameters: cookie – The name and value of the cookie to be added.
Example
@Test
public void addCookie()
{
driver= new FirefoxDriver();
String URL=<span class="hljs-string">"</span><span class="hljs-string">https://www.example.com/"</span>;
driver.navigate().to(URL);
//we should pass name and value for cookie as parameters
// In this example we are passing, name=mycookie and value=123456789123
Cookie name = new Cookie(<span class="hljs-string">"mycookie"</span>, <span class="hljs-string">"cookiedata"</span>);
driver.manage().addCookie(name);
// After adding the cookie we will check that by displaying all the cookies.
Set<Cookie> cookiesList = driver.manage().getCookies();
for(Cookie cookie :cookiesList) {
System.out.println(cookie);
}
}
The output looks like below. We can see the added cookie along with the other cookies of the domain.