Hello I want to learn how to switch in in to a new windows without using thread sleep. I was trying to use awaitility artifact but I was not able to done it correctly. I was trying to automate print window. When I click on print icons on my web page I navigate to print window I want to wait while navigating to print window and once print window displayed I want to click on cancel button. Can someone help me for that
Print_icon.click();
await().atMost(10,TimeUnit.SECOND).pollInterval(1,TimeUnit.SECONDS);
Cancel_button.click();
You can try this :
Print_icon.click();
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
}
boolean elmnt = false;
boolean timeOut = false;
int second = 1;
do {
try {
if(second>30) {
timeOut = true;
}
Cancel_button.click();
elmnt=true;
} catch (Exception e) {
TimeUnit.SECONDS.sleep(1);
second++;
}
}while(elmnt==false && timeOut==false);
You can't handle windows dialogs so I suggest you review your page code and find the name of the method that opens the print window and override it. In your test case for example you can override print method to do nothing, like this:
((JavascriptExecutor)driver).executeScript("window.print=function(){};");
Related
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));
There is a focus on the field , in the browser , or notepad . When I plan to offer NFC, I want to force to insert text into the focused field . I know how to read NFC tag and add it to the clipboard . But how to make paste this text into an external application for the selected field ? Unfortunately I have not found how to do it using the clipboard manager. Tell me in what direction I move? Maybe using the keyboard ?
I'd suggest emulating keypresses.
new Thread(new Runnable() {
#Override
public void run() {
try {
Instrumentation inst = new Instrumentation();
for ( int i = 0; i < 10; ++i ) {
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
Thread.sleep(2000);
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
Thread.sleep(2000);
}
}
catch(InterruptedException e){
}
}
}).start();
Android simulate key press
There's probably a way for you to emulate ctrl+v, which, despite not being on the default keyboards, does work on most devices.
I am evaluating tools for testing a WPF based app. I am currently trying Sikuli with the Java API. When I try to click on an object from Java code, the mouse cursor goes to the object and the object is highlighted, however the click action does not work, because the expected menu does not open. The click() method returns status 1 though.
If I am doing a click from Sikuli IDE, it works fine.
I tried 1.0.1 version and also the nightly build. Here's my code:
#Test
public void testLogin() {
Screen s = new Screen();
try {
s.wait(Constants.overflowMenu);
System.out.println(s.click(Constants.overflowMenu));
s.wait(Constants.signInMenuOption, 5);
} catch (FindFailed e) {
Assert.fail(e.getMessage());
}
}
What am I doing wrong?
try this code, it worked for me. what it does, it checks the image, click on it and then check this image again on the screen, if it still exists, click again.
Screen screen = new Screen();
Pattern pattern = null;
try
{
pattern = new Pattern(imageLocation);
screen.wait(pattern,30);
screen.click(pattern);
System.out.println("First Attempt To Find Image.");
}
catch(FindFailed f)
{
System.out.println("Exception In First Attempt: " +f.getMessage());
System.out.println("FindFailed Exception Handled By Method: ClickObjectUsingSikuli. Please check image being used to identify the webelement. supplied image: " +imageLocation);
Assert.fail("Image wasn't found. Please use correct image.");
}
Thread.sleep(1000);
//In case image/object wasn't clicked in first attempt and cursor stays in the same screen, then do second atempt.
if(screen.exists(pattern) != null)
{
try
{
screen.getLastMatch().click(pattern);
System.out.println("Second Attempt To Find Image.");
System.out.println("Object: " +imageLocation + " is clicked successfully.");
}
catch(FindFailed f)
{
System.out.println("Exception In Second Attempt: " +f.getMessage());
System.out.println("FindFailed Exception Handled By Method: ClickObjectUsingSikuli. Please check image being used to identify the webelement. supplied image: " +imageLocation);
}
}
In my case it seems it was a problem with the fact that I have two monitors..
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.
I have situation, when click on button opens the new browser window with search results.
Is there any way to connect and focus to new opened browser window?
And work with it, then return back to original(first) window.
You can switch between windows as below:
// Store the current window handle
String winHandleBefore = driver.getWindowHandle();
// Perform the click operation that opens new window
// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
}
// Perform the actions on new window
// 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)
Just to add to the content ...
To go back to the main window(default window) .
use driver.switchTo().defaultContent();
This script helps you to switch over from a Parent window to a Child window and back cntrl to Parent window
String parentWindow = driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles();
for(String windowHandle : handles)
{
if(!windowHandle.equals(parentWindow))
{
driver.switchTo().window(windowHandle);
<!--Perform your operation here for new window-->
driver.close(); //closing child window
driver.switchTo().window(parentWindow); //cntrl to parent window
}
}
I 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);
}
Surya, your way won't work, because of two reasons:
you can't close driver during evaluation of test as it will loose focus, before switching to active element, and you'll get NoSuchWindowException.
if test are run on ChromeDriver you`ll get not a window, but tab on click in your application. As SeleniumDriver can't act with tabs, only switchs between windows, it hangs on click where new tab is being opening, and crashes on timeout.
Modify registry for IE:
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main
Right-click → New → String Value → Value name: TabProcGrowth (create if not exist)
TabProcGrowth (right-click) → Modify... → Value data: 0
Source: Selenium WebDriver windows switching issue in Internet Explorer 8-10
For my case, IE began detecting new window handles after the registry edit.
Taken from the MSDN Blog:
Tab Process Growth : Sets the rate at which IE creates New Tab processes.
The "Max-Number" algorithm: This specifies the maximum number of tab processes that may be executed for a single isolation session for a single frame process at a specific mandatory integrity level (MIC). Relative values are:
TabProcGrowth=0 : tabs and frames run within the same process; frames are not unified across MIC levels.
TabProcGrowth =1: all tabs for a given frame process run in a single tab process for a given MIC level.
Source: Opening a New Tab may launch a New Process with Internet Explorer 8.0
Internet Options:
Security → Untick Enable Protected Mode for all zones (Internet,
Local intranet, Trusted sites, Restricted sites)
Advanced → Security → Untick Enable Enhanced Protected Mode
Code:
Browser: IE11 x64 (Zoom: 100%)
OS: Windows 7 x64
Selenium: 3.5.1
WebDriver: IEDriverServer x64 3.5.1
public static String openWindow(WebDriver driver, By by) throws IOException {
String parentHandle = driver.getWindowHandle(); // Save parent window
WebElement clickableElement = driver.findElement(by);
clickableElement.click(); // Open child window
WebDriverWait wait = new WebDriverWait(driver, 10); // Timeout in 10s
boolean isChildWindowOpen = wait.until(ExpectedConditions.numberOfWindowsToBe(2));
if (isChildWindowOpen) {
Set<String> handles = driver.getWindowHandles();
// Switch to child window
for (String handle : handles) {
driver.switchTo().window(handle);
if (!parentHandle.equals(handle)) {
break;
}
}
driver.manage().window().maximize();
}
return parentHandle; // Returns parent window if need to switch back
}
/* How to use method */
String parentHandle = Selenium.openWindow(driver, by);
// Do things in child window
driver.close();
// Return to parent window
driver.switchTo().window(parentHandle);
The above code includes an if-check to make sure you are not switching to the parent window as Set<T> has no guaranteed ordering in Java. WebDriverWait appears to increase the chance of success as supported by below statement.
Quoted from Luke Inman-Semerau: (Developer for Selenium)
The browser may take time to acknowledge the new window, and you may
be falling into your switchTo() loop before the popup window appears.
You automatically assume that the last window returned by
getWindowHandles() will be the last one opened. That's not necessarily
true, as they are not guaranteed to be returned in any order.
Source: Unable to handle a popup in IE,control is not transferring to popup window
Related Posts:
Selenium switching to new Tab in
IE
How to open new tab in IE using selenium (java) and open a url in
that tab (not
window)
You could use:
driver.SwitchTo().Window(WindowName);
Where WindowName is a string representing the name of the window you want to switch focus to. Call this function again with the name of the original window to get back to it when you are done.
main you can do :
String mainTab = page.goToNewTab ();
//do what you want
page.backToMainPage(mainTab);
What you need to have in order to use the main
private static Set<String> windows;
//get all open windows
//return current window
public String initWindows() {
windows = new HashSet<String>();
driver.getWindowHandles().stream().forEach(n -> windows.add(n));
return driver.getWindowHandle();
}
public String getNewWindow() {
List<String> newWindow = driver.getWindowHandles().stream().filter(n -> windows.contains(n) == false)
.collect(Collectors.toList());
logger.info(newWindow.get(0));
return newWindow.get(0);
}
public String goToNewTab() {
String startWindow = driver.initWindows();
driver.findElement(By.cssSelector("XX")).click();
String newWindow = driver.getNewWindow();
driver.switchTo().window(newWindow);
return startWindow;
}
public void backToMainPage(String startWindow) {
driver.close();
driver.switchTo().window(startWindow);
}
So the problem with a lot of these solutions is you're assuming the window appears instantly (nothing happens instantly, and things happen significantly less instantly in IE). Also you're assuming that there will only be one window prior to clicking the element, which is not always the case. Also IE will not return the window handles in a predictable order. So I would do the following.
public String clickAndSwitchWindow(WebElement elementToClick, Duration
timeToWaitForWindowToAppear) {
Set<String> priorHandles = _driver.getWindowHandles();
elementToClick.click();
try {
new WebDriverWait(_driver,
timeToWaitForWindowToAppear.getSeconds()).until(
d -> {
Set<String> newHandles = d.getWindowHandles();
if (newHandles.size() > priorHandles.size()) {
for (String newHandle : newHandles) {
if (!priorHandles.contains(newHandle)) {
d.switchTo().window(newHandle);
return true;
}
}
return false;
} else {
return false;
}
});
} catch (Exception e) {
Logging.log_AndFail("Encountered error while switching to new window after clicking element " + elementToClick.toString()
+ " seeing error: \n" + e.getMessage());
}
return _driver.getWindowHandle();
}
This feature works with Selenium 4 and later versions.
// 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);
If you have more then one browser (using java 8)
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TestLink {
private static Set<String> windows;
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("file:///C:/Users/radler/Desktop/myLink.html");
setWindows(driver);
driver.findElement(By.xpath("//body/a")).click();
// get new window
String newWindow = getWindow(driver);
driver.switchTo().window(newWindow);
// Perform the actions on new window
String text = driver.findElement(By.cssSelector(".active")).getText();
System.out.println(text);
driver.close();
// Switch back
driver.switchTo().window(windows.iterator().next());
driver.findElement(By.xpath("//body/a")).click();
}
private static void setWindows(WebDriver driver) {
windows = new HashSet<String>();
driver.getWindowHandles().stream().forEach(n -> windows.add(n));
}
private static String getWindow(WebDriver driver) {
List<String> newWindow = driver.getWindowHandles().stream()
.filter(n -> windows.contains(n) == false).collect(Collectors.toList());
System.out.println(newWindow.get(0));
return newWindow.get(0);
}
}