How to addcookie with Selenium Webdriver
There are situation when we need to addcokkie with selenium webdriver in order to pre establish a behaviour in our browser for the tests that are going to be executed after that.
For example when you first open your web app you have an overlay over the page , like a sort of user guide , so every time you execute your tests this overlay will not leave you to interact with the interface as all the web-elements are hidden behind it. In this situation you have an option every time you see it you close it like an user does or usually when this is closed developers write a cookie for it to know to to show it again for that session.
If you choose the first option to find it and click on it that’s an extra request to the server and from performance point of view you might not want to do that .
So you can choose option number 2 when you pre set the cookie in your browser.
addcookie with Selenium Webdriver
You can simply check if your cookie has been added to your browser with the following code :
In one of the previous project I was using addcookie to handle a 2 steps authentication . Let me explain you how , Before all tests were supposed to start I was running the actual 2 steps authentication and generate all cookies for that session that was valid for 1 hour, I was outputting the cookies into a shared location where all my tests had access to and each tests was using those cookies and add it to the session so for all further tests I didn’t had to perform the authentication and my test execution time was improved.
You can check more selenium performance tips here .
I advise you have a look at the Cookie.java to understand all the ways you can benefit from cookies handling.