Handling New Web Browser Window in Selenium WebDriver - automation

When I click on Help Screen in a web page, it opens a new web browser window containing information of of help webpage. I wanted to read some text or title of that webpage, but i can't able to read anything of that help window. The main objective in this case is to verify the help screen content and close that help window after verifying the help screen. The code i'm using is as follows:
public void verifyNewWindow(String buttonId, String screenShotFileName)
{
String winHandleBefore = driver.getWindowHandle();
clickOnButton(buttonId); //Clicking on help button on a webpage, help id is passed from baseclass)
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
for(String winHandle : driver.getWindowHandles()){
if(!winHandle.equals(winHandleBefore))
{
driver.switchTo().window(winHandle);
takeScreenShot(screenShotFileName);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.close();
break;
}
}
driver.switchTo().window(winHandleBefore);
}

First get the window handles(not handle) after opening the new window.
Set<String> windows = driver.getWindowHandles();
Once you get the window handles then iterate through them and get the child window handle as below;
String parent = null;
String child = null;
Iterator it = windows.iterator();
while(it.hasNext())
{
parent = it.next();
child = it.next();
}
Then switch to the child window.
driver.switchTo().window(child);

Related

Handling a button that opens a new tab and redirects you to it

After clicking the create invoice button, it opens a new tab and redirects you to it. Next, it should click a button but it says no element exists. Did it search the element on the current page ? not on the new tab?
Tried explicit wait for that button and tried switching back and forth to the tab
#Test (priority=3)
public void ProductListExpress() {
driver.findElement(By.className("bttn-imp-create")).click();
System.out.println("Successful in proceeding to Purchase.php");
String newUrl1 = driver.getCurrentUrl();
if(newUrl1.equalsIgnoreCase("http://localhost:82/purchase.php")){
System.out.println("Successful in proceeding to Purchase page ");
}
else {
System.out.println("Failed in proceeding to Purchase page");
}
}
#Test (priority=4)
public void ClickInvoice() {
}
#Test (priority=5)
public void test() {
//Click create invoice button
driver.findElement(By.name("btncreateinvoice")).click();
System.out.println("Successful in clicking create invoice");
}
Expect to click button after redirecting.
First of all wait for 2nd window to open and be available to the WebDriver. You can use Explicit Wait for this like:
new WebDriverWait(driver,10).until(ExpectedConditions.numberOfWindowsToBe(2));
Check out How to use Selenium to test web applications using AJAX technology article for more information on the concept
Once you have the confidence that the number of windows is 2 you can use switchTo().window() function to change the context for the 2nd window:
driver.switchTo().window(driver.getWindowHandles().stream().reduce((f, s) -> s).orElse(null));
When you are clicking on new button, new tab is getting open. In this scenario, you need to use WindowsHandles. Try below code:
#Test (priority=3)
public void ProductListExpress() {
driver.findElement(By.className("bttn-imp-create")).click();
System.out.println("Successful in proceeding to Purchase.php");
Set<String> winHandles= driver.getWindowHandles();
Iterator<String> it = winHandles.iterator();
String parentWindowId = it.next();
String newWindowID= it.next();//Here you will get windows id of newly opened tab
driver.switchTo().window(newWindowID); //now your driver is switching to new tab
String newUrl1 = driver.getCurrentURL();
if(newUrl1.equalsIgnoreCase("http://localhost:82/purchase.php")){
System.out.println("Successful in proceeding to Purchase page ");
}
else {
System.out.println("Failed in proceeding to Purchase page");
}
}
You can switch to new tab with this way :
//Click create invoice button
driver.findElement(By.name("btncreateinvoice")).click();
System.out.println("Successful in clicking create invoice");
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
during execution whenever a new tab or window opens, control of the driver still remains in the original tab or window unless we write couple of lines of code to manually switch the control to new tab or window.
In your case, Since the driver control is still in original tab and next element to click is in new tab, selenium is not able to find it, hence it says no element exists
#Test (priority=5)
public void test() {
WebDriverWait w= new WebDriverWait(driver, 10);
ArrayList<String> x = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(x.get(1)); // here x.get(1) indicates that
driver control is switched to new tab or new window
w.until(ExpectedConditions.elementToBeClickable("locator of button to be clicked"));
}
In case ,in your next steps if you can to continue execution in the original window or tab, you have to again switch selenium driver control back .
driver.switchTo().window(x.get(0));// during next steps if you want
driver control to switch back to original tab or window you have to write this line
of code
IDK if this is what you're asking, but it might be. I was CTRL+CLICKING a button to open a new tab. This is how I found the tab:
Set<String> curWindows = new HashSet<> (driver.getWindowHandles ());
String newWindowHandle = null;
a.keyDown(Keys.LEFT_CONTROL).click(THE_BUTTON).keyUp(Keys.LEFT_CONTROL).build().perform();
this.delay (500);
for (String windowHandle : driver.getWindowHandles ()) {
if (curWindows.contains (windowHandle) == false) {
newWindowHandle = windowHandle;
break;
}
}
if (newWindowHandle == null) {
log.error ("Unable to find the new window handle.");
return null;
}

How to Navigate between multiple browser windows using serinity

Serenity is a BDD based on selenium . I am using 3 window handlers . My requirement is something like this -
Open window 1
click an element on window 1 that will open window 2
3.click an element on window 2 that will open window 3
close all windows
All window handlers are getting inputs fine but still I am not able to switch between the windows
This worked a bit fine for me in handling upto 2 windows but not for 3 -
public class MultipleWindowsHandle {
WebDriver driver;
#Before
public void setup() throws Exception {
driver=new FirefoxDriver();
String URL="http://www.seleniummaster.com";
driver.get(URL);
driver.manage().window().maximize();
}
#Test
public void test() throws Exception {
// Opening site
driver.findElement(By.xpath("//img[#alt='SeleniumMasterLogo']")).click();
// Storing parent window reference into a String Variable
String Parent_Window = driver.getWindowHandle();
// Switching from parent window to child window
for (String Child_Window : driver.getWindowHandles())
{
driver.switchTo().window(Child_Window);
// Performing actions on child window
driver.findElement(By.id("dropdown_txt")).click();
List dropdownitems=driver.findElements(By.xpath("//div[#id='DropDownitems']//div"));
int dropdownitems_Size=dropdownitems.size();
System.out.println("Dropdown item size is:"+dropdownitems_Size);
((WebElement) dropdownitems.get(1)).click();
driver.findElement(By.xpath("//*[#id='anotherItemDiv']")).click();
}
//Switching back to Parent Window
driver.switchTo().window(Parent_Window);
//Performing some actions on Parent Window
driver.findElement(By.className("btn_style")).click();
}
#After
public void close() {
driver.quit();
}
}
//In first window - Do something to activate second window
//Actions ..... here
//Second window opens
//Following code handles second window
ArrayList<String> newTab = new ArrayList (getDriver().getWindowHandles());
getDriver().switchTo().window(newTab.get(1));
//In second window - do some actions here
ArrayList<String> newTabs = new ArrayList<String> getDriver().getWindowHandles());
getDriver().switchTo().window((newTabs.get(2)));
//In Third Window
//Do some actions here
//Close Third Window
getDriver().close(); //Disable if the action in third window closes third window like Cancel/OK button
//Switch back to second window
getDriver().switchTo().window(newTab.get(1));
//Close Second Window
getDriver().close();
//ghet back to initial (First) window
getDriver().switchTo().window(newTab.get(0));

How to handle pop-up window using Selenium? ("driver.switchTo().window(winHandle);" not working consistently)

We are facing some issue in switching to new window after clicking on the link/button
I was using the below code for switching to new window.
elem.click();
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle); }
Observed that scripts runs inconsistently, It will be great if i get some consistent code for switching to new window. I feel there is a synchronization issue while switching to new window.
If #HelpingHands suggestion will not work the problem may lies in the several handlers exist simultaneously
The following code may help:
When you create the driver please save the appropriated handler
driver = new FirefoxDriver(profile);
driver.get(uri);
MainWinHandler = driver.getWindowHandle();
Then in order to switch
for(String winHandle : driver.getWindowHandles()){
if(!winHandle.equals(MainWinHandler))
driver.switchTo().window(winHandle);
}
Tried to use in below mentioned format
`driver = new FirefoxDriver(profile);
driver.get(uri);
String parentWindowHandlerP = driver.getWindowHandle();
elem.click();
while (driver.getWindowHandles().size() < 2) {
Thread.sleep(500);
}
Set<String> handles = driver.getWindowHandles();
for (String windowHandle : handles) {
if (!windowHandle.equals(parentWindowHandlerP)) { driver.switchTo().window(windowHandle);
}
}`

Not able to move to Parent window after selecting a value in the Child window using selenium

I used the below code to switch the window to child window and select a radio-button and switch back to parent window to select few values,but after selecting a value in the child window it doesn't allow me to select a value in the parent window
It says "unable to locate element"
fd.findElementByXPath("//*[#id='image22']").click();
String parentwindowRMU=fd.getWindowHandle();
Set<String> handles1=fd.getWindowHandles();
for(String Windowhandles1:handles1)
{
if(!Windowhandles1.equals(parentwindowRMU))
{
fd.switchTo().window(Windowhandles1);
Thread.sleep(7000);
fd.findElementByXPath("//*[#id='radio1']").click();
fd.findElementByXPath("//*[#id='ext-gen31']").click();
Thread.sleep(5000);
break;
}
}
fd.switchTo().window(parentwindowRMU);
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);
}
I am using similar code like this:
click on New button
Another window will open to fill up the form
Click on Done button
Now click on Submit button on previous Window
Logout the application
Below is my code:
String parentWindow = driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles();
for(String windowHandle : handles)
{
if(!windowHandle.equals(parentWindow))
{
driver.switchTo().window(windowHandle);
driver.findElement(By.id("student_fname1")).clear();
driver.findElement(By.id("student_fname1")).sendKeys("test");
driver.findElement(By.id("student_lname1")).clear();
driver.findElement(By.id("student_lname1")).sendKeys("auto");
driver.findElement(By.id("student_username1")).clear();
driver.findElement(By.id("student_username1")).sendKeys("testuser5");
driver.findElement(By.id("student_password1")).clear();
driver.findElement(By.id("student_password1")).sendKeys("password");
new Select(driver.findElement(By.id("student_grade1"))).selectByVisibleText("testvalue");
driver.findElement(By.name("submit_done")).click();
driver.switchTo().window(parentWindow); //cntrl to parent window
driver.findElement(By.className("frm_btn")).click();//button on parent window
driver.findElement(By.linkText("Logout")).click();//button on parent window
}
}
Use below code and see if it works or not
fd.findElementByXPath("//*[#id='image22']").click();
String parentwindowRMU=fd.getWindowHandle();
Set<String> handles1=fd.getWindowHandles();
for(String Windowhandles1:handles1)
{
if(!Windowhandles1.equals(parentwindowRMU))
{
fd.switchTo().window(Windowhandles1);
Thread.sleep(7000);
fd.findElementByXPath("//*[#id='radio1']").click();
fd.close();
fd.findElementByXPath("//*[#id='ext-gen31']").click();
Thread.sleep(5000);
fd.switchTo().window(parentwindowRMU);
//code to perform on parent window.
}
}
As per my understanding your code is fine the problem may be of xpath not used properly to locate element on parent window.
You can use Iterator for this. A sample example to switch between parent and child windows:
WebDriver driver = new FirefoxDriver();
driver.get("https://www.aplha.co.in/");
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.linkText("alpha")).click();
Set<String> windowHandlesAfter = driver.getWindowHandles();
Iterator<String> itAfter = windowHandlesAfter.iterator();
String parent = itAfter.next();
String child = itAfter.next();
driver.switchTo().window(child);
driver.findElement(By.xpath("//img[#alt='Ginger Hotel']")).click();
System.out.println("After clicking on Ginger Hotels on child window");
Set<String> windowHandlesAfter1 = driver.getWindowHandles();
Iterator<String> itAfter1 = windowHandlesAfter1.iterator();
System.out.println("Printing windowHandles" + driver.getWindowHandles());
parent = itAfter1.next();
child = itAfter1.next();
String child1 = itAfter1.next();
driver.switchTo().window(child1);

Handling Child window in selenium

I'm trying to access second level Popup in VCM using TestNG i.e I'm clicking on "Add" button on parent window and it opens then I have other field to add into subcontent but I'm not able select subcontentwindow.
Here is my code:
selenium.open("http://xyz.com/AppConsole");
selenium.type("name=j_username", "username");
selenium.type("name=j_password", "password!");
selenium.click("id=vign-login-button");
selenium.waitForPageToLoad("30000");
selenium.click("id=href_consoleMenus30");
selenium.waitForPageToLoad("30000");
selenium.click("link= Contents");
selenium.waitForPageToLoad("30000");
selenium.click("id=href_VignConsoleForm");
selenium.waitForPopUp("createContentInstance_undefined", "30000");
selenium.selectWindow("name=createContentInstance_undefined");
selenium.click("link=XYZ");
selenium.waitForPageToLoad("30000");
selenium.click("id=o12_hierarchyBrowserForm");
selenium.click("name=cmdOK");
selenium.waitForPageToLoad("30000");
selenium.type("id=ce_f508VgnVCM____", "Testing");
selenium.select("id=ce_060859310VgnVCM____", "label=Counting");
verifyTrue(selenium.isTextPresent("Forms"));
selenium.click("name=coe_relator_butn_add_2468d");
selenium.waitForPopUp("Add/Edit", "90000");
selenium.selectWindow("Add/Edit");
verifyEquals(selenium.getTitle(), "Add/Edit");
I think you can modify the code as follows & it may work fine.
selenium.click("name=coe_relator_butn_add_2468d");
try{
Thread.sleep(5000);
}catch(Exception e){
}
String titles = selenium.getAllWindowTitles();
int i =0;
while(i<titles.length){
if(titles[i].equalsIgnoreCase("Add/Edit"))
break;
i++;
}
selenium.selectWindow(titles[i]);
I'd share with you approach that helped me (I using selenium webDriver+java):
//Store the current window handle
String winHandleBefore = driver.getWindowHandle();
//Perform the click operation that opens new window
fluentWait(By.xpath("....")).click();
driver.manage.timeouts.implicitWait(2,TimeUnit.SECONDS);
//Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
}
String winHandleAfter = driver.getWindowHandle();
// Perform the actions on new window
driver.findElement(By.id("nav_aHighlight")).click();
//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)
.......