how to disable cookies using webdriver for Chrome and FireFox JAVA

I've just get solution for Firefox:

FirefoxProfile profile = new ProfilesIni().getProfile("default");
profile.setPreference("network.cookie.cookieBehavior", 2);
driver = new FirefoxDriver(profile);

for Chrome (block all cookies)

ChromeOptions options = new ChromeOptions();
options.AddUserProfilePreference("profile.default_content_setting_values.cookies", 2);

for Chrome (block only third party cookies)

ChromeOptions options = new ChromeOptions();
options.AddUserProfilePreference("profile.default_content_setting_values.cookies", 1);
options.AddUserProfilePreference("profile.cookie_controls_mode", 1);

You can disable Chrome cookies as below:

Map prefs = new HashMap();
prefs.put("profile.default_content_settings.cookies", 2);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOptions("prefs", prefs);
driver = new ChromeDriver(options);

You can use the below code snippets to disable the cookies in the Chrome and Firefox browsers. If you wish to enable cookies, just remove the capability.

Safari doesn't support any capability to achieve this.

For Chrome:

DesiredCapabilities caps = new DesiredCapabilities();

ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<String, Object>();
Map<String, Object> profile = new HashMap<String, Object>();
Map<String, Object> contentSettings = new HashMap<String, Object>();

contentSettings.put("cookies",2);
profile.put("managed_default_content_settings",contentSettings);
prefs.put("profile",profile);
options.setExperimentalOption("prefs",prefs);
caps.setCapability(ChromeOptions.CAPABILITY,options);

WebDriver driver = new ChromeDriver(caps);

For Firefox:

FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("network.cookie.cookieBehavior",2);
caps.setCapability(FirefoxDriver.PROFILE,profile);