Skip to content

Instantly share code, notes, and snippets.

@johnnonolan
Created December 2, 2013 16:23
Show Gist options
  • Save johnnonolan/7752077 to your computer and use it in GitHub Desktop.
Save johnnonolan/7752077 to your computer and use it in GitHub Desktop.
Cookies and Selenium
<html>
<body>
<div>
<input id="setCookie" type="button" onclick="setCookie()" value="set cookie"></input>
<input type="button" onclick="setCookie2('test2','hello 2',1);" value="set cookie 2"></input>
<input type="button" onclick="getCookie2()" value="get cookie"></input>
<input type="button" onclick="delCookie();" value="del cookie"></input>
</div>
</body>
<script>
function setCookie2(cookieName,cookieValue,nDays) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
var x = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString();
console.log(x);
document.cookie = x;
}
function setCookie() {
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1)
var c_value=escape("hello world") + ";expires="+tomorrow.toGMTString();
console.log("testcookie=" +c_value);
document.cookie="testcookie=" + c_value;
}
function getCookie(c_name){
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1) {
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1) {
c_value = null;
}
else {
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1) {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}
function delCookie() {
document.cookie = "testcookie=blah;expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}
</script>
</html>
namespace seleniumhost
{
class Program
{
static void Main(string[] args)
{
//IWebDriver wd = new ChromeDriver();
IWebDriver wd = new FirefoxDriver();
const string url = "localhost:8123";
wd.Navigate().GoToUrl(url);
var q = wd.FindElement(By.Id("setCookie"));
q.Click();
var _oldCookies = wd.Manage().Cookies.AllCookies;
////_oldCookies now has all of the browser cookies, each with 'Name' attributes associated with them.
wd.Manage().Cookies.DeleteAllCookies();
wd.Navigate().GoToUrl(url);
foreach (var cookie in _oldCookies)
{
wd.Manage().Cookies.AddCookie(new Cookie(cookie.Name,cookie.Value,cookie.Domain,cookie.Path,cookie.Expiry) );
}
//this is where it blows up
var _newCookies = wd.Manage().Cookies.AllCookies;
Console.WriteLine(_newCookies.First().Name);
//wd.Manage().Cookies.AddCookie(new Cookie("geoff","barry"));
Console.WriteLine(wd.Manage().Cookies.AllCookies.Count);
wd.Quit();
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment