How to handle window based pop up after alert in selenium webdriver? - java

After saving user, there are two alerts and one window based pop up is coming. I am able to handle alert but not able to handle window based pop up after the alert in selenium.
I need to click on the button"Ok" for window based pop up after the alert pop up.
public void clickonSaveButton() {
savebutton.click();
driver.switchTo().alert().accept();
Helper.acceptAlert(driver);
String parentWindowHandler = driver.getWindowHandle();
String subWindowHandler = null;
Set<String> handles = driver.getWindowHandles();
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()) {
subWindowHandler = iterator.next();
}
driver.switchTo().window(subWindowHandler);
System.out.println("Sub window is:" +subWindowHandler);
driver.switchTo().window(parentWindowHandler);
System.out.println("Parent window is:" + parentWindowHandler);
}

Related

wait for child window in selenium webdriver using java

How to wait for the child window in selenium web driver
when I click on the submit button it leads me to child window and I assert the Url but sometimes the child window takes time to come
Currently using thread.sleep(4000)
But this is the wrong way.
// parent window
String subWindowHandler = null;
Set<String> handles = driver.getWindowHandles(); // get all window
// handles
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()) {
subWindowHandler = iterator.next();
}
driver.switchTo().window(subWindowHandler); // switch to popup window
System.out.println(driver.getTitle());
String Current_Url = driver.getCurrentUrl();
System.out.println("Current open Url in other Tab -->" + Current_Url);
try {
Assert.assertEquals("http://intelliview-dev.psi.psigroupinc.com/Reports/ReportView.aspx", Current_Url);
logger.info("Assertion Passed");
logger.info("User is able to login to My Account Application");
} catch (AssertionError e) {
logger.info("Assertion Failed");
logger.info("User Provide Invalid Username or Password");
throw e;
}
You can use ExpectedConditions.numberOfWindowsToBe.
Click on event which invoke window and then use below code and then use switch another window
Put the count as per your requirement
new WebDriverWait(driver,30).until(ExpectedConditions.numberOfWindowsToBe(2));
For that, you need to make sure that what would be the max time(Acceptable time limit) does the application takes to open that new window.
Before that get the current window details using
String parent_window = driver.getWindowHandle();
Then wait for the new window using
new WebDriverWait(driver,AcceptableTimeLimit).until(ExpectedConditions.numberOfWindowsToBe(2));
Then switch to the new window using
Set<String> allWindows = driver.getWindowHandles();
Iterator ite=allWindows.iterator();
while(ite.hasNext()){
String popupHandle=ite.next().toString();
if(!popupHandle.contains(parent_window)){
driver.switchTo().window(popupHandle);
//perform your operations on New window
//Then switch back to parent window
driver.switchTo().window(parent_window);
}
}

Selenium SwitchWindow in IE Issue

I am attempting to switch to a popup window using selenium web driver on IE. When I get to the line that switches to my popup window the code just hangs. I'm looking for ways that I can either attempt to switch the window 10 times and try another attempt after 20 seconds as I tried to do below or a better way to ensure the windows switches properly. If I manually close the popup I get noSuchWindow Exceptions and the code bombs out. I've reviewed other stackoverflow articles before posting this, but I believe my issue is unique. Here is my scenario:
Scenario:
1. Retrieve parent window handle
2. Perform action launching popup window
3. Get the popup window handles and store them in a string set
4. Loop through window handles until there are no more. Retrieve Popup window handle
5. Loop until the popup window does not match the parent windows handle and if 20 seconds has passed
6. Switch to popup ---Code Hangs Here---
7. Retrieve popup title
8. Close popup
9. Switch to parent
10. Verification of title
Below is all relevant code to the above scenario:
String popupWindow = "";
String parentWindow = "";
int saveCount = 0;
int getPopupCount = 0;
int tryCount = 0;
// Get Parent window handle
parentWindow = driver.getWindowHandle();
System.out.println("parentWindow: " + parentWindow);
Thread.sleep(500);
//Perform Action launching popup window
//Get the popup window handles and store them in a string set
Set<String> popups = driver.getWindowHandles();
saveCount = getPopupCount;
try {
tryCount = 0;
//Loop until the popup count does not equal the save count or until 10 tries (20 seconds) have passed
while (saveCount == getPopupCount && tryCount++ < 10) {
//Wait 2 second
Thread.sleep(2000);
getPopupCount = popups.size();
System.out.println("getPopupCount: -" + getPopupCount + "-");
}//end while
if (tryCount >= 10) {
System.out.println("Failed after 10 tries");
}//end if
//Loop through window handles until there are no more. Retrieve Popup window handle
Iterator<String> myIterator = popups.iterator();
while (myIterator.hasNext()) {
popupWindow = myIterator.next();
System.out.println("popupWindow: " + popupWindow);
System.out.println("Boolean should be false: " + parentWindow.equalsIgnoreCase(popupWindow));
Thread.sleep(5000);
//fetch starting time
long startTime = System.currentTimeMillis();
//Loop until the popup window does not match the parent windows handle and if 20 seconds has passed
while(!parentWindow.equalsIgnoreCase(popupWindow) && (System.currentTimeMillis()-startTime) < 20000) {
try{
Thread.sleep(500);
//Switch to the Popup window
//TODO - This is where it fails
driver.switchTo().window(popupWindow);
Thread.sleep(500);
System.out.println(driver.getTitle());
popupTitle = driver.getTitle();
//Close the Popup Window
driver.close();
} catch (Exception e) {
throw new RuntimeException(Thread.currentThread().getStackTrace()[1].getMethodName()
+ "...Error: " + e.getMessage());
}//end catch
}//end if
}//end while
} catch(Exception e) {
throw new RuntimeException(Thread.currentThread().getStackTrace()[1].getMethodName()
+ "...Error switching to and closing popup: " + e.getMessage());
}//end catch
//Switch to parent window.
driver.switchTo().window(parentWindow);
driver.manage().window().maximize();
Thread.sleep(2000);
//Verification of title
Assert.assertTrue(popupTitle.contains("MYTITLE"));
CI Info:
JDK: 1.8.0_66
Java: Version 8
IE: 11
Other similar issues that didn't answer my question:
switchWindow does not work in IE
How to switch to the new browser window, which opens after click on the button?
How to exit a while loop after a certain time?
Any help or feedback is greatly appreciated!
Using the below code I tested against both my private code and the http://demo.guru99.com/popup.php demo pop up site. My code works fine against that site, but fails on my private site. I implementing wait periods, however I don't believe it's a timing issue. I simply believe the popup isn't compatible on IE with Selenium on my private site. Posting my code that works on the dummy site as an answer in case someone else has similar issues as the code is valid.
//Retrieve parent window handle
parentWindow = driver.getWindowHandle();
//Loop through the window handles until you are on the popup window
for(String popupWindow : driver.getWindowHandles()){
if (driver.switchTo().window(popupWindow).getTitle().equals(myTitle)) {
break;
}
else {
driver.switchTo().window(parentWindow);
}
}
//Store the title
popupTitle = driver.getTitle();
//Close the Popup Window
driver.close();
//switch to parent window.
driver.switchTo().window(parentWindow);
driver.manage().window().maximize();
//Verification of title
Assert.assertTrue(popupTitle.toUpperCase().contains(myTitle));

How to close the new windows in firefox that open after extracting elements from div using webdriver?

Webdriver launches multiple windows after performing click action. I have tried driver.close() but it close the webdriver and test fails.
WebDriver driver = new FirefoxDriver ();
driver.get("http://www.xyz.com/");
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement page = driver.findElement(By.className("coupon-rows"));
List <WebElement> coupontrigger = page.findElements(By.className("code"));
System.out.println("number of couponsTriggers on carousel = "+ "coupontrigger.size());
for (int j=0; j<=coupontrigger.size(); j++) {
js.executeScript("$('.ccode.coupon-trigger').eq("+j+").click()");
System.out.println(driver.getTitle());
driver.switchTo().defaultContent();
driver.get("http://www.xyz.com/");
page = driver.findElement(By.className("coupon-rows"));
coupontrigger = page.findElements(By.className("code"));
}
}
If I understood your requirement you want to close the other popups rather than the main window. In that case you can do below. Though I am not 100% sure of your requirement.
String mwh=driver.getWindowHandle(); // Get current window handle
Set<String> s=driver.getWindowHandles();
Iterator<String> ite=s.iterator();
String popupHandle = "";
while(ite.hasNext())
{
popupHandle = ite.next().toString();
if(!popupHandle.contains(mwh)) // If not the current window then shift focus and close them
{
driver.switchTo().window(popupHandle);
driver.close();
}
}
driver.switchTo().window(mwh); // finally move control to main window.
You can introduce a helper method which will do that task for you. You just need to find out what your current view is (WebDriver#getWindowHandle will give the one you have focus on) and then just close the rest of the windows.
private String closeAllpreviouslyOpenedWindows() {
String firstWindow = webDriver.getWindowHandle();
Set<String> windows = webDriver.getWindowHandles();
windows.remove(firstWindow);
for (String i : windows) {
webDriver.switchTo().window(i);
webDriver.close();
}
webDriver.switchTo().window(firstWindow);
return firstWindow;
}

How to check if facebook popup appears on tapping on a button in selenium?

I am writing a stepdefinition for Cucumber Scenario ,in the When clause I click on a button that brings a popup window for facebook share.
Will the driver automatically be focused on the popup window ?
Or I will have to access it via code.
I want to verify the url of the popup to check if its correct or not in the Then clause.
Once there is a popup, the driver will not automatically focus on the popup. You need to handle it via code.
Here is how I would handle popups.
String parentWindowHandler = driver.getWindowHandle(); // Store your parent window
String subWindowHandler = null;
Set<String> handles = driver.getWindowHandles(); // get all window handles
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
subWindowHandler = iterator.next();
}
driver.switchTo().window(subWindowHandler); // switch to popup window
// perform operations on popup
driver.switchTo().window(parentWindowHandler); // switch back to parent window

How to switch to the new browser window, which opens after click on the button?

I have situation, when click on button opens the new browser window with search results.
Is there any way to connect and focus to new opened browser window?
And work with it, then return back to original(first) window.
You can switch between windows as below:
// Store the current window handle
String winHandleBefore = driver.getWindowHandle();
// Perform the click operation that opens new window
// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
}
// Perform the actions on new window
// Close the new window, if that window no more required
driver.close();
// Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);
// Continue with original browser (first window)
Just to add to the content ...
To go back to the main window(default window) .
use driver.switchTo().defaultContent();
This script helps you to switch over from a Parent window to a Child window and back cntrl to Parent window
String parentWindow = driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles();
for(String windowHandle : handles)
{
if(!windowHandle.equals(parentWindow))
{
driver.switchTo().window(windowHandle);
<!--Perform your operation here for new window-->
driver.close(); //closing child window
driver.switchTo().window(parentWindow); //cntrl to parent window
}
}
I use iterator and a while loop to store the various window handles and then switch back and forth.
//Click your link
driver.findElement(By.xpath("xpath")).click();
//Get all the window handles in a set
Set <String> handles =driver.getWindowHandles();
Iterator<String> it = handles.iterator();
//iterate through your windows
while (it.hasNext()){
String parent = it.next();
String newwin = it.next();
driver.switchTo().window(newwin);
//perform actions on new window
driver.close();
driver.switchTo().window(parent);
}
Surya, your way won't work, because of two reasons:
you can't close driver during evaluation of test as it will loose focus, before switching to active element, and you'll get NoSuchWindowException.
if test are run on ChromeDriver you`ll get not a window, but tab on click in your application. As SeleniumDriver can't act with tabs, only switchs between windows, it hangs on click where new tab is being opening, and crashes on timeout.
Modify registry for IE:
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main
Right-click → New → String Value → Value name: TabProcGrowth (create if not exist)
TabProcGrowth (right-click) → Modify... → Value data: 0
Source: Selenium WebDriver windows switching issue in Internet Explorer 8-10
For my case, IE began detecting new window handles after the registry edit.
Taken from the MSDN Blog:
Tab Process Growth : Sets the rate at which IE creates New Tab processes.
The "Max-Number" algorithm: This specifies the maximum number of tab processes that may be executed for a single isolation session for a single frame process at a specific mandatory integrity level (MIC). Relative values are:
TabProcGrowth=0 : tabs and frames run within the same process; frames are not unified across MIC levels.
TabProcGrowth =1: all tabs for a given frame process run in a single tab process for a given MIC level.
Source: Opening a New Tab may launch a New Process with Internet Explorer 8.0
Internet Options:
Security → Untick Enable Protected Mode for all zones (Internet,
Local intranet, Trusted sites, Restricted sites)
Advanced → Security → Untick Enable Enhanced Protected Mode
Code:
Browser: IE11 x64 (Zoom: 100%)
OS: Windows 7 x64
Selenium: 3.5.1
WebDriver: IEDriverServer x64 3.5.1
public static String openWindow(WebDriver driver, By by) throws IOException {
String parentHandle = driver.getWindowHandle(); // Save parent window
WebElement clickableElement = driver.findElement(by);
clickableElement.click(); // Open child window
WebDriverWait wait = new WebDriverWait(driver, 10); // Timeout in 10s
boolean isChildWindowOpen = wait.until(ExpectedConditions.numberOfWindowsToBe(2));
if (isChildWindowOpen) {
Set<String> handles = driver.getWindowHandles();
// Switch to child window
for (String handle : handles) {
driver.switchTo().window(handle);
if (!parentHandle.equals(handle)) {
break;
}
}
driver.manage().window().maximize();
}
return parentHandle; // Returns parent window if need to switch back
}
/* How to use method */
String parentHandle = Selenium.openWindow(driver, by);
// Do things in child window
driver.close();
// Return to parent window
driver.switchTo().window(parentHandle);
The above code includes an if-check to make sure you are not switching to the parent window as Set<T> has no guaranteed ordering in Java. WebDriverWait appears to increase the chance of success as supported by below statement.
Quoted from Luke Inman-Semerau: (Developer for Selenium)
The browser may take time to acknowledge the new window, and you may
be falling into your switchTo() loop before the popup window appears.
You automatically assume that the last window returned by
getWindowHandles() will be the last one opened. That's not necessarily
true, as they are not guaranteed to be returned in any order.
Source: Unable to handle a popup in IE,control is not transferring to popup window
Related Posts:
Selenium switching to new Tab in
IE
How to open new tab in IE using selenium (java) and open a url in
that tab (not
window)
You could use:
driver.SwitchTo().Window(WindowName);
Where WindowName is a string representing the name of the window you want to switch focus to. Call this function again with the name of the original window to get back to it when you are done.
main you can do :
String mainTab = page.goToNewTab ();
//do what you want
page.backToMainPage(mainTab);
What you need to have in order to use the main
private static Set<String> windows;
//get all open windows
//return current window
public String initWindows() {
windows = new HashSet<String>();
driver.getWindowHandles().stream().forEach(n -> windows.add(n));
return driver.getWindowHandle();
}
public String getNewWindow() {
List<String> newWindow = driver.getWindowHandles().stream().filter(n -> windows.contains(n) == false)
.collect(Collectors.toList());
logger.info(newWindow.get(0));
return newWindow.get(0);
}
public String goToNewTab() {
String startWindow = driver.initWindows();
driver.findElement(By.cssSelector("XX")).click();
String newWindow = driver.getNewWindow();
driver.switchTo().window(newWindow);
return startWindow;
}
public void backToMainPage(String startWindow) {
driver.close();
driver.switchTo().window(startWindow);
}
So the problem with a lot of these solutions is you're assuming the window appears instantly (nothing happens instantly, and things happen significantly less instantly in IE). Also you're assuming that there will only be one window prior to clicking the element, which is not always the case. Also IE will not return the window handles in a predictable order. So I would do the following.
public String clickAndSwitchWindow(WebElement elementToClick, Duration
timeToWaitForWindowToAppear) {
Set<String> priorHandles = _driver.getWindowHandles();
elementToClick.click();
try {
new WebDriverWait(_driver,
timeToWaitForWindowToAppear.getSeconds()).until(
d -> {
Set<String> newHandles = d.getWindowHandles();
if (newHandles.size() > priorHandles.size()) {
for (String newHandle : newHandles) {
if (!priorHandles.contains(newHandle)) {
d.switchTo().window(newHandle);
return true;
}
}
return false;
} else {
return false;
}
});
} catch (Exception e) {
Logging.log_AndFail("Encountered error while switching to new window after clicking element " + elementToClick.toString()
+ " seeing error: \n" + e.getMessage());
}
return _driver.getWindowHandle();
}
This feature works with Selenium 4 and later versions.
// Opens a new tab and switches to new tab
driver.switchTo().newWindow(WindowType.TAB);
// Opens a new window and switches to new window
driver.switchTo().newWindow(WindowType.WINDOW);
If you have more then one browser (using java 8)
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TestLink {
private static Set<String> windows;
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("file:///C:/Users/radler/Desktop/myLink.html");
setWindows(driver);
driver.findElement(By.xpath("//body/a")).click();
// get new window
String newWindow = getWindow(driver);
driver.switchTo().window(newWindow);
// Perform the actions on new window
String text = driver.findElement(By.cssSelector(".active")).getText();
System.out.println(text);
driver.close();
// Switch back
driver.switchTo().window(windows.iterator().next());
driver.findElement(By.xpath("//body/a")).click();
}
private static void setWindows(WebDriver driver) {
windows = new HashSet<String>();
driver.getWindowHandles().stream().forEach(n -> windows.add(n));
}
private static String getWindow(WebDriver driver) {
List<String> newWindow = driver.getWindowHandles().stream()
.filter(n -> windows.contains(n) == false).collect(Collectors.toList());
System.out.println(newWindow.get(0));
return newWindow.get(0);
}
}

Categories

Resources