Webdriver can't control popups - java

After sending click with findElement, I Cant go on to the next action of handling the popup until popup closed (manually), since current window is not in control, therefore webdriver waits forever.
Im trying to do the following:
driver.findElement(By.xpath(salesforceButtons.CUSTOM_OBJECT_DELETE.getValue())).click();
Set<String> windowId = driver.getWindowHandles(); // get window id of current window
Iterator<String> itererator = windowId.iterator();
String mainWinID = itererator.next()
String newAdwinID = itererator.next();
driver.switchTo().window(newAdwinID);
But it stuck after the click.

I think you need to use the following (presuming by pop-up you mean a browser alert window):
Alert alert = driver.switchTo().alert();
alert.accept()
I may be wrong with this, and it may be that you do need to iterate through the windows, however, the code you've stated isn't doing that, it is simply changing the window focus to the one defined by the second result in the driver.getWindowHandles() set. Might I suggest the following if it's not just a simple alert:
String startWinId = driver.getWindowHandle(); // caches the current window id
driver.findElement(By.xpath(salesforceButtons.CUSTOM_OBJECT_DELETE.getValue())).click();
Set<String> windowId = driver.getWindowHandles(); // actually gets all available windows ids
Iterator<String> iterator = windowId.iterator();
// Iterates through each active window and does stuff within that window.
while (iterator.hasNext()) {
driver.switchTo().window(iterator.next());
<insert code to run against each window here>
}
// Switches back to the original window to carry on with executing tests
driver.switchTo().window(startWinId);

Related

Switch To any new window

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));

Selenium: How can I navigate back to parent window

I am running below java code for switching windows and getting error message, Kindly suggest something.
Driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
Set<String>set=Driver.getWindowHandles();
Iterator<String> It=set.iterator();
String PId=It.next();
String CId=It.next();
Driver.switchTo().window(CId);
Driver.get("https://www.facebook.com");/* Here again I want to come back to parent window and perform some action */
Please refer to this java documentation link for the list of available switchTo options:
https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/WebDriver.TargetLocator.html
In your case, you may need to save the window handle before switching and then use it later to switch back to original window.
String originalWindow = Driver.getWindowHandle();
Driver.switchTo().window(CId);
//Operations on new window here
Driver.switchTo().window(originalWindow);
//Operations on original window here

unable to read child window element in selenium as parent window getting closed

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);
}
}

Is using the method driver.close() required?

Let's say
I have a window 1. I have performed an event on the window 1 that makes window 2 to appear.
Now I switched to the window 2 and clicked a button on it which closes window 2.
If I use driver.close() after I performed an event which caused the window to close, sometimes it throws NoSuchWindowException.
If I don't use the driver.close() then sometimes driver.getWindowHandles().size() returns 2 even when there is only one window and I have waited enough time to number of windows become 1.
I refresh driver.getWindowHandles() and check for the driver.getWindowHandles().size() to become 1 but it doesn't sometimes.
My question is, do I need to use the method driver.close() after I clicked the button that caused the window to close? How to use the driver.close() correctly.
EDIT: Yes, it is a problem. If selenium doesn't realize window2 has been closed, it keeps returning the handles to be 2. Suppose that I closed window2 and switched back to window1 and performed an event which opens window3. Now I want to switch to window3. Here is the problem because Selenium still think windows2 exists and now there are three windows according to the Selenium.
String window1Handle = driver.getWindowHandle();
//Now I have oepend window3
//According to the Selenium there are 3 windows
// So driver.getWindowHandles().size() returns 3
for (String window : driver.getWindowHandles() {
if (!window.equals(window1Handle)) {
driver.switchTo().window();
The above line may throw exception because driver is trying to switch to a window which has already been closed"
No you don't need to perform a driver.close(), if anything is left open, when you perform a driver.quit() at the end of your test WebDriver will clean up and make sure that everything is shut down correctly.
Selenium can track how many windows are open, if you are seeing window handles for windows that are closed that sounds like a potential bug. Bear in mind that it may take some time for Selenium to realise that the window has been closed, you could try using an explicit wait to wait for the count of window handles to drop back down to 1, you'll need to add the following ExpectedCondition:
public static ExpectedCondition<Boolean> numberOfWindowsToBe(final int numberOfWindows) {
return new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
return driver.getWindowHandles().size() == numberOfWindows;
}
};
}
Then you can use it by doing:
WebDriverWait wait = new WebDriverWait(driver, 15, 100);
wait.until(numberOfWindowsToBe(1));
or you could just try closing the window by performing a driver.close() and catching the NoSuchWindowException e.g.
try{
driver.close();
} catch(NoSuchWindowException ignored){
System.out.println("Window already closed");
}
This should give Selenium the kick it needs to realise that the window has been closed (Although to be honest I wouldn't bother).
*EDIT*
So it sounds like the problem is that you have multiple window handles and you don't know which one is the window that has been closed, and which one is your newly opened window. One workaround would be to track the window handles in a Map. Every time you open a new window store the window handle in the map like this:
Map<String, String> openedWindows = new HashMap<String, String>();
openedWindows.put("Window 1", driver.getWindowHandle());
You will then know which window handle is associated with your window, you can then remove windows from the map as they are closed. You will know which handles that are still being reported are actually closed and which are being reported in error.
Really this sounds like a bug in Selenium window handling and I would suggest you raise an issue on the issue tracker with a minimal test script that reproduces the problem. Of course the other option above is still valid, try and close the window but catch the exception and see if that gives Selenium the kick it needs to remove it from the list of window handles.
I had the same exact issue You are facing.
Before i perform an action which pops up second window, i intiated
String window = driver.getWindowHandle();
Later i clicked link 1 which populates window 2 and i switch to that window
driver.switchTo().window(window name);
i performed my action in Window 2 and when i click the link in Window 2 my window closes automatically and if i use driver.close() it wont happen as webdriver will throw error as u said
so instead of trying to close the second window, i try to switch back to window 1 with
driver.switchTo().window(window);
This is because since window 2 is closed automatically and since the control does not pass to window 1 the error will happen.. So there is no necessity to close window 2. instead we can switch back to our default window and continue or close the default window..
I know that this is a bit of a hack...but I've never seen something like what you are describing, so I think its worth a try. Change this code:
driver.switchTo().window();
to something like this:
try{
driver.switchTo().window();
perform action that will throw error
return; //will return if error wasn't thrown
catch(Error thrown if on bad window){
//continue in your for loop to switch to the next window;
}
I wrote a method that is working pretty good for me.
public static boolean letWebDriverRealizeThisWindowHasBeenClosed(WebDriver driver,
String closedWindowHandle) {
/**
* to avoid infinite loop, do write a break when definite time has been passed
*/
/**
* Generally, this method returns true given that window is closed
*/
boolean isWebDriverRealized = false;
long start = System.currentTimeMillis();
long end = start + (30 * 1000); //30 seconds
while (!isWebDriverRealized
&& System.currentTimeMillis() < end) {
try {
driver.switchTo().window(closedWindowHandle);
} catch (NoSuchWindowException nswe) {
isWebDriverRealized = true;
}
}
return isWebDriverRealized;
}
If this method returns true, then it means WebDriver has realized that window has been closed. driver.getWindowHandles.size() returns the correct number of windows once the above method returns true.
No, you don't need to do that. Because second window is already close, and if you will use method driver.close() it will close your first window and the browser itself(because there is only one tab left in browser window).
Its depends upon the Window,
some Window close while click on outside Window content, in that case no need of driver.close() method.
but for some Window, click on outside the Window content, Window unable to close (i.e. Window gets close after click on close button), in that case need to close such Window using thedriver.close() method.

WebDriver + Internet Explorer, switchTo.window issue

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);

Categories