How to get current active window while running my java application - java

I need to get current active window.
I have used KeyboardFocusManager, for getting active window. But i am getting active window is null.
below is the code.
please provide any way to get current active window.
KeyboardFocusManager currentManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
Window activeWindow = currentManager.getActiveWindow();

This single line of code should work:
Window activeWindow = javax.swing.FocusManager.getCurrentManager().getActiveWindow();
from the JavaDoc:
Returns the active Window, if the active Window is in the same context
as the calling thread. Only a Frame or a Dialog can be the active
Window. The native windowing system may denote the active Window or its
children with special decorations, such as a highlighted title bar.
The active Window is always either the focused Window, or the first
Frame or Dialog that is an owner of the focused Window.
to get the GlobalActiveWindow, call:
javax.swing.FocusManager.getCurrentManager().getGlobalActiveWindow();
JavaDoc:
Returns the active Window, even if the calling thread is in a different context than the active Window. Only a Frame or a Dialog can be the active Window. The native windowing system may denote the active Window or its children with special decorations, such as a highlighted title bar. The active Window is always either the focused Window, or the first Frame or Dialog that is an owner of the focused Window.
Note:
When your application does not have the focus, this method returns null!
Cheers!

Found the following code and it worked fine for me:
Window getSelectedWindow(Window[] windows) {
Window result = null;
for (int i = 0; i < windows.length; i++) {
Window window = windows[i];
if (window.isActive()) {
result = window;
} else {
Window[] ownedWindows = window.getOwnedWindows();
if (ownedWindows != null) {
result = getSelectedWindow(ownedWindows);
}
}
}
return result;
}
And you can call it like this using the static method of class Window:
Window w = getSelectedWindow(Window.getWindows());
Good Luck.
Almost forgot to mention, I've found the recursive method in this site.

Related

Unclear about driver.getWindowHandles() & driver.getWindowHandle()

Hi all I am learning Selenium & I am not really clear about how the above two functions work:
Problem Statement:
I have a practice assignment say: Go to http://the-internet.herokuapp.com/
Click on a link> Multiple Windows A Window opens> Click on>> Click Here Another Window opens>> from this window grab text and print it After that go back to this http://the-internet.herokuapp.com/windows and print text.
Flow: http://the-internet.herokuapp.com/>>>http://the-internet.herokuapp.com/windows>>>http://the-internet.herokuapp.com/windows/new
Que1) If I use driver.getWindowHandle() and print it for each window its value remains constant so does this method always returns the parent window or it works differently.
Ques2) When I use driver.getWindowHandles() it is returning 2 values in the set. Does driver.getWindowHandles() return the parent window as well. (I am not sure if there should be 2 or 3 values as I have 3 URLS I thought the set should have 3)
Ques3) Can someone share the most effective way to work with multiple child window id's:
Set with iterator method
People also convert Set to Arraylist and then use get method. [which is a better way]
Code:
driver.get("http://the-internet.herokuapp.com/");
String p1=driver.getWindowHandle();
System.out.println(p1);
text1=driver.findElement(By.xpath("//a[#href='/windows']"));
text1.click();
WebElement
text2=driver.findElement(By.xpath("//a[#href='/windows/new']"));
text2.click();
Set<String> child=driver.getWindowHandles();
System.out.println(child.size());
ArrayList<String> children=new ArrayList<String>(child);
System.out.println(children);
driver.switchTo().window(children.get(1));
System.out.println(driver.findElement(By.xpath("//div[#class='example']/h3")).getText());
driver.close();
driver.switchTo().window(children.get(0));
System.out.println(driver.findElement(By.xpath("//div[#class='example']/h3")).getText());
driver.switchTo().window("");
System.out.println(driver.getCurrentUrl());
driver.close();
driver.get("http://the-internet.herokuapp.com/");
String p1=driver.getWindowHandle(); //Gets the newly opened and the only window handle
System.out.println("This is parent window handle " + p1);
text1=driver.findElement(By.xpath("//a[#href='/windows']"));
text1.click(); //Navigates, no new window opened. Handle remains the same
//WebElement 'Unnecessary code
text2=driver.findElement(By.xpath("//a[#href='/windows/new']"));
text2.click(); //opens second window/tab as per the settings. there are 2 window handles here for current driver instance
Set<String> child=driver.getWindowHandles(); //set of 2
System.out.println(child.size());
// ArrayList<String> children=new ArrayList<String>(child);' modifying this
String strSecondWindowHandle = "";
for(String str : s) // as set is not an ordered collection we need to loop through it to know which position holds which handle.
{
if(str.equalsIgnoreCase(p1) == false) //to check if the window handle is not equal to parent window handle
{
driver.switchTo().window(str) // this is how you switch to second window
strSecondWindowHandle = str;
break;
}
}
// System.out.println(children);
// driver.switchTo().window(children.get(1)); //not required
System.out.println(driver.findElement(By.xpath("//div[#class='example']/h3")).getText());
driver.close(); // now this will close the second window
driver.switchTo().window(p1); // switches to main window
System.out.println(driver.findElement(By.xpath("//div[#class='example']/h3")).getText());
// driver.switchTo().window(""); //not required as it is the same window
System.out.println(driver.getCurrentUrl());
driver.close(); //closes the main window
So to answer your questions
Window handle is automatically and uniquely assigned by the operating system (Windows) to each newly opened window
Q1 --> Until and unless you explicityly switch the windows, the window handle remains the same. switching is the key here.
Q2 --> Navigating does not change the handles. it is not page specific rather it is window specific. getWindowHandles will return all the open browser windows opened by WebDriver instances that is currently running. Already open windows are not included.
Q3 --> Using the for loop demonstrated above, you open the window, find the ID which is not your parent window handle, store it in a variable. Repeat the procedure for more windows.
You can see in the documentation what are the main differences between getWindowHandle() and getWindowHandles() methods:
getWindowHandle(): Return an opaque handle to this window that uniquely identifies it within this driver instance.
getWindowHandles(): Return a set of window handles which can be used to iterate over all open windows of this WebDriver instance by passing them to switchTo().WebDriver.Options.window()
In simpler terms, driver.getWindowHandles() stores the set of handles for all the pages opened simultaneously, but driver.getWindowHandle() fetches the handle of the web page which is in focus. It gets the address of the active browser and it has a return type of String.

Calling dispose() or WindowEvent causes parent window to freeze

I am currently attempting to add functionality to a program such that if a user closes a child window, it will also close the parent window that created it. I boot the starting program, select an option in the menu that will create the parent window, which then creates the child window. The program already has a endProcess function that prints something to the parent window so I figured it would be a good place to accomplish this task. Here is that function:
private synchronized void endProcess(Exec.FinishedEvent e) {
exec.removeFinishedListener(this);
exec = null;
String str;
if (e.getExitValue() != 0) {
JOptionPane.showMessageDialog(this, exec, "Exec '"+e.getExec()+"' failed: return value: "+e.getExitValue(), JOptionPane.ERROR_MESSAGE);
str = "Process FAILED [exit="+e.getExitValue()+"]: '"+e.getExec()+"'\n";
} else
str = "Process Done [exit="+e.getExitValue()+"]: '"+e.getExec()+"'\n";
statusLabel.setText(str);
outputTextArea.append("*****" + str);
//this.dispose();
//this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
The bottom two commented out lines are what I have tried to add. (Two different ideas) Both of these work properly in that when I close the child window, the parent window also closes. However, it also freezes the original program window and will not respond to anything. I believe I am somehow calling some sort of kill function to the original program window as well? Thank you and let me know if I need to provide anything else!
To clarify...
Original Program = Window that first opens when booting the program
Parent Window = Command I run in the original program to produce the child window (I wish this one to close and NOT the Original Program when closing the child)
Child Window = The Window created from the Parent Window that I wish to also close the Parent Window upon the Child Window's closing.

Close platform after closing a pop-up | JavaFX

So I have 2 stages, one is the main stage and the other is a pop-up screen. When the pop-up screen shows up you can close it by pressing the 'x' at the upper-left (or upper-right depending on your OS). Is there a way to close the main stage whenever you close the pop-up screen?
Stage and Popup inherit an onHidden property from Window. This is a handler that is invoked immediately after the window is hidden (by any mechanism). You can call Platform.exit() in the handler in order to exit the application:
popup.setOnHidden(event -> Platform.exit());
Note that Platform.exit() is generally preferred to System.exit(0): calling System.exit(...) will not allow the Application's stop() method to be called, so you may bypass any resource clean-up your application is performing.
There have a Event named setOnCloseRequest. If you are opening an Alert pop-up window.
Alert popup = new Alert(AlertType.INFORMATION);
Then your solution is:
alert.setOnCloseRequest(new EventHandler<DialogEvent>()
{
#Override
public void handle(DialogEvent t)
{
System.exit(0);
}
});
Else if you want to close another window with it's owner, then just use it's stage and replace DialogEvent with WindowEvent.

WizardPage adjustment with change of screen resolution

I have a dialog with a wizard containing one wizard page. The wizard page appears differently for different screen resolution. Some contents of wizardpage is missed if the it is executed in laptop or desktop with different screen resolution.
I have set the wizard page size in the dialog:
dialog.setPageSize(700, 700);
But eventhough this is not working properly. Please let me know is there any way so that wizard page gets adjusted with screen resolution changes.
Thanks in advance.
In your WizardPage you can reset the size of the dialog to match the preferred size of the contents using something like this:
private void recalcSize()
{
Composite dialogAreaComp = (Composite)getControl();
Shell shell = getShell();
Point shellSize = shell.getSize();
dialogAreaComp.layout(true, true);
Point newSize = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
if (newSize.x != shellSize.x || newSize.y != shellSize.y)
shell.setSize(newSize);
}
Put a call to recalcSize in the setVisible method of the page.

Webdriver showModalDialog

We are using webdriver for our functional tests. But our application uses the showModalDialog JS function a lot to open a popup. When we try to test this functionality with webdriver it hangs from the moment the popup is opened.
We tried several things to test this:
Using the workaround explained here. But this seems to be a fix for selenium and not for webdriver. We tried it but it didn't work.
Searching for a good alternative, HtmlUnit opened the modal dialog and could interact with it, but it has it's drawbacks like no visual help to fix certain tests and it stopped execution when it detected a JS error in a JS library we have to use but have no control over.
How can we test this or work around this problem?
From my experiences with various automation tools interaction with "webpage dialog" windows opened from IE using window.showModalDialog() or window.showModelessDialog() is not available.
Since the window is not a "true" window (look at the taskbar, it doesn't even show up) most tools can't "inspect" it and/or interact with it.
However if you do find a tool that will, please advise - there are many people looking for such a beast.
That all said, if you can possibly avoid using either of these 2 proprietary methods you'll have much more luck.
(and yes, for the picky ones, Firefox and Chrome have adopted these kind of dialogs but they don't work quite the same)
None of the answers answer the question. If the driver hangs, then you can't call any methods on it. The question is NOT about finding the pop up, it is about how to stop the driver hanging. The only way I have found is to not use showModalDialog. This can be done by adding the folowing to your test code :
((JavascriptExecutor) driver).executeScript("window.showModalDialog = window.open;");
which calls window.open each time your JavaScript calls window.showModalDialog.
I am using webdriver.SwitchTo().Window() method but my concern is my popup window does not have "Name"
When I use webdriver.WindowHandles it return only one handle, I am using this statement after popup window open.
As I don't have name / handle I cannot switch from parent window to child window.
Any other solution to do the same functionality
First we have to switch to the active element:
driver.switchTo().activeElement();
To check whether we have actually switched to the correct active element:
driver.switchTo().activeElement().getText();
Even if the window doesn't have name u can use
driver.switchTo.defaultcontent();
and perform the operation you want to execute
or else you can get the window handle name using the below command
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle); }
hope this should work for you.
Issue 284 is for WebDriver. It seems that it will be implemented only after Issue 27 will be implemented, so the fix should be in Beta 1 or 2 of WebDriver.
Set<String> beforePopup = driver.getWindowHandles();
Set<String> afterPopup = driver.getWindowHandles();
afterPopup.removeAll(beforePopup);
if(afterPopup.size()==1){
System.out.println(afterPopup.toArray()[0]);
}
driver.switchTo().window((String) afterPopup.toArray()[0]);
What I have been using and it works great for us on with IE and Firefox is to go through popups
and look for a a unique text on the popup you are trying to interact with. Here is the method, let me know if it works for you. Please note the line driver = driver.switchTo().window(windowHandle);
public void switchWindow(String containingText, WebDriver driver) throws Exception {
if ( StringUtils.isEmpty(containingText))
return;
int counter = 1;
int numOfpopups = driver.getWindowHandles().size();
System.out.println("Waiting for popup to load..... # handles:" + numOfpopups);
while ( numOfpopups < 2 && ((counter%10) != 0) ) {
counter++;
try{Thread.sleep(1000);}catch (Exception e) {}
}
System.out.println("Done waiting for..... " + counter + " seconds");
if (driver.getWindowHandles().size() < 2)
throw new BrowserException("Timeout after " + counter + " secs. No popup present. ");
System.out.println("Going through window handles...");
for (String windowHandle : driver.getWindowHandles()) {
driver = driver.switchTo().window(windowHandle);
if ( driver.getPageSource().contains(containingText)
return;
else
continue;
}
throw new Exception("Window containing text '" + containingText + "' not found");
}
To my knowledge, webdriver has no built-in functionality to handle modal windows as of now. Webdriver will hang once you click button which opens modal window. This happens due to JS on parent window halts until child window is closed.
To handle modal windows such as this one, see below for possible workaround written in Java. The main idea is to perform action that opens modal window (click on the button) in new thread.
/**
* Click button to open modal window and switch to it
* #param we webElement handle of a button
*/
public void clickToOpenModal(final WebElement we) {
//Get handles of all opened windows before opening modal window
Set<String> initWindowHandles = getDriverInstance().getWindowHandles();
//Create new thread and click button to open window
Thread thread1 = new Thread() {
#Override
public void run() {
//Click button
click(we);
}
};
thread1.start();
//Wait for window to appear
waitForWindow(initWindowHandles, pauseL);
thread1.interrupt();
thread1 = null;
//Get handles of all opened windows after opening modal window
Iterator<String> it = getDriverInstance().getWindowHandles().iterator();
//Select handle of modal window
String windowHandle = "";
while(it.hasNext()){
windowHandle = it.next();
}
//Switch focus and work on the modal window
getDriverInstance().switchTo().window(windowHandle);
}
The solution by Hugh Foster works, i tried this and succeeded
((JavascriptExecutor) driver).executeScript("window.showModalDialog = window.open;");
You can find the url of modal dialog then open it on another tab, it will work as normal.
In case you want to deal with open modal dialog, you can try to send "tab" key for move around objects and "send keys... enter" for setText or click.
Note: Below is some information why you cannot use selenium webdriver for work with that modal.
Modal pop-up - This is very specific to IE, Microsoft defined it as
When Windows Internet Explorer opens a window from a modal or modeless HTML dialog box by using the showModalDialog method or by using the showModelessDialog method, Internet Explorer uses Component Object Model (COM) to create a new instance of the window. Typically, the window is opened by using the first instance of an existing Internet Explorer process. When Internet Explorer opens the window in a new process, all the memory cookies are no longer available, including the session ID. This process is different from the process that Internet Explorer uses to open a new window by using the open method.
http://msdn.microsoft.com/en-us/library/ms536759(VS.85).aspx
MSDN blog on Modal dialog
When user select Model popup, parent window is blocked waiting for the return value from the popup window. You will be not able to see the view source of the page, need to close the popup then only the parent window is activated.

Categories

Resources