Handling Child window in selenium - testing

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

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

Handling New Web Browser Window in Selenium WebDriver

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

How can selenium web driver get to know when the new window has opened and then resume its execution

I am facing an issue in automating a web application using selenium web driver.
The webpage has a button which when clicked opens a new window. When I use the following code, it throws OpenQA.Selenium.NoSuchWindowException: No window found
WebDriver.FindElement(By.Id("id of the button that opens new window")).Click();
//Switch to new window
_WebDriver.SwitchTo().Window("new window name");
//Click on button present on the newly opened window
_WebDriver.FindElement(By.Id("id of button present on newly opened window")).Click();
To solve the above issue I add Thread.Sleep(50000); between the button click and SwitchTo statements.
WebDriver.FindElement(By.Id("id of the button that opens new window")).Click();
Thread.Sleep(50000); //wait
//Switch to new window
_WebDriver.SwitchTo().Window("new window name");
//Click on button present on the newly opened window
_WebDriver.FindElement(By.Id("id of button present on newly opened window")).Click();
It solved the issue, but I do not want to use the Thread.Sleep(50000); statement because if the window takes more time to open, code can fail and if window opens quickly then it makes the test slow unnecessarily.
Is there any way to know when the window has opened and then the test can resume its execution?
You need to switch the control to pop-up window before doing any operations in it. By using this you can solve your problem.
Before opening the popup window get the handle of main window and save it.
String mwh=driver.getWindowHandle();
Now try to open the popup window by performing some action:
driver.findElement(By.xpath("")).click();
Set s=driver.getWindowHandles(); //this method will gives you the handles of all opened windows
Iterator ite=s.iterator();
while(ite.hasNext())
{
String popupHandle=ite.next().toString();
if(!popupHandle.contains(mwh))
{
driver.switchTo().window(popupHandle);
/**/here you can perform operation in pop-up window**
//After finished your operation in pop-up just select the main window again
driver.switchTo().window(mwh);
}
}
You could wait until the operation succeeds e.g., in Python:
from selenium.common.exceptions import NoSuchWindowException
from selenium.webdriver.support.ui import WebDriverWait
def found_window(name):
def predicate(driver):
try: driver.switch_to_window(name)
except NoSuchWindowException:
return False
else:
return True # found window
return predicate
driver.find_element_by_id("id of the button that opens new window").click()
WebDriverWait(driver, timeout=50).until(found_window("new window name"))
WebDriverWait(driver, timeout=10).until( # wait until the button is available
lambda x: x.find_element_by_id("id of button present on newly opened window"))\
.click()
I finally found the answer,
I used the below method to switch to the new window,
public String switchwindow(String object, String data){
try {
String winHandleBefore = driver.getWindowHandle();
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
}
}catch(Exception e){
return Constants.KEYWORD_FAIL+ "Unable to Switch Window" + e.getMessage();
}
return Constants.KEYWORD_PASS;
}
To move to parent window, i used the following code,
public String switchwindowback(String object, String data){
try {
String winHandleBefore = driver.getWindowHandle();
driver.close();
//Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);
//continue with original browser (first window)
}catch(Exception e){
return Constants.KEYWORD_FAIL+ "Unable to Switch to main window" + e.getMessage();
}
return Constants.KEYWORD_PASS;
}
I think this will help u to switch between the windows.
I use this to wait for window to be opened and it works for me.
C# code:
public static void WaitUntilNewWindowIsOpened(this RemoteWebDriver driver, int expectedNumberOfWindows, int maxRetryCount = 100)
{
int returnValue;
bool boolReturnValue;
for (var i = 0; i < maxRetryCount; Thread.Sleep(100), i++)
{
returnValue = driver.WindowHandles.Count;
boolReturnValue = (returnValue == expectedNumberOfWindows ? true : false);
if (boolReturnValue)
{
return;
}
}
//try one last time to check for window
returnValue = driver.WindowHandles.Count;
boolReturnValue = (returnValue == expectedNumberOfWindows ? true : false);
if (!boolReturnValue)
{
throw new ApplicationException("New window did not open.");
}
}
And then i call this method in the code
Extensions.WaitUntilNewWindowIsOpened(driver, 2);
You can wait for another window to pop using WebDriverWait.
First you have to save current handles of all opened windows:
private Set<String> windowHandlersSet = driver.getWindowHandles();
Then you click a button to open a new window and wait for it to pop with:
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(driver -> !driver.getWindowHandles().equals(windowHandlersSet));
Which checks if there is a change to current window handles set comparing to saved one. I used this solutnion writing tests under Internet Explorer where it always takes few seconds to open new window.
WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(max duration you want it to check for new window));
wait.until(ExpectedConditions.numberOfWindowsToBe(2));//here 2 represents the current window and the new window to be opened
Although this question already has answers, none of them was useful to me really since I can't rely on getting any new window, I needed to filter even more, so I started using Dadoh's solution but tweaked it until I came up with this solution, hope it will be of some use to someone.
public async Task<string> WaitUntilNewWindowIsOpen(string expectedWindowTitle, bool switchToWindow, int maxRetryCount = 100)
{
string newWindowHandle = await Task.Run(() =>
{
string previousWindowHandle = _driver.CurrentWindowHandle;
int retries = 0;
while (retries < maxRetryCount)
{
foreach (string handle in _driver.WindowHandles)
{
_driver.SwitchTo().Window(handle);
string title = _driver.Title;
if (title.Equals(expectedWindowTitle))
{
if(!switchToWindow)
_driver.SwitchTo().Window(previousWindowHandle);
return handle;
}
}
retries++;
Thread.Sleep(100);
}
return string.Empty;
});
return newWindowHandle;
}
So in this solution I opted to pass the expected window title as an argument for the function to loop all windows and compare the new window title, this way, it's guaranteed to return the correct window. Here is an example call to this method:
await WaitUntilNewWindowIsOpen("newWindowTitle", true);
Below function can wait for given max time until your new window is open
public static void waitForWindow(int max_sec_toWait, int noOfExpectedWindow) {
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver);
wait.pollingEvery(Duration.ofMillis(200));
wait.withTimeout(Duration.ofSeconds(max_sec_toWait));
wait.ignoring(NoSuchWindowException.class);
Function<WebDriver, Boolean> function = new Function<WebDriver, Boolean>(){
#Override
public Boolean apply(WebDriver driver) {
Set<String> handel = driver.getWindowHandles();
if(handel.size() == noOfExpectedWindow)
return true;
else
return false;
}
};
wait.until(function);
}
Js code
await firstPage.clickOnLink();
let tabs = await driver.getAllWindowHandles();
await driver.switchTo().window(tabs[1]);
await driver.wait(await until.titleContains('myString'), 2000);