Testing / Selenium Interview questions
How do you handle browser cookies in Selenium?
The Options interface (via driver.manage()) exposes methods to read, add, and remove cookies for the current domain.
Cookie sessionCookie = new Cookie("session_id", "abc123"); driver.manage().addCookie(sessionCookie); Set<Cookie> all = driver.manage().getCookies(); driver.manage().deleteCookie(sessionCookie); driver.manage().deleteAllCookies();
A cookie can only be added for the domain currently loaded in the browser - trying to set a cookie before navigating to that domain at all will fail, since there's no active page context to attach it to. This makes a common pattern navigate to the target site first (even to a lightweight page like a 404), inject an auth cookie to skip a UI login, then reload the actual page under test.
More Related questions...