1

I am using Selenium to test a website. I can upload a ".txt" file and then double click on it to open,But I am not able to close the opened file using selenium!!!

I know there is a solution with robot tool by using Alt+F4 but I am not allowed to use robot, I tried the selenium code below to close the window, it does not work:

action.sendKeys(Keys.chord(Keys.ALT,Keys.F4)).build().perform();
skumar
  • 180
  • 3
  • 17
  • have you tried with other tools like autoit or sikuli – skumar Jun 06 '15 at 19:23
  • @skumar the problem with sikuli is that first time that I run the program it throws exception and create a "PATH" to its dll files, I do not want it to happen on the costumer's computer :( any way that we can add the "PATH" and "libs" in executable jar file that I will not throw the exception and does not change any thing on the computer? your answer is must appreciated –  Jun 08 '15 at 19:08

2 Answers2

1

Try this (driver is an instance of WebDriver):

String myWindow = driver.getWindowHandle();

//open file with double click
//do something ...

driver.switchTo().window(myWindow);

This stores a handle to the original window and switches back to it. The other window may be still open in background but will be closed, if you call driver.quit();

Würgspaß
  • 4,660
  • 2
  • 25
  • 41
  • I does not close the window, it opens a small window on top-left side of the new opened window and says "Disable developer mode extensions..." –  Jun 08 '15 at 16:32
0

Thanks to: CODEBLACK

String parentHandle = driver.getWindowHandle(); // get the current window handle
driver.findElement(By.xpath("//*[@id='someXpath']")).click(); // click some link that opens a new window

for (String winHandle : driver.getWindowHandles()) {
    driver.switchTo().window(winHandle); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}

//code to do something on new window

driver.close(); // close newly opened window when done with it
driver.switchTo().window(parentHandle); // switch back to the original window


  [1]: https://stackoverflow.com/questions/19112209/how-to-handle-the-new-window-in-selenium-webdriver
Community
  • 1
  • 1
  • ok, that's essentially the same as the first answer. But please be aware, that `getWindowHandles()` returns all current windows. Your code relies on the assumption, that the last one is always the newly opened window. This may be the case - or not. – Würgspaß Jun 08 '15 at 17:04