Selenium check if a window is currently open - java

So I have a selenium webdriver logging me into a website and from there I click a button which opens a second window. I use this code below to switch to the new window
String winParent = driver.getWindowHandle();
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
}
Now on that second window I run some automation . Once complete I would press the save button and this would close the current window. If the window doesn't close it means I have some errors on the page and I need to loop back and fix it.
driver.findElement(By.id("btnSave")).click();
if (isAlive(driver) == false) {
//break and exit
System.out.println("cic" + name);
finalString = finalString + "cic: " + name;
break;
}
public Boolean isAlive(WebDriver driver) {
try {
driver.getCurrentUrl();//or driver.getTitle();
return true;
} catch (Exception ex) {
return false;
}
}
The The program works as expected when it catches the errors and the window doesn't close. But as soon as everything is clear and the window closes it enters the if statement above and displays this error.
Unable to receive message from renderer.
I believe that I'm not checking if the window has been closed correctly.
edit: after some debugging it seems like once the window closes the program can't really tell what to do next. http://i.imgur.com/l8nsPPr.png

I suggest using windowHandle for this.
You are saving initial window in String winParent = driver.getWindowHandle();
Then you switch to the second window, which will have different handle.
When you need to check if the second window is still open, just use:
private boolean isNewWindowOpened(WebDriver driver, String parentWindowHandle) {
try {
return !driver.getWindowHandle().equals(parentWindowHandle);
} catch (Exception ex) {
driver.switchTo(parentWindowHandle);
return false;
}

I came across the same situation, I've got a solution for you, check window count after clicking on "Save" button. Ideally, there will be one window if you have provided all the correct data and if not then there are two windows.
driver.findElement(By.id("btnSave")).click();
if (driver.getWindowHandled().size() >= 2) {
// make required changes
// again click on save button
} else {
//break and exit
System.out.println("cic" + name);
finalString = finalString + "cic: " + name;
break;
}
}

Related

Error trying to close a tab and switching to the other tab using selenium / java

I have a window with two tabs. I am trying to close the tab with a specific title and switch the control to the other tab.
Here is my code:
public static void closeTheWindowWithTitle(String title) {
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
String mainWindow = driver.getWindowHandle();
for(int i = 0; i < tabs.size(); i++) {
log.debug("switched to " + driver.getTitle() + " Window");
if(driver.getTitle().contains(title))
{
driver.switchTo().window(tabs.get(i));
driver.close();
log.debug("Closed the " + driver.getTitle() + " Window");
}
}
driver.switchTo().window(mainWindow);
}
When I run my code, I am getting the following exception:
org.openqa.selenium.NoSuchWindowException: no such window: target window already closed
from unknown error: web view not found
I am unable to figure out what is the problem. Please help.
I'm guessing, that the WindowHandle of your Main-Window got changed, somewhere along the way. You should be able to get your problem solved by doing something similar to the suggested solution here, i.e. getting all WindowHandles, and iterating over them and in the end switching to [0], which should be the only one left, after closing the second one.
I hope this will help you to fix your issue, i dont want to provide code fix and i want to explain you the details process step by step.
Open firefox/IE/Chrome browser and Navigate to https://www.bbc.co.uk
WebDriver driver = new AnyDriveryourusing();
// set implicit time to 30 seconds
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
// navigate to the url
driver.get("https://www.bbc.co.uk");
Get the GU ID of the current (parent) window using getWindowHandle() method present in the webdriver and store the value in a String
// get the Session id of the Parent
String parentGUID = driver.getWindowHandle();
Click on the Open New Window button, application open new window with google page.
// click the button to open new window
driver.findElement(By.id("two-window")).click();
Thread.sleep(5000);
Get the GU IDs of the two windows (parent + google), using getWindowHandles() method present in the webdriver. Store the GU IDs in a Set Collection, this Set will have GU IDs of both parent and Child Browsers
// get the All the session id of the browsers
Set allGUID = driver.getWindowHandles();
iterate the Set of GUID values, and if the value is parent value skip it if not switch to the new window
// iterate the values in the set
for(String guid : allGUID){
// one enter into if block if the GUID is not equal to parent window's GUID
if(! guid.equals(parentGUID)){
//todo
}
}
Switch to window using switchTo().window() method, pass the GU ID of the child browser to this method.
// switch to the guid
driver.switchTo().window(guid);
Find the search bar in Google.com and search for "success"
driver.findElement(By.name("q")).sendKeys("success");
Close the Google tab/Window and return to parent tab/browser window
// close the browser
driver.close();
// switch back to the parent window
driver.switchTo().window(parentGUID);
You were close but you weren't switching windows before checking the title. I've updated the code to something that should work.
public static void closeTheWindowWithTitle(String title)
{
Set<String> tabs = driver.getWindowHandles();
String mainWindow = driver.getWindowHandle();
for(int i = 0; i < tabs.size(); i++)
{
// you need to switch to the window before checking title
driver.switchTo().window(tabs.get(i));
log.debug("switched to " + driver.getTitle() + " Window");
if(driver.getTitle().contains(title))
{
driver.close();
log.debug("Closed the " + driver.getTitle() + " Window");
break; // this breaks out of the loop, which I'm assuming is what you want when a match is found
}
}
driver.switchTo().window(mainWindow);
}

Visible but overlaid

I am making a script using selenium and at one step it shows loading icon in center of webpage.The loading icon appears after 1st line is executed
test.driver.findElement(By.id("oaapprove")).click();
test.driver.findElement(By.xpath("//*[text()='DATA EXPLORER']")).click();
The 2nd element is still there in DOM but its not clickable so i get error as not clickable
i tried this:
Boolean isPresent=test.driver.findElements(By.xpath("//div[#class='spinner-container']")).size() > 0;
if(isPresent)
{
System.out.println("Target element found");
}
while(test.driver.findElements(By.xpath("//div[#class='spinner-container']")).size() > 0)
{
try {
System.out.println("inside");
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(!(test.driver.findElements(By.xpath("//div[#class='spinner-container']")).size() > 0))
{
System.out.println("Target element not found");
}
It is printing "inside" till the loading icon is visible but but after icon disappears it does not print "inside" but it waits for 7-8 secs and then executes next statements.
What is the cause of waiting?
Can u please tell how to i solve this.
try actions class if it's showing using fluentwait that element is clickable:
WebElement yourElement = test.driver.findElement(By.xpath("//*[text()='DATA EXPLORER']"));
Actions act = new Actions(test.driver);
act.moveToElement(yourElement).click().build().perform();
I got the solution and i used stalenessOf
new WebDriverWait(driver, 10).until(ExpectedConditions.stalenessOf(findElement(By.xpath("element_path"))));

Wait until text is not present in textbox selenium

Below is the scenario I am trying to automate:
1) Some text is already present in Textbox.
2) Click on Radio button.
3) Processing popup is displayed for few seconds. After popup disappears the textbox
becomes blank
4) After textbox is blank then I have to enter different value in text box.
Please help me, how to wait till textbox value is blank.
I am automating with IE driver.
Thanks In advance
I would try:
int timeout = 10; // depends on your needs
WebDriverWait myWait= new WebDriverWait(driver,timeout);
myWait.until(ExpectedCondition.textToBePresentInElementValue(By locator, String text))
-- with empty string passed as text argument
You can try something like this :-
public void waitUntilTextNotToBeInWebElement(WebElement element, String textValue) {
int timer = 0;
final int pollInterval = 500;
while (timer < MAX_TIME*1000) {
if (element.getText().equalsIgnoreCase(textValue)) {
sleep(500);
timer += pollInterval;
} else {
return;
}
}
throw new TimeoutException("Maximum time exceeded.");
}
Hi there is two possible way through which you can do this
1.Use Expected condition
// after you have clicked on radio button and it does some processing
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.invisibilityOfElementWithText(locator, "your text"));
// now perform your operation
use if else
// get the text of input box like below
String myInitialText = driver.findElement(By.xpath("")).getAttribute("value");
// click on radio button
// now apply the logic
if(myInitialText == null){
System.out.println("Input box is blank");
// perform next operation
}else{
Thread.sleep(5000);
}
// now fill the input box
Below code worked for me.
WebElement element=driver.findElement(By.id("ctl00_cphClaimFlow_tabcontainerClaimFlow_tabFulfillment_Shipping_ctl33_txtStreeAddress1"));
String myInitialText=element.getAttribute("value");
//click on radio btn
driver.findElement(By.id("ctl00_cphClaimFlow_tabcontainerClaimFlow_tabFulfillment_Shipping_ctl33_radNewAddress")).click();
logger.info("New Address radio button clicked");
System.out.println("1 "+myInitialText);
while(!myInitialText.equals("")){
try {
Thread.sleep(5000);
logger.info("Thread is sleeping");
//System.out.println("2 "+myInitialText);
myInitialText=driver.findElement(By.id("ctl00_cphClaimFlow_tabcontainerClaimFlow_tabFulfillment_Shipping_ctl33_txtStreeAddress1")).getAttribute("value");
//System.out.println("3 "+myInitialText);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
driver.findElement(By.id("ctl00_cphClaimFlow_tabcontainerClaimFlow_tabFulfillment_Shipping_ctl33_txtStreeAddress1")).sendKeys(td.getAddressLine1().get(0));
logger.info("Address Line1 entered");

How can I test a dropdown menu in Java from a generated selenium test case?

I am converting one of my Selenium test cases to Java and I am having a problem. The test involves checking links in drop down menus. My code is working sporadically on some of the links. Do I need to add this before each link test? I can make it a method if that is the case.
driver.get(baseUrl + "/");
try {
driver.findElement(By.cssSelector("a.dropdown-toggle")).click();
}
catch (Exception e) {
new SendMail("janet.frank#rodale.com",to_email,"CSS Selector","Error in cssSelector execution");
errorsFound = true;
}
Here is the method for the xpath:
private void executeXpath (String urlName, String value) {
String msg = "";
String xPath = "(//a[contains(text(),'" + urlName + "')])[" + value + "]";
try {
driver.findElement(By.xpath(xPath)).click();
checkUrl(urlName);
} catch (Exception e) {
msg = urlName + " test was not successful";
new SendMail("janet.frank#rodale.com",to_email,urlName,msg);
errorsFound = true;
}
// driver.navigate().back();
wait_fiveSeconds();
}
I have tried doing waits, executing the CSS dropdown method before each link but short of me staying hovered over the main header so that the dropdown stays visible does not work.
So I saw this code example posted, but what do I import so that I can create and Actions chain?
Actions action = new Actions(webdriver);
WebElement we = webdriver.findElement(By.xpath("//html/body/div[13]/ul/li[4]/a"));
action.moveToElement(we).build().perform();
I need to have my code execute the link and go to new pages but it does not seem to be doing that using the Actions API. Any help would be appreciated.

Switch tabs using Selenium WebDriver with Java

Using Selenium WebDriver with Java.
I am trying to automate a functionality where I have to open a new tab do some operations there and come back to previous tab (Parent).
I used switch handle but it's not working.
And one strange thing the two tabs are having same window handle due to which I am not able to switch between tabs.
However when I am trying with different Firefox windows it works, but for tab it's not working.
How can I switch tabs?
Or, how can I switch tabs without using window handle as window handle is same of both tabs in my case?
(I have observed that when you open different tabs in same window, window handle remains same)
psdbComponent.clickDocumentLink();
ArrayList<String> tabs2 = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs2.get(1));
driver.close();
driver.switchTo().window(tabs2.get(0));
This code perfectly worked for me. Try it out. You always need to switch your driver to new tab, before you want to do something on new tab.
This is a simple solution for opening a new tab, changing focus to it, closing the tab and return focus to the old/original tab:
#Test
public void testTabs() {
driver.get("https://business.twitter.com/start-advertising");
assertStartAdvertising();
// considering that there is only one tab opened in that point.
String oldTab = driver.getWindowHandle();
driver.findElement(By.linkText("Twitter Advertising Blog")).click();
ArrayList<String> newTab = new ArrayList<String>(driver.getWindowHandles());
newTab.remove(oldTab);
// change focus to new tab
driver.switchTo().window(newTab.get(0));
assertAdvertisingBlog();
// Do what you want here, you are in the new tab
driver.close();
// change focus back to old tab
driver.switchTo().window(oldTab);
assertStartAdvertising();
// Do what you want here, you are in the old tab
}
private void assertStartAdvertising() {
assertEquals("Start Advertising | Twitter for Business", driver.getTitle());
}
private void assertAdvertisingBlog() {
assertEquals("Twitter Advertising", driver.getTitle());
}
There is a difference how web driver handles different windows and how it handles different tabs.
Case 1:
In case there are multiple windows, then the following code can help:
//Get the current window handle
String windowHandle = driver.getWindowHandle();
//Get the list of window handles
ArrayList tabs = new ArrayList (driver.getWindowHandles());
System.out.println(tabs.size());
//Use the list of window handles to switch between windows
driver.switchTo().window(tabs.get(0));
//Switch back to original window
driver.switchTo().window(mainWindowHandle);
Case 2:
In case there are multiple tabs in the same window, then there is only one window handle. Hence switching between window handles keeps the control in the same tab. In this case using Ctrl + \t (Ctrl + Tab) to switch between tabs is more useful.
//Open a new tab using Ctrl + t
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
//Switch between tabs using Ctrl + \t
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");
Detailed sample code can be found here:
http://design-interviews.blogspot.com/2014/11/switching-between-tabs-in-same-browser-window.html
Work around
Assumption : By Clicking something on your web page leads to open a new tab.
Use below logic to switch to second tab.
new Actions(driver).sendKeys(driver.findElement(By.tagName("html")), Keys.CONTROL).sendKeys(driver.findElement(By.tagName("html")),Keys.NUMPAD2).build().perform();
In the same manner you can switch back to first tab again.
new Actions(driver).sendKeys(driver.findElement(By.tagName("html")), Keys.CONTROL).sendKeys(driver.findElement(By.tagName("html")),Keys.NUMPAD1).build().perform();
Since the driver.window_handles is not in order , a better solution is this.
first switch to the first tab using the shortcut Control + X to switch to the 'x' th tab in the browser window .
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "1");
# goes to 1st tab
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "4");
# goes to 4th tab if its exists or goes to last tab.
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL, Keys.RETURN);
WebElement e = driver.findElement(By
.xpath("html/body/header/div/div[1]/nav/a"));
e.sendKeys(selectLinkOpeninNewTab);//to open the link in a current page in to the browsers new tab
e.sendKeys(Keys.CONTROL + "\t");//to move focus to next tab in same browser
try {
Thread.sleep(8000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//to wait some time in that tab
e.sendKeys(Keys.CONTROL + "\t");//to switch the focus to old tab again
Hope it helps to you..
The first thing you need to do is opening a new tab and save it's handle name. It will be best to do it using javascript and not keys(ctrl+t) since keys aren't always available on automation servers. example:
public static String openNewTab(String url) {
executeJavaScript("window.parent = window.open('parent');");
ArrayList<String> tabs = new ArrayList<String>(bot.driver.getWindowHandles());
String handleName = tabs.get(1);
bot.driver.switchTo().window(handleName);
System.setProperty("current.window.handle", handleName);
bot.driver.get(url);
return handleName;
}
The second thing you need to do is switching between the tabs. Doing it by switch window handles only, will not always work since the tab you'll work on, won't always be in focus and Selenium will fail from time to time.
As I said, it's a bit problematic to use keys, and javascript doesn't really support switching tabs, so I used alerts to switch tabs and it worked like a charm:
public static void switchTab(int tabNumber, String handleName) {
driver.switchTo().window(handleName);
System.setProperty("current.window.handle", handleName);
if (tabNumber==1)
executeJavaScript("alert(\"alert\");");
else
executeJavaScript("parent.alert(\"alert\");");
bot.wait(1000);
driver.switchTo().alert().accept();
}
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL,Keys.SHIFT,Keys.TAB);
This method helps in switching between multiple windows. The restricting problem with this method is that it can only be used so many times until the required window is reached. Hope it helps.
With Selenium 2.53.1 using firefox 47.0.1 as the WebDriver in Java: no matter how many tabs I opened, "driver.getWindowHandles()" would only return one handle so it was impossible to switch between tabs.
Once I started using Chrome 51.0, I could get all handles. The following code show how to access multiple drivers and multiple tabs within each driver.
// INITIALIZE TWO DRIVERS (THESE REPRESENT SEPARATE CHROME WINDOWS)
driver1 = new ChromeDriver();
driver2 = new ChromeDriver();
// LOOP TO OPEN AS MANY TABS AS YOU WISH
for(int i = 0; i < TAB_NUMBER; i++) {
driver1.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
// SLEEP FOR SPLIT SECOND TO ALLOW DRIVER TIME TO OPEN TAB
Thread.sleep(100);
// STORE TAB HANDLES IN ARRAY LIST FOR EASY ACCESS
ArrayList tabs1 = new ArrayList<String> (driver1.getWindowHandles());
// REPEAT FOR THE SECOND DRIVER (SECOND CHROME BROWSER WINDOW)
// LOOP TO OPEN AS MANY TABS AS YOU WISH
for(int i = 0; i < TAB_NUMBER; i++) {
driver2.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
// SLEEP FOR SPLIT SECOND TO ALLOW DRIVER TIME TO OPEN TAB
Thread.sleep(100);
// STORE TAB HANDLES IN ARRAY LIST FOR EASY ACCESS
ArrayList tabs2 = new ArrayList<String> (driver1.getWindowHandles());
// NOW PERFORM DESIRED TASKS WITH FIRST BROWSER IN ANY TAB
for(int ii = 0; ii <= TAB_NUMBER; ii++) {
driver1.switchTo().window(tabs1.get(ii));
// LOGIC FOR THAT DRIVER'S CURRENT TAB
}
// PERFORM DESIRED TASKS WITH SECOND BROWSER IN ANY TAB
for(int ii = 0; ii <= TAB_NUMBER; ii++) {
drvier2.switchTo().window(tabs2.get(ii));
// LOGIC FOR THAT DRIVER'S CURRENT TAB
}
Hopefully that gives you a good idea of how to manipulate multiple tabs in multiple browser windows.
Simple Answer which worked for me:
for (String handle1 : driver1.getWindowHandles()) {
System.out.println(handle1);
driver1.switchTo().window(handle1);
}
Set<String> tabs = driver.getWindowHandles();
Iterator<String> it = tabs.iterator();
tab1 = it.next();
tab2 = it.next();
driver.switchTo().window(tab1);
driver.close();
driver.switchTo().window(tab2);
Try this. It should work
public void switchToNextTab() {
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(1));
}
public void closeAndSwitchToNextTab() {
driver.close();
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(1));
}
public void switchToPreviousTab() {
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(0));
}
public void closeTabAndReturn() {
driver.close();
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(0));
}
public void switchToPreviousTabAndClose() {
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(1));
driver.close();
}
I had a problem recently, the link was opened in a new tab, but selenium focused still on the initial tab.
I'm using Chromedriver and the only way to focus on a tab was for me to use switch_to_window().
Here's the Python code:
driver.switch_to_window(driver.window_handles[-1])
So the tip is to find out the name of the window handle you need, they are stored as list in
driver.window_handles
Please see below:
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.irctc.co.in/");
String oldTab = driver.getWindowHandle();
//For opening window in New Tab
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN);
driver.findElement(By.linkText("Hotels & Lounge")).sendKeys(selectLinkOpeninNewTab);
// Perform Ctrl + Tab to focus on new Tab window
new Actions(driver).sendKeys(Keys.chord(Keys.CONTROL, Keys.TAB)).perform();
// Switch driver control to focused tab window
driver.switchTo().window(oldTab);
driver.findElement(By.id("textfield")).sendKeys("bangalore");
Hope this is helpful!
It is A very simple process: assume you have two tabs so you need to first close the current tab by using client.window(callback) because the switch command "switches to the first available one". Then you can easily switch tab using client.switchTab.
A brief example of how to switch between tabs in a browser (in case with one window):
// open the first tab
driver.get("https://www.google.com");
Thread.sleep(2000);
// open the second tab
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
driver.get("https://www.google.com");
Thread.sleep(2000);
// switch to the previous tab
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "" + Keys.SHIFT + "" + Keys.TAB);
Thread.sleep(2000);
I write Thread.sleep(2000) just to have a timeout to see switching between the tabs.
You can use CTRL+TAB for switching to the next tab and CTRL+SHIFT+TAB for switching to the previous tab.
This will work for the MacOS for Firefox and Chrome:
// opens the default browser tab with the first webpage
driver.get("the url 1");
thread.sleep(2000);
// opens the second tab
driver.findElement(By.cssSelector("Body")).sendKeys(Keys.COMMAND + "t");
driver.get("the url 2");
Thread.sleep(2000);
// comes back to the first tab
driver.findElement(By.cssSelector("Body")).sendKeys(Keys.COMMAND, Keys.SHIFT, "{");
To get parent window handles.
String parentHandle = driverObj.getWindowHandle();
public String switchTab(String parentHandle){
String currentHandle ="";
Set<String> win = ts.getDriver().getWindowHandles();
Iterator<String> it = win.iterator();
if(win.size() > 1){
while(it.hasNext()){
String handle = it.next();
if (!handle.equalsIgnoreCase(parentHandle)){
ts.getDriver().switchTo().window(handle);
currentHandle = handle;
}
}
}
else{
System.out.println("Unable to switch");
}
return currentHandle;
}
The flaw with the selected answer is that it unnecessarily assumes order in webDriver.getWindowHandles(). The getWindowHandles() method returns a Set, which does not guarantee order.
I used the following code to change tabs, which does not assume any ordering.
String currentTabHandle = driver.getWindowHandle();
String newTabHandle = driver.getWindowHandles()
.stream()
.filter(handle -> !handle.equals(currentTabHandle ))
.findFirst()
.get();
driver.switchTo().window(newTabHandle);
protected void switchTabsUsingPartOfUrl(String platform) {
String currentHandle = null;
try {
final Set<String> handles = driver.getWindowHandles();
if (handles.size() > 1) {
currentHandle = driver.getWindowHandle();
}
if (currentHandle != null) {
for (final String handle : handles) {
driver.switchTo().window(handle);
if (currentUrl().contains(platform) && !currentHandle.equals(handle)) {
break;
}
}
} else {
for (final String handle : handles) {
driver.switchTo().window(handle);
if (currentUrl().contains(platform)) {
break;
}
}
}
} catch (Exception e) {
System.out.println("Switching tabs failed");
}
}
Call this method and pass parameter a substring of url of the tab you want to switch to
public class TabBrowserDemo {
public static void main(String[] args) throws InterruptedException {
System.out.println("Main Started");
System.setProperty("webdriver.gecko.driver", "driver//geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.irctc.co.in/eticketing/userSignUp.jsf");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.xpath("//a[text()='Flights']")).click();
waitForLoad(driver);
Set<String> ids = driver.getWindowHandles();
Iterator<String> iterator = ids.iterator();
String parentID = iterator.next();
System.out.println("Parent WIn id " + parentID);
String childID = iterator.next();
System.out.println("child win id " + childID);
driver.switchTo().window(childID);
List<WebElement> hyperlinks = driver.findElements(By.xpath("//a"));
System.out.println("Total links in tabbed browser " + hyperlinks.size());
Thread.sleep(3000);
// driver.close();
driver.switchTo().window(parentID);
List<WebElement> hyperlinksOfParent = driver.findElements(By.xpath("//a"));
System.out.println("Total links " + hyperlinksOfParent.size());
}
public static void waitForLoad(WebDriver driver) {
ExpectedCondition<Boolean> pageLoadCondition = new
ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
}
};
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(pageLoadCondition);
}
WebDriver driver = new FirefoxDriver();
driver.switchTo().window(driver.getWindowHandles().toArray()[numPage].toString());
numPage - int (0,1..)
String mainWindow = driver.getWindowHandle();
seleniumHelper.switchToChildWindow();
..
..//your assertion steps
seleniumHelper.switchToWindow(mainWindow);
with Java I used this for switching the selenium focus to the new tab.
//Before the action that redirect to the new tab:
String windHandleCurrent = driver.getWindowHandle();
// code that click in a btn/link in order to open a new tab goes here
// now to make selenium move to the new tab
ArrayList<String> windows = new ArrayList<String>(driver.getWindowHandles());
for(int i =0;i<windows.size();i++ ) {
String aWindow = windows.get(i);
if(aWindow != windHandleCurrent) {
driver.switchTo().window(aWindow);
}
}
// now you can code your AssertJUnit for the new tab.
Selenium 4 has new features:
// 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);
driver.getWindowHandles() is a Set.I converted it to array of objects by
Object[] a=driver.getWindowHandles().toArray;
Say you want to switch to 2nd tab then (after conversion) use
driver.switchTo().windows(a[1].toString());

Categories