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();
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();
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
Related
I am writing a code using selenium.
On a particular click there are chances of coming one of two windows. and both the windows takes around 20-50 seconds of time to appear.
so i want to switch to whichever window appears.
I have no way to predict which window is going to appear
Current process - i am searching for main window for some seconds and if it is not found i am trying to search small pop up window with ok button on it. If found click on it. if not found again try to find main window it is taking time.
If i have a way to switch to latest window and by checking its title which window it is and do the appropriate action.
Edited - main window is not the original window. There are total 3 windows in picture . One og window where i have to click . now after clicking main window can appear or small popup window can apear with ok button.
You can try something like this for your problem
// Store the current window handle
String mainWin = driver.getWindowHandle();
// Perform the click operation that opens new window
//Wait till driver.getWindowHandles() returns 2 windows
// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
}
//Get current window to take decision on the next actions
String currentWin= driver.getWindowHandle();
// Perform the actions on new window
// Close the new window
driver.close();
// Switch back to original first window
driver.switchTo().window(mainWin);
To handle windows size, you can use .getWindowHandles(), and try use while loop to wait the new windows appear, then you can iteration again all current window.
int sizeBefore = driver.getWindowHandles().size();
elemnt.click();//to bring up new windows
//until current windows size>before, please keep adding timeout
while(driver.getWindowHandles().size()==sizeBefore) {
//wait in milliseconds
Thread.sleep(500);
}
//handle current size windows
ArrayList<String> hnds = new ArrayList<String> (driver.getWindowHandles());
//iteration windows
for(String hnd: hnds) {
driver.switchTo().window(hnd);
System.out.println(driver.getTitle());
}
To switch to particular windows, use:
driver.switchTo().window(hnds.get(index));
You should save the window handle for the main window before any action is done.
String mainWindow = driver.getWindowHandle();
Now click and do the following:
You can poll for 30 seconds max time with interval say 5 seconds, break the polling the moment you get more than one window handle.
Set<String> windows = driver.getWindowHandles();
let me know in which language you are working.
I can help you with the code.
Hi you can use Javascript for switching wondow: below are the code:
((JavascriptExecutor)LoginDriver).executeScript("window.open('about:blank', '-blank')");
// To switch to the new tab
ArrayList<String> tabs = new ArrayList<String>(LoginDriver.getWindowHandles());
LoginDriver.switchTo().window(tabs.get(1));
I am working with selenium automation. I have coded to login a page and it works fine. The login passed and new child window was opened as a result and parent window was closed.
Due to that my web driver stops and result in exceptions.
Exception in thread main org.openqa.selenium.NoSuchWindowException:
No window found (WARNING: The server did not provide any stacktrace information)
Please help
Selenium keeps a list of windows (handles). The webdriver needs to point to the right handle. When a window is closed, its handle is deleted, and your driver will now point to something that doesn't exist anymore.
Likely, you have to explicitly switch window to point your driver to the right window handle. Maybe this could help:
Switch between two browser windows using selenium webdriver
Selenium python bindings: Moving between windows and frames
"new child window was opened as a result and parent window was closed"
The code below from (1) shows you how to retrieve the list of window handles, and retrieve the right handle based on its title.
private void handleMultipleWindows(String windowTitle) {
Set<String> windows = driver.getWindowHandles();
for (String window : windows) {
driver.switchTo().window(window);
if (driver.getTitle().contains(windowTitle)) {
return;
}
}
}
You can use that function (or something similar) to retrieve the new window. From the code you provided, this would give:
// Entering the credentials in the login window.
driver.findElement(By.id(txtUserId)).clear();
driver.findElement(By.id(txtUserId)).sendKeys(poovan);
driver.findElement(By.id(txtPassword)).clear();
driver.findElement(By.id(txtPassword)).sendKeys(welcome1);
driver.findElement(By.id(btnSubmit)).click();
// Here the login window gets closed, handler to that window disappears, and driver becomes stale.
// So we need update the driver to point to the new window
handleMultipleWindows("The title of my new window");
driver.findElement(By.name(bono)).sendKeys(080);
Please use below code. It will work for sure.
String parentWindow = driver.getWindowHandle();
Set<String> handles2 = driver.getWindowHandles();
for (String windowHandle : handles2) {
if (!windowHandle.equals(parentWindow)) {
driver.switchTo().window(windowHandle);
}
}
I am working with Selenium, now there is a condition:
when I hit a button in my webpage a window pop up opens up.
Now I have to click a radio button (one out of two, it will work even if we send a TAB ) and then click an OK button. I searched in the net and got to know about "driver.getWindowHandle()".
But I don't have any idea dealing with the newly opened window popup.
Need help in this.
For switching purpose u can use enhanced for loop:
for (String winHandle : objDriver.getWindowHandles()) {
objDriver.switchTo().window(winHandle);
}
So it will switch the control from one driver window to child windows.
To interact with elements on the window try to find element with whatever tool u r using and perform the required action after switching to the window.
To return back to parent window you can use the same loop or use:
driver.switchTo().defaultContent();
Check my answer in this post and also read the comments to help you understand the difference between getWindowHandle() and getWindowHandles()
Java: focus is not on pop-window during window handling
We handled this situation using AutoItX - https://www.autoitscript.com/site/ in our Windows/IE C# project:
AutoItX3 autoIt = new AutoItX3();
var handle = autoIt.WinWaitActive("[window title]", "", 20);
Assert.IsTrue(handle != 0", string.Format("Was not able to find: {0}", [window title]);
autoIt.Send("{ESCAPE}"); // tab may work as well for selection
The pop up was a Windows window, and not part of IE, therefore the WebDriver didn't know about it.
Hope this helps.
I use Selenium 2 + Java for testing the application on IE 9.
After clicking on the link, the pop-up window is opened. I use switchTo.window method for going to pop-up window. But when I try to go back, my test is delayed on this operation and doesn't go on.
Some code:
link.click(); //Open pop-up window
Object[] windows = driverIE.getWindowHandles().toArray();
driverIE.switchTo().defaultContent();
driverIE.switchTo().window(windows[1].toString()); //Focus on pop-up window
.....
mainWindowHandle = driverIE.getWindowHandles().iterator().next(); //Handle of main window
driverIE.switchTo().window(mainWindowHandle); //Fail!
Please help me to solve the problem.
Windows handles returned by getWindowHandles() are not guaranteed to be in any order. In other words, you cannot depend on windows[1] in your code sample above to contain the window handle of the opened window. Rather, you need code that looks something like the following (NOTE: Completely untested code ahead!):
String mainHandle = driver.getWindowHandle();
// Do whatever you need to do to open a new window,
// and properly wait for the new window to appear...
Set<String> allHandles = driver.getWindowHandles();
for(String currentHandle : allHandles) {
// Note that this is cheating a bit. It will only
// work with a total of two windows. If you have
// more than two windows total, your logic here
// will have to be a little more sophisticated.
if (!currentHandle.equals(mainHandle)) {
driver.switchTo().window(currentHandle);
break;
}
}
// Work with popup window...
// Close the popup window and switch context back
// to the main window.
driver.close();
driver.switchTo().window(mainHandle);
As JimEvans stated, driver.getWindowHandles() sometimes puts windows in incorrect order, thus the for loop does not always work.
Similar to above worked for me (I only have two windows to handle):
String winHandleBefore = driver.getWindowHandle();
driver.findElement(By.cssSelector("a")).click();
Set<String> winHandle = driver.getWindowHandles();
winHandle.remove(winHandleBefore);
String winHandleNew = winHandle.toString();
String winHandleFinal = winHandleNew.replaceAll("\\[", "").replaceAll("\\]","");
driver.switchTo().window(winHandleFinal);
I am testing a web application that creates a new window long after a button is clicked. The sequence is the following
window 1: (parent window) click button to create window 2
window 2: progress window appears until background process on server returns data
window 3: progress window turns into 3rd window (with different handle)
I want to properly wait for the 3rd window to appear. I know what the 'title' of all 3 windows will be however in order to get the titles from WebDriver I have to use the following code:
while(timeout has not occured...){
for (String handle : _driver.getWindowHandles()) {
String myTitle = driver.switchTo().window(handle).getTitle();
if(3rdWindowTitle.equalsIgnoreCase(myTitle)){
return true;
}
}
}
This will effectively switch the active window back and forth every time it loops because of the 'switchTo'. This causes the firefox windows to cycle back and forth really quickly and is obnoxious. What I need is a way to get the title's of the windows that are available without having to 'switchTo' each window in a loop waiting for the 3rd window. Any ideas?
I basically want a method (waitForWindowByTitle(titleIWant)) which will block until the window with the title I want appears.
Well, Better you can wait for your window to appear by checking the number of windows. Like:
for(int i=0; i<noOfTrials;i++){
noOfWindows = driver.getWindowHandles().size();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
if(noOfWindows>currentNoOfWindows){
break;
}
}
}
then for the first and last time you can browse through the windows (using switchTo) and navigate to the window you want.