Andre
Andre

Reputation: 53

Adding cookies to selenium from cookie container

I have a data grid view which collects successful http requests. What I want to happen is when the button inside the data grid view is clicked it should open up a browser in selenium with the cookies from that specific http request. I have some of it already.

Here is a screenshot of the data grid view: https://i.sstatic.net/c3cYQ.jpg

Here is what I have so far:

CookieContainer cookiejar = new CookieContainer();
//Http request goes here
httpWebRequest1.CookieContainer = cookiejar;

This is used to add an item to cart and save the cookies in the cookie container.

This is what the checkout button does:

var driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://www.adidas.co.uk/on/demandware.store/Sites-adidas-GB-Site/en_GB/Cart-Show");

foreach (System.Net.Cookie cook in response.Cookies)
{                    
driver.Manage().Cookies.AddCookie(new OpenQA.Selenium.Cookie(cook.Name, cook.Value));
}

What I want to happen is that each data grid view row has a different cookie container and when checkout is clicked it opens a browser using that cookie container. At the moment one of the problems is I can't make a working public cookie container that I can add the cookies from using the button. The second thing is I don't know how to make a separate container for each row.

Any help is appreciated even if you don't know the whole process.

Upvotes: 3

Views: 2655

Answers (1)

Gregory Liénard
Gregory Liénard

Reputation: 1731

You can't iterate through a cookie collection. You must use reflection.

Hashtable table = (Hashtable)response.Cookies.GetType().InvokeMember(
    "m_domainTable",
    BindingFlags.NonPublic |
    BindingFlags.GetField |
    BindingFlags.Instance,
    null,
    cookies,
    new object[] { }
);

                foreach (var hostname in table.Keys)
                {
                    Uri uri = new Uri(string.Format("https://{0}/", hostname));

                    foreach (System.Net.Cookie netcookie in cookies.GetCookies(uri))
                    {
                        OpenQA.Selenium.Cookie cookie = new OpenQA.Selenium.Cookie(netcookie.Name, netcookie.Value, netcookie.Domain,netcookie.Path, netcookie.Expires);
                        _currentDriver.Manage().Cookies.AddCookie(cookie);

                    }
                }

Upvotes: 1

Related Questions