While doing handle windows in selenium - Java, in Java it shows one 1 window open and if i tried with C# it shows 2 . I am not able to get the window handle of second window opened(Actually it is a message dialog box, i need to click on ok button and proceed to the parent window) in Java.Please help me to sort this out
You should have searched for solution on internet and tried it yourself first, well below code might help you:
//Before you click, get main window handle
String mainhandle=driver.getWindowHandle();
//Enter code to click button
new WebDriverWait(driver, 60)
.ignoring(NoAlertPresentException.class)
.until(ExpectedConditions.alertIsPresent());
flag=0;
while(flag==0){
try{
driver.switchTo().alert().accept();
flag=1;
}
catch(Exception e){
driver.manage().timeouts().implicitlyWait(1,TimeUnit.SECONDS);
}
}
driver.switchTo().window(mainhandle);
Related
I am working with Selenium, now there is a condition:
when I hit a button in my webpage a window pop up opens up.
Now I have to click a radio button (one out of two, it will work even if we send a TAB ) and then click an OK button. I searched in the net and got to know about "driver.getWindowHandle()".
But I don't have any idea dealing with the newly opened window popup.
Need help in this.
For switching purpose u can use enhanced for loop:
for (String winHandle : objDriver.getWindowHandles()) {
objDriver.switchTo().window(winHandle);
}
So it will switch the control from one driver window to child windows.
To interact with elements on the window try to find element with whatever tool u r using and perform the required action after switching to the window.
To return back to parent window you can use the same loop or use:
driver.switchTo().defaultContent();
Check my answer in this post and also read the comments to help you understand the difference between getWindowHandle() and getWindowHandles()
Java: focus is not on pop-window during window handling
We handled this situation using AutoItX - https://www.autoitscript.com/site/ in our Windows/IE C# project:
AutoItX3 autoIt = new AutoItX3();
var handle = autoIt.WinWaitActive("[window title]", "", 20);
Assert.IsTrue(handle != 0", string.Format("Was not able to find: {0}", [window title]);
autoIt.Send("{ESCAPE}"); // tab may work as well for selection
The pop up was a Windows window, and not part of IE, therefore the WebDriver didn't know about it.
Hope this helps.
Let's say
I have a window 1. I have performed an event on the window 1 that makes window 2 to appear.
Now I switched to the window 2 and clicked a button on it which closes window 2.
If I use driver.close() after I performed an event which caused the window to close, sometimes it throws NoSuchWindowException.
If I don't use the driver.close() then sometimes driver.getWindowHandles().size() returns 2 even when there is only one window and I have waited enough time to number of windows become 1.
I refresh driver.getWindowHandles() and check for the driver.getWindowHandles().size() to become 1 but it doesn't sometimes.
My question is, do I need to use the method driver.close() after I clicked the button that caused the window to close? How to use the driver.close() correctly.
EDIT: Yes, it is a problem. If selenium doesn't realize window2 has been closed, it keeps returning the handles to be 2. Suppose that I closed window2 and switched back to window1 and performed an event which opens window3. Now I want to switch to window3. Here is the problem because Selenium still think windows2 exists and now there are three windows according to the Selenium.
String window1Handle = driver.getWindowHandle();
//Now I have oepend window3
//According to the Selenium there are 3 windows
// So driver.getWindowHandles().size() returns 3
for (String window : driver.getWindowHandles() {
if (!window.equals(window1Handle)) {
driver.switchTo().window();
The above line may throw exception because driver is trying to switch to a window which has already been closed"
No you don't need to perform a driver.close(), if anything is left open, when you perform a driver.quit() at the end of your test WebDriver will clean up and make sure that everything is shut down correctly.
Selenium can track how many windows are open, if you are seeing window handles for windows that are closed that sounds like a potential bug. Bear in mind that it may take some time for Selenium to realise that the window has been closed, you could try using an explicit wait to wait for the count of window handles to drop back down to 1, you'll need to add the following ExpectedCondition:
public static ExpectedCondition<Boolean> numberOfWindowsToBe(final int numberOfWindows) {
return new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
return driver.getWindowHandles().size() == numberOfWindows;
}
};
}
Then you can use it by doing:
WebDriverWait wait = new WebDriverWait(driver, 15, 100);
wait.until(numberOfWindowsToBe(1));
or you could just try closing the window by performing a driver.close() and catching the NoSuchWindowException e.g.
try{
driver.close();
} catch(NoSuchWindowException ignored){
System.out.println("Window already closed");
}
This should give Selenium the kick it needs to realise that the window has been closed (Although to be honest I wouldn't bother).
*EDIT*
So it sounds like the problem is that you have multiple window handles and you don't know which one is the window that has been closed, and which one is your newly opened window. One workaround would be to track the window handles in a Map. Every time you open a new window store the window handle in the map like this:
Map<String, String> openedWindows = new HashMap<String, String>();
openedWindows.put("Window 1", driver.getWindowHandle());
You will then know which window handle is associated with your window, you can then remove windows from the map as they are closed. You will know which handles that are still being reported are actually closed and which are being reported in error.
Really this sounds like a bug in Selenium window handling and I would suggest you raise an issue on the issue tracker with a minimal test script that reproduces the problem. Of course the other option above is still valid, try and close the window but catch the exception and see if that gives Selenium the kick it needs to remove it from the list of window handles.
I had the same exact issue You are facing.
Before i perform an action which pops up second window, i intiated
String window = driver.getWindowHandle();
Later i clicked link 1 which populates window 2 and i switch to that window
driver.switchTo().window(window name);
i performed my action in Window 2 and when i click the link in Window 2 my window closes automatically and if i use driver.close() it wont happen as webdriver will throw error as u said
so instead of trying to close the second window, i try to switch back to window 1 with
driver.switchTo().window(window);
This is because since window 2 is closed automatically and since the control does not pass to window 1 the error will happen.. So there is no necessity to close window 2. instead we can switch back to our default window and continue or close the default window..
I know that this is a bit of a hack...but I've never seen something like what you are describing, so I think its worth a try. Change this code:
driver.switchTo().window();
to something like this:
try{
driver.switchTo().window();
perform action that will throw error
return; //will return if error wasn't thrown
catch(Error thrown if on bad window){
//continue in your for loop to switch to the next window;
}
I wrote a method that is working pretty good for me.
public static boolean letWebDriverRealizeThisWindowHasBeenClosed(WebDriver driver,
String closedWindowHandle) {
/**
* to avoid infinite loop, do write a break when definite time has been passed
*/
/**
* Generally, this method returns true given that window is closed
*/
boolean isWebDriverRealized = false;
long start = System.currentTimeMillis();
long end = start + (30 * 1000); //30 seconds
while (!isWebDriverRealized
&& System.currentTimeMillis() < end) {
try {
driver.switchTo().window(closedWindowHandle);
} catch (NoSuchWindowException nswe) {
isWebDriverRealized = true;
}
}
return isWebDriverRealized;
}
If this method returns true, then it means WebDriver has realized that window has been closed. driver.getWindowHandles.size() returns the correct number of windows once the above method returns true.
No, you don't need to do that. Because second window is already close, and if you will use method driver.close() it will close your first window and the browser itself(because there is only one tab left in browser window).
Its depends upon the Window,
some Window close while click on outside Window content, in that case no need of driver.close() method.
but for some Window, click on outside the Window content, Window unable to close (i.e. Window gets close after click on close button), in that case need to close such Window using thedriver.close() method.
I'm creating screenshots in my testcases with selenium webdriver, and while these indeed show what is visible in my web application, it doesn't show popups created by the browser.
I have found that in IE in some cases, my app triggers a JS debug popup in IE. This is of course an error and breaks the rest of my test, but the screenshot does not show the error. I presume this is because it's an IE native popup, rather than one trigger by my application.
Is it possible to get this included in the screenshots? I was thinking of maybe creating the screenshot with Robot#createScreenCapture() but obviously that wouldn't show anything useful if the browser is minimized.
So, a few possible solutions:
- can you detect if an error message pops up in a browser
- is it possible to maximise/focus the browser while running?
- can you take screenshots from selenium with the popups showing?
Selenium will take a screenshot that represents the rendered DOM that the browser shows the end user by intercepting the rendered image that the browser is displaying and taking a copy of it.
It does not take a desktop screenshot so the screenshots shown will not show anything covering the browser window. JavaScript alerts are not part of the rendered DOM so you will not see these in Selenium screenshots.
Maybe because the driver is not with the Alert/Window active?
You could try something like this:
private void CheckForOtherWindows()
{
//Check for any other window open
if (driver.WindowHandles.Count > 0)
{
foreach (string window in driver.WindowHandles)
{
driver.SwitchTo().Window(window);
TakeScreenshot();
}
}
//Check for alert window
try
{
driver.SwitchTo().Alert();
TakeScreenshot();
}
catch
{
//Nothing
}
}
This is not tested, not sure if works. Just giving the idea. :)
Edit:
To maximize the window is easy:
driver.Manage().Window.Maximize();
Hope it helps.
You can use this as below:
FileUtils.copyFile(((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE), new File("E:\\ScreenShot\\screenshot.png"));
In my application , by clicking the save button, the dialog prompts a message with OK button. While recording 'the OK button' got recorded and shows 'text_ok().click(atpoint(11,8));'. But during play back it shows me a 'Object not found' error.
Recently updated the RFT Version 8.2.2.1 after this only this issue is seen.
Can anyone say me how to solve this problem or any coding in java.
My regression is waiting due to this, your help is highly appreciable.
Thanks in Advance.
You have not mentioned what type of dialog window it is. But you can try the IWindow API of RFT to find active top window and perform the click as specifed below.
The Following code for eg can handle an alert dialog box in html by calling
handleDialogButton("Message from Webpage", "ok");
Or,to click on canel button on Notepad's Font dialog (Format>Font) by calling
handleDialogButton("font","cancel");
-------Sample code----
/*
* Activates the top window with the given caption and clicks on the child control(window) with the specified text
* #param caption- Caption of the Dialog window
* #param btnToClick- Text of the button(any other control) to click
*/
void handleDialogButton(String caption,String btnToClick)
{
IWindow[] windows = getTopWindows();
for(IWindow window: windows)
{
if(window.getText().equalsIgnoreCase(caption))
{
window.activate();
//window.close(); //we can just close it also n break.
IWindow[] children = window.getChildren(); // OR go thru the children to get the child
for(IWindow child:children)
{
if(child.getText().equalsIgnoreCase(btnToClick))
{
child.click();
break;
}
}
}
}
unregisterAll();
}
From the poing of Selenium Web driver API i recommend you do the following:
Alert alert = driver.switchTo().alert();
alert.accept();
Hope this works for you
I am testing a web application that creates a new window long after a button is clicked. The sequence is the following
window 1: (parent window) click button to create window 2
window 2: progress window appears until background process on server returns data
window 3: progress window turns into 3rd window (with different handle)
I want to properly wait for the 3rd window to appear. I know what the 'title' of all 3 windows will be however in order to get the titles from WebDriver I have to use the following code:
while(timeout has not occured...){
for (String handle : _driver.getWindowHandles()) {
String myTitle = driver.switchTo().window(handle).getTitle();
if(3rdWindowTitle.equalsIgnoreCase(myTitle)){
return true;
}
}
}
This will effectively switch the active window back and forth every time it loops because of the 'switchTo'. This causes the firefox windows to cycle back and forth really quickly and is obnoxious. What I need is a way to get the title's of the windows that are available without having to 'switchTo' each window in a loop waiting for the 3rd window. Any ideas?
I basically want a method (waitForWindowByTitle(titleIWant)) which will block until the window with the title I want appears.
Well, Better you can wait for your window to appear by checking the number of windows. Like:
for(int i=0; i<noOfTrials;i++){
noOfWindows = driver.getWindowHandles().size();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
if(noOfWindows>currentNoOfWindows){
break;
}
}
}
then for the first and last time you can browse through the windows (using switchTo) and navigate to the window you want.