Site icon

Delete Cookies using Selenium WebDriver (Clear cookies)

Must Read : Handle Cookies using Selenium WebDriver

                      Add a Cookie using Selenium WebDriver

 

Different built in Methods available for deleting (clear) Cookies:

Method Name Description
driver.manage().deleteCookie(Cookie cookie)   delete a specific cookie
driver.manage().deleteCookieNamed(String name)   delete named cookie from the current domain
driver.manage().deleteAllCookies() delete all the cookies for the current domain

Delete cookie named “MJ134” – deleteCookieNamed(String name):

package TestCases;
import java.util.Set;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

public class MakeinJavaTest {
	public WebDriver driver;
	@Test
	public void deleteCookieNamedTest()
	{
		System.setProperty("webdriver.chrome.driver", "C:\\work\\chromedriver.exe");
		driver = new ChromeDriver();
		driver.get("https://makeinjava.com");
		
		driver.manage().deleteCookieNamed("MJ134");
	}
}

Delete newly created cookie – deleteCookie(Cookie cookie)

package TestCases;
import java.util.Set;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

public class MakeinJavaTest {
	public WebDriver driver;
	@Test
	public void deleteCookieTest) {
		System.setProperty("webdriver.chrome.driver", "C:\\work\\chromedriver.exe");
		driver = new ChromeDriver();

		driver.get("https://makeinjava.com");

		// Passing parameters, name = CookieName and value=12345678 for new cookie
		Cookie cookie = new Cookie("CookieName", "12345678");
		driver.manage().addCookie(cookie);

		driver.manage().deleteCookie(cookie);
	}
}

Delete all cookies for the current domain – deleteAllCookies() :

package TestCases;
import java.util.Set;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

public class MakeinJavaTest {
	public WebDriver driver;
	@Test
	public void deleteCookieTest) {
		System.setProperty("webdriver.chrome.driver", "C:\\work\\chromedriver.exe");
		driver = new ChromeDriver();
		driver.get("https://makeinjava.com");
		driver.manage().deleteAllCookies();
	}
}
Exit mobile version