skhro87
skhro87

Reputation: 143

Selenium FirefoxDriver: Share Session/Cookies between different instances

I have the following scenario:

I have a C# WPF program where I try to access different websites at the same time and collect data from them.

Website A (www.example.com) has a login form and after login displays a number of links such as www.example.com?redir=abc

What I do:

The problem is, I have another FirefoxDriver instance 2 running in a different Thread in my Project.

In this Instance 2 I access the links that I collected before and want to open them.

The problem is that in order to access them (they are redirecting), I need to login again to website A. When I login, the session on Instance 1 is ended so I need to login there again etc. etc., so effectively the instances are "stealing" each other sessions. (I want to scale this even more to have instances 3,4...so that makes the problem even worse).

Obviously my problem is that instance 1 and instance 2 are not sharing the same session.

Possibilities that I found to solve the issue:

Therefore I am asking, anyone has an advice how I should design this?

Thank you for your help.

Upvotes: 2

Views: 3269

Answers (1)

mtmk
mtmk

Reputation: 6326

First I thought there was a way to share a profile between two instances, but that doesn't seem to be the case with WebDriver. The only way I was able to get it working was to copy the cookies from one instance to the other:

var driver1 = new FirefoxDriver();
driver1.Navigate().GoToUrl("http://www.html-kit.com/tools/cookietester/");
driver1.FindElementByXPath("//input[@value=\"Set Test Cookie\"]").Click();

var driver2 = new FirefoxDriver();
driver2.Navigate().GoToUrl("http://www.html-kit.com/tools/cookietester/");

// Copy cookies from one driver to the other
foreach (Cookie c in driver1.Manage().Cookies.AllCookies)
{
    driver2.Manage().Cookies.AddCookie(new Cookie(c.Name, c.Value, c.Domain.TrimStart('.'), c.Path, c.Expiry));
}

driver2.Navigate().Refresh();

Only issue I had to work around was that WebDriver (or Firefox) does not let you set cookies if you are not on the same domain. So a little trickery is required: go to a URL on the same domain and a refresh or navigate to the target URL later. So in your case:

  • Driver1: Navigate to SiteA
  • Driver1: Login
  • Driver2: Navigate to SiteA
  • Copy cookies from Driver1 to Driver2
  • Driver2: Refresh (Should be logged in now)
  • Driver2: Navigate to SiteB

Bit of a scenario. I hope it works. Good luck.

Upvotes: 9

Related Questions