In Selenium how to handle a new window? - selenium-webdriver

I am writing a selenium script to login and create new mail, send it and logout. But when I click on New mail button, it opens a new window. In selenium how I can handle this. I am new to selenium. Please explain in detail.

Use the below code, you have to use getWindowHandles- I hope it helps, Let me know in case you get stuck anywhere else -
#Test
public void multipleWindows() {
driver.get(URL+"/windows");
driver.findElement(By.cssSelector(".example a")).click();
Object[] allWindows = driver.getWindowHandles().toArray();
driver.switchTo().window(allWindows[0].toString());
Assert.assertNotEquals(driver.getTitle(), "New Window");
driver.switchTo().window(allWindows[1].toString());
Assert.assertEquals(driver.getTitle(), "New Window");
}
}

How to get Window Handle:
String handle = driver.getWindowHandle();
If there are multiple window gets opened when you click on any link,button etc... then to get "window Handle" of each window -
Set windowHandles = driver.getWindowHandles();
"getWindowHandles()" : method return window handle (unique id for each opened window) so that the return type is set. Because set will not contain duplicate elements so here getWindowHandles return unique id/window handles for each winodw and stored in Set.
How to switch to correct / appropriate window:
Basically there are two ways to switch to appropriate window.
By using windowName
driver.switchTo().window( "windowName" );
OR
To get current/parent/default window handle:
String handle = driver.getWindowHandle();
driver.switchTo().window( handle );
OR
Set < String > windowHandles = driver.getWindowHandles();
for(String handle : windowHandles )
{
driver.swicthTo().window( handle );
}
Example of Handling Multiple Windows In Selenium

Try this code, it is very easy to understand.
WebDriver driver = new FirefoxDriver();
driver.get("http://demo.guru99.com/popup.php");
driver.findElement(By.xpath("html/body/p/a")).click();
// return the parent window name as a String
String parentWindow=driver.getWindowHandle();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Pass a window handle to the other window
for(String childWindow: driver.getWindowHandles())
{
System.out.println("Switch to child window");
//switch to child window
driver.switchTo().window(childWindow);
//find an element and print text of it
WebElement textLabel=driver.findElement(By.xpath("html/body/div[1]/h2"));
System.out.println(" text: "+textLabel.getText());
driver.close();
}
System.out.println("Get back to parent window");
//switch to Parent window
driver.switchTo().window(parentWindow);
//find an element and print text of it
WebElement logotext=driver.findElement(By.xpath("html/body/div[1]/h2"));
System.out.println("text: "+logotext.getText());
driver.close();
}

Related

Unable to handle the new window

I have a situation(mentioned below) due to which my selenium script is failing. Can someone help me?
I have a webpage where there is a save button, clicking on save button opens a new popup window. My requirement is to switch to the new window and click on one of the buttons(in the new window) which will automatically close the window and navigates to some other page. I have written a code which actually works fine but sometimes due to the application problem the new window is not getting closed. And due to this my script is failing. Here is the code I have used.
public void test() {
// i have two pages gets involved in this scenario
driver.get("some url"); // user is in page 1
// clicking on save button
driver.findElement(By.xpath("some xpath")).click(); // a new window opens
Set<String> winIDS = driver.getWindowHandles();
if (winIDS.size() > 1) {
Iterator<String> it = winIDS.iterator();
it.next();
String childWindow = it.next();
driver.switchTo().window(childWindow);
driver.findElement(By.xpath("some xpath")).click();
//after clicking on this button the user is navigated to page2
}
// after clicking on the button in the new window the new window gets closed and the user is navigate to page 2 as mentioned before.
// To validate if that has happened i am using the below code so that my test case flow wont be stopped. But
// the code is getting hanged at the new window as the app fails to perform the button click action on the new window.
winIDS = driver.getWindowHandles();
if(winIDS.size() > 1)
{
Iterator<String> it = winIDS.iterator();
it.next();
String childWindow = it.next();
driver.switchTo().window(childWindow);
driver.close();
//i m making the test failed here as the new window is not closed.
}
}
Looking at your code, I can see that you do twice the iteration to next window:
it.next();
String childWindow = **it.next();**
The second it.next() is obsolet.
Hope this solvs your issue.

Below code is not handelling new window in selenium webdriver

To handle multiple windows I have written below code. Its not giving me any error, however no action is getting performed on new window. Can you please help me to fix this issue or suggest me any other way. Thanks!
Code:
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
FirefoxDriver dw2 = new FirefoxDriver();
dw2.get("http://quercus0638v.quercus.kpn.org:90");
//OPEN login and provide credentials
dw2.manage().window().maximize();
Thread.sleep(2000);
dw2.findElement(By.id("ContentPlaceHolder1_GebruikersnaamTextBox")).clear();
dw2.findElement(By.id("ContentPlaceHolder1_GebruikersnaamTextBox")).sendKeys("behdse");
dw2.findElement(By.id("ContentPlaceHolder1_WachtwoordTextBox")).clear();
dw2.findElement(By.id("ContentPlaceHolder1_WachtwoordTextBox")).sendKeys("fiet$hok");
//Login : Clcik on Login button
dw2.findElement(By.id("ContentPlaceHolder1_LoginButton")).click();
//Click on Select button. After that new window will open
dw2.findElement(By.id("ContentPlaceHolder1_CWDatumRadioButton")).click();
// Below code I written to get the window handles
Set<String> AllWindowHandles = dw2.getWindowHandles();
String window1 = (String) AllWindowHandles.toArray()[0];
System.out.print("window1 handle code = "+AllWindowHandles.toArray()[0]);
String window2 = (String) AllWindowHandles.toArray()[1];
System.out.print("\nwindow2 handle code = "+AllWindowHandles.toArray()[1]);
//Switch to window2(child window) and performing actions on it.
dw2.switchTo().window(window2);
//Click the user
dw2.findElement(By.id("AfdelingGebruikersListView_RowCheckBox_8")).click();
//Click on OK button after selecting User
dw2.findElement(By.id("AfdelingGebruikersListView_OKButton")).click();
//Switch to window1(child window) and performing actions on it.
dw2.switchTo().window(window1);
//Click the order type you want to retrieve
dw2.findElement(By.id("ContentPlaceHolder1_VerwerktRadioButton")).click();
//Click for exporting the data to Excel Sheet
dw2.findElement(By.id("ContentPlaceHolder1_ExporteerNaarExcelButton")).click();
}
U can switch to windows using:
for (String winHandle : objDriver.getWindowHandles()) {
objDriver.switchTo().window(winHandle);
}
This will switch to the last window opened. To get back to parent window by again using the above code. It would be better that u incorporate the code in a different method in order to reuse.
Hope this helps. Thanks.
Editing the Code as per the comment by OP :-
Since, as I suggested in comment, it might not be a new window. It must be a pop-up. So, please replace your code as below and try:
//Click on Select button. After that new window will open
dw2.findElement(By.id("ContentPlaceHolder1_CWDatumRadioButton")).click()
//Click the user
try{
WebDriverWait wait = new WebDriverWait(dw2,20);
WebElement ele = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("AfdelingGebruikersListView_RowCheckBox_8")));
ele.click();
}catch(Throwable e){
System.err.println("Error while clicking on the element. "+e.getMessage());
}
//Click on OK button after selecting User
dw2.findElement(By.id("AfdelingGebruikersListView_OKButton")).click();

How can I check a checkbox on the popup window? Selenium Webdriver

When a popup window open how can I handle on this window?
driver.switchTo().defaultContent();
MenuUtil.doClickMenu(selenium, driver, "Access 2G", "Cảnh báo", "Giám sát cảnh báo BTS");
ControlBase.waitForLoadOk(5);
CheckBoxUtil.doCheckByXpath(selenium, "//*[#id='listRow1']/tbody/tr[1]/td[18]/input");
ControlBase.waitForLoadOk(5);
ButtonUtil.doClickByLabel(driver, "Cập nhật");
ControlBase.waitForLoadOk(5);
CheckBoxUtil.doCheckByXpath(selenium, "//*[#id='txtName']");
Generally I use the Selenium IDE. Here you can 'click & record', which allows you to then get the XPath of the JS pop-up alert box.
I would suggest you first check for the alert box showing up with something such as this:
if (selenium.isAlertPresent()){
System.out.println(selenium.getAlert()); //show alert text message
selenium.click("id=alertbox_ok_btn"); //click OK on alert box
}
Download Selenium IDE from here: http://docs.seleniumhq.org/download/
Also, refer to Selenium's documentation for Java here: http://selenium.googlecode.com/svn/trunk/docs/api/java/index.html
Try the below code written in JAVA
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("Your application URL");
String parentWindow = driver.getWindowHandle();
//click on the link/box/whatever to open the pop up
driver.findElement(By.xpath("")).click();
Set <String> popupWindows = driver.getWindowHandles();
for(String popup : popupWindows){
driver.switchTo().window(popup);
//you can use getTitle/getCurrentUrl to match with title/url of the pop up
if(driver.getTitle().equals("actual title on the pop up")){
break;
}
}
//Write a code to check a checkbox
//Close the pop up
driver.close();
//Come back to the parent window
driver.switchTo().window(parentWindow);
//Code if you want to test/do something else
driver.close();

Could not switch between browsers in selenium webdriver

Iam trying to switch between browser ie on click of a button it launches a new browser it
is finding the handle ..the problem is it is not able to find the object inside the new browser searched with id,xpath,name etc can some one give me any suggestion on the same.
also it is able to match the url as well.
please provide me the solution on the same.
below is the code.
//Previous screen
Set windows = driver1.getWindowHandles();
driver1.findElement(By.id("findButton")).click();
//switching handle for the new screen
driver1.switchTo().window("Customer Search");
driver1.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
int i = 1;
while(i<= 10){
for (String handle : driver1.getWindowHandles()) {
String myTitle = driver1.switchTo().window(handle).getTitle();
System.out.println("myTitle value : " +myTitle);
//customer search is the new window title
if(myTitle.equalsIgnoreCase("Customer Search")){
driver1.manage().window().maximize();
//if i pass the right url of the screen that is also matching here i have given dummy("sshsj")
if(driver1.getCurrentUrl().equalsIgnoreCase("sshsj"));
{
System.out.println("Url is matching");
//But not able the recognise the object on the new window.
driver1.findElement(By.xpath("html/body/left/form/table/tbody/tr[2]/td[1]/input")).sendKeys("kamal");
}
You can use JS to open a new window, it's faster.
IJavaScriptExecutor jscript = driver as IJavaScriptExecutor;
jscript.ExecuteScript("window.open()");
Then to switch windows, use the window handles:
List<string> handles = driver.WindowHandles.ToList<string>();
driver.SwitchTo().Window(handles.Last());
driver.get(url);
driver.findElement(By.xpath("html/body/left/form/table/tbody/tr[2]/td[1]/input")).sendKeys("kamal");
It is possible that the element may be present inside an iframe. In that case, you need to switch to that iframe before you can access any element inside the iframe.

Is it possible to re-show and closed dialog window?

Some context here...I have a System.Windows.Window that is used to display a modal message box. I created a Show() method that initializes the content of the window, and then calls ShowDialog(). The user clicks a button on this window, some information about the clicked button is set in the Tag property, and then the window is closed via Close().
As expected, I get a ShowDialog Exception when attempting to call ShowDialog() on the Window once is has been closed. Is there some way to reuse that same Window instance so that I don't have to new up an instance every time I need a message box?
For example...
MessageBoxWindow mbw = new MessageBoxWindow();
result = mbw.Show("caption", "message 1");
mbw.Show("caption", "message 2");
// The above throws an exception, so I have to do this...
mbw = new MessageBoxWindow();
result = mbw.Show("caption", "message 2");
Any help would be greatly appreciated!
Use .Hide() instead of .Close(). That removes it without destroying it. Then you can call Show() again when needed.
MainWindow test = new MainWindow();
test.Show();
test.Hide();
test.Show();
You can add a FormClosing event that cancels the form close and instead sets the Form.Visible to false. Then you would also need Show method that checks if this Form is null, so you would know whether you need to create a new Form or just show the one you already have.
For example:
private void FormMessageBox_FormClosing(object sender, FormClosingEventArgs e)
{
//This stops the form from being disposed
e.Cancel = true;
this.Visible = false;
}
public static void Show(FormMessageBox formMessageBox, string message)
{
//if formMessageBox is null we need to create a new one otherwise reuse.
if (formMessageBox == null)
{
formMessageBox = new FormMessageBox(message);
formMessageBox.ShowDialog();
}
else
{
formMessageBox.lblMessage.Text = message;
formMessageBox.Visible = true;
}
}

Resources