Amrutha
Amrutha

Reputation: 301

Switching between 2 windows in selenium webdriver with java

I am automating an application using selenium webdriver with java. In that i have to open a browser instance & perform some actions. After that i have to open another browser instance, perform some actions in it & close that instance. Then i have to return the control back to the first browser instance again to perform some other actions.

I tried using :

String winHandleBefore = driver.getWindowHandle();
//then open new instance and perfom the actions
driver.switchTo().window(winHandleBefore);

But this returned an error :

org.openqa.selenium.remote.SessionNotFoundException: no such session

How can i do this? Can anybody help?

Upvotes: 0

Views: 1489

Answers (1)

Guy
Guy

Reputation: 50809

When you did driver = new ChromeDriver(); you reinitialized the driver object, which caused the lost of the first window. You can see it by checking the number of window handles after opening the new window

WebDriver driver = new ChromeDriver();
int len = getWindowHandles().size(); // 1 as expected
driver = new ChromeDriver();
len = getWindowHandles().size(); // still 1, has only the new window

To solve this use temporary driver to open the new window

WebDriver tempDriver = new ChromeDriver();
// do some stuff
tempDriver.close();

Upvotes: 1

Related Questions