Focus on recent open tab using selenium webdriver - java

I have one website in which When I click on button, it open new tab with link in same browser.
I want to tell selenium to focus on that recently open tab.
I tried many methods but none of them seem helpful in my case.
I have tried :
Method 1 :
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL);
driver.findElement(By.cssSelector("body")).sendKeys(Keys.TAB);
Method 2 :
((JavascriptExecutor) webDriver).executeScript("window.focus();");
Method 3:
driver.switchTo().window(driver.getWindowHandles().last());

Try this code, use Java Robot. that worked for me.
ArrayList<String> tabs2 = new ArrayList<String>(driver.getWindowHandles());
System.out.println(tabs2.size());
for (int i = tabs2.size()-1; i>=0; i--) {
Thread.sleep(2000);
driver.switchTo().window(tabs2.get(i));
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_CONTROL);
System.out.println(driver.getTitle() + "i: " + i);
// do what you needed
}

Related

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

Download a file in IE using Selenium

OK, so I am trying to export a file using Selenium. My browser is IE. When I click on the export button a native windows dialogue box comes up.
Image of the pop up
I have to click on the Save button. For this I tried using AutoIT but its not working.
exportbutton.click();
Thread.sleep(2000);
driver.switchTo().activeElement();
AutoItX x = new AutoItX();
x.winActivate("window name");
x.winWaitActive("window name");
x.controlClick("window name", "", "[CLASS:Button; INSTANCE:2]");
This did not work. So I decided to use Robot class and perform the keyboard clicks Atl + S, as this will also enable the browser to Save the file. That did not work either.
try
{
Robot robot = new Robot();
robot.setAutoDelay(250);
robot.keyPress(KeyEvent.VK_ALT);
Thread.sleep(1000);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_S);
}
catch (AWTException e)
{
e.printStackTrace();
}
There is some problem with the web driver I suppose because I tried printing a line after exportbutton.click() and it did not get printed either.
I am new so I can't understand the problem. Please help me out.
So, the problem was that the cursor gets stuck sometimes when you call the click() function. So as a solution I used the Robot class to move my cursor and click on the export button and then I used Robot class to press Alt+S, which is a keyboard shortcut to save a file in IE.
To click on the button I used
try
{
Robot robot = new Robot();
Thread.sleep(2000);
robot.mouseMove(coordinates.getX()+100,coordinates.getY()-400);
Thread.sleep(2000);
robot.mousePress( InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}
catch (AWTException e)
{
e.printStackTrace();
}
To get the coordinates in the above snippet I used the following line
Point coordinates = driver.findElement(By.id("id")).getLocation();
System.out.println("Co-ordinates"+coordinates);
And to press Alt+S I used the following code
try
{
Robot robot = new Robot();
robot.setAutoDelay(250);
robot.keyPress(KeyEvent.VK_ALT);
Thread.sleep(1000);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_S);
}
catch (AWTException e)
{
e.printStackTrace();
}
I had the same problem. I came to realization that
button.click()
does not work very well in this case (with IE driver). So instead of clicking the button I tried this:
robot = new Robot();
button.sendKeys("""");
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
This just gives focus on button and 'presses' it by hitting enter.
Sorry, I wrote approach how to upload the file. If you want to download - use the same approach, but use another buttons: Instead buttons Cntrl + V you can use button Tab to find control of Save/Save as and then Press Enter. Before it, you can paste String with file path ( directory where you want to upload your file).
Auto IT is not required to handle this. just use the below code and it works fine.
If we give element.click on the element, control stops there and hence we use element.sendkeys("") and robot.keyPress(KeyEvent.VK_ENTER);
Below is the complete code:
Robot robot = new Robot();
//get the focus on the element..don't use click since it stalls the driver
element.sendKeys("");
//simulate pressing enter
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
//wait for the modal dialog to open
Thread.sleep(2000);
//press s key to save
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_N);
robot.keyRelease(KeyEvent.VK_N);
robot.keyRelease(KeyEvent.VK_ALT);
Thread.sleep(2000);
//press enter to save the file with default name and in default location
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
I used AutoIt and it works in windows 10. Refer to the below AutoIt script :
Sleep(9000);
Local $hIE = WinGetHandle("[Class:IEFrame]");
Local $hCtrl = ControlGetHandle($hIE, "", "[ClassNN:DirectUIHWND1]");
If WinExists($hIE,"") Then
WinActivate($hIE,"");
ControlSend($hIE ,"",$hCtrl,"{F6}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{TAB}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{ENTER}");
EndIf
Sleep(5000);
If WinExists($hIE,"") Then
WinActivate($hIE,"");
ControlSend($hIE ,"",$hCtrl,"{F6}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{TAB}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{TAB}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{TAB}");
Sleep(1500);
ControlSend($hIE ,"",$hCtrl,"{ENTER}");
EndIf
Sleep(5000);
It clicks the save button and also closes the next alert.
Please adjust Sleep() accordingly.
This is a hack by Dave Haefner. If you don't care if a file was downloaded or not and you want to confirm only that a file can be downloaded, you can use an HTTP request. Instead of downloading the file you'll receive the header information for the file which contains things like the content type and length. With this information, you can confirm the file is you expect.
String link = driver.findElement(By.cssSelector("download-link-element")).getAttribute("href");
HttpClient httpClient = HttpClientBuilder.create().build();
HttpHead request = new HttpHead(link);
HttpResponse response = httpClient.execute(request);
String contentType = response.getFirstHeader("Content-Type").getValue();
int contentLength = Integer.parseInt(response.getFirstHeader("Content-Length").getValue());
assertThat(contentType, is("application/octet-stream"));
assertThat(contentLength, is(not(0)));

Selenium sendkeys not inputting the text

I have the below code which will click on a button in window. On clicking the button,the current window is closed and new window will be opened. Some text will be inputted in a textbox in new window.
WebElement element=null;
try {
driver.getWindowHandles();
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
try {
element = driver.findElement(By.xpath("//*[#id='username']"));
} catch (Exception e) {
continue;
}
if (element.isDisplayed()) {
windowFound = 1;
break;
}
}
}
element.sendKeys("Testingusername");
Last line to input send keys is not failing. But the actual text is not entered into the textbox.
This works well in chrome. Issue is with Internet explorer only.
Selenium : 2.53.1
IE 11
Try to focus on the element let say
element.Clear();
element.sendKeys("testingUserName");
and put this code to try catch to see if you get any exceptions
Few things :
verify if you've located the correct element in IE as it sometimes XPath behavior is different in IE.
try to confirm the attributes of the element under question with the attributes observed in other browsers.
try using IE Driver 32 bit version for IE11 browser.
if nothing works then there is no harm in using javascript sendKeys. it's not a bad practise
Actions a = new Actions(driver);
a.SendKeys(element, "Your text to input").Build().Perform();
Note: Works in IE11
try this one This works for me
WebElement element=null;
try {
driver.getWindowHandles();
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
try {
element = driver.findElement(By.xpath("//*[#id='username']"));
} catch (Exception e) {
continue;
}
if (element.isDisplayed()) {
windowFound = 1;
break;
}
}
}
element.click();
String text = "your text that you want to enter";
StringSelection stringSelection = new StringSelection(text);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, stringSelection);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
I think it's all about timing.
You should consider adding Thread.Sleep(3000); to your code:
Thread.Sleep(3000);
element.sendKeys("Testingusername");

Selenium Internet Explorer click button

I have a problem. I want to click for button and open link in new tab. This my code:
Actions actions = new Actions(this.driver);
actions.keyDown(Keys.CONTROL).click(myButton).keyUp(Keys.CONTROL).perform();
But link is opened on current tab, not new tab.
This is bug of that?
P.S. on chrome and firefox this code work very well
One solution would be to open a new window before clicking the link :
WebDriver driver = new FirefoxDriver();
driver.get("http://stackoverflow.com");
// open a new window
((JavascriptExecutor)driver).executeScript("window.open(window.location.href, '_blank');");
// set the context to the new window
driver.switchTo().window(driver.getWindowHandles().toArray()[1]);
// click the link
driver.findElement(By.linkText("Stack Overflow")).click();
Another solution would be to set the target attribute on the targeted element:
WebDriver driver = new FirefoxDriver();
driver.get("http://stackoverflow.com");
WebElement element = driver.findElement(By.linkText("Stack Overflow"));
// set the target _blank on the link
((JavascriptExecutor)driver).executeScript("arguments[0].target='_blank';", element);
// click the link
element.click();
// set the context to the new window
driver.switchTo().window(driver.getWindowHandles().toArray()[1]);
Your code is fine but the IEDriver is not quite as good as the ones for FireFox and Chrome. I had similar issues, as you can read here. I ended up solving my issues with the java.awt.Robot. In your case that would mean you'd need an IE-specific method for opening in new tab.
Robot r = null;
try {
r = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
...
r.setAutoDelay(30);
r.keyPress(KeyEvent.VK_CONTROL);
//then click the button
r.keyRelease(KeyEvent.VK_CONTROL);
It's not elegant but it works.

WebDriver.getWindowHandle() method

I'm new to Selenium learning. WebDriver.getWindowHandle() documentation is not very clear to me and the example is not working as given in the book, so I thought of confirming the value returned by this method.
1) Let's say I am on page PAGE1. So getWindowHandle() should return handle to PAGE1. (Correct)
2) Now from this page, I go to PAGE2 (by hyperlink and opening a new window). My book says now getWindowHandle() should return handle to PAGE2. However my program still returns handle to PAGE1.
Selenium v2.43
Reproducible on Firefox and Chrome both.
Question: What is the exact value that getWindowHandle() should return?
WebDriver wd = new ChromeDriver();
wd.get("file://D:/Projects/Selenium/Startup/web/ch3/switch_main.html");
String h1 = wd.getWindowHandle();// original handle
System.out.println("First handle = " + h1);
WebElement clickhere = wd.findElement(By.id("clickhere"));
clickhere.click();//moved to a new child page<
String h2 = wd.getWindowHandle();
System.out.println("Second handle = " + h2);// this handle is not different than h1
getWindowHandle() will get the handle of the page the webDriver is currently controlling. This handle is a unique identifier for the web page. This is different every time you open a page even if it is the same URL.
getWindowHandles() (don't forget the 's') will give you all the handles for all the pages that the web driver understands are open. Note that when you put these in a list they are listed in the order that they have been opened.
You can use SwitchTo().Window("handle") to switch to the window you desire.
You can use SwitchTo().Window("mywindowID"), if you know the window ID.
SwitchTo().Window("") will always go back to the base/main window.
SwitchTo().Frame("popupFrame") will get to the Popup that came from the window the webdriver is currently controlling.
If the link opens a new window you should have a new window handle in the WebDriver. You can loop current window handles with getWindowHandles.
See this example from http://www.thoughtworks.com/products/docs/twist/13.3/help/how_do_i_handle_popup_in_selenium2.html
String parentWindowHandle = browser.getWindowHandle(); // save the current window handle.
WebDriver popup = null;
Iterator<String> windowIterator = browser.getWindowHandles();
while(windowIterator.hasNext()) {
String windowHandle = windowIterator.next();
popup = browser.switchTo().window(windowHandle);
if (popup.getTitle().equals("Google") {
break;
}
}
When you open the new window, the WebDriver doesn't automatically switch to it. You need to use the switchTo() method to switch to the new window, either using the name of the new window, or its handle (which you can get with getWindowHandles() and searching for the one that's not the current window).
I have used this code for my project
String oldTab = driver.getWindowHandle();
public static void switchingToNewTabUsingid(WebDriver driver,WebDriverWait wait,String id,String oldTab)
{
wait.until(ExpectedConditions.elementToBeClickable(By.id(id)));
driver.findElement(By.id(id)).click();
ArrayList<String> newTab = new ArrayList<String>(driver.getWindowHandles());
newTab.remove(oldTab);
driver.switchTo().window(newTab.get(0));
}
//Perfrom Opeartion here on switched tab
public static void comingBackToOldTab(WebDriver driver,String oldTab)
{
driver.close();
driver.switchTo().window(oldTab);
}
With Selenium 2.53.1 using firefox 47.0.1 as the WebDriver in Java: You need to open the separate windows/browsers in it's own driver. I have having the same problem. No matter how many windows or tabs I opened, "driver.getWindowHandles()" would only return one handle so it was impossible to switch between tabs. I found Chrome worked way better for me.
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/BROWSERS)
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> (driver2.getWindowHandles());
// NOW PERFORM DESIRED TASKS WITH FIRST BROWSER IN ANY TAB
for(int ii = 0; ii <= TAB_NUMBER; ii++) {
driver2.switchTo().window(tabs2.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.

Categories

Resources