Java/Javascript bring browser window containing applet to foreground - java

Is there a way to pull a browser window to the foreground/focus from a Java applet alert window? I have an applet in a html page that brings up an alert with a button in it. When the button is pressed, I want the original browser window to pop up from wherever it is (minimized, covered, etc.) I believe there is a way to connect Java to Javascript to do this, but I don't know Javascript.
Here is the Java applet code:
/** An applet that posts an alert and waits for the alert button to be pressed.
* Version 1 uses http://java.sun.com/products/plugin/1.3/docs/jsobject.html
*/
import netscape.javascript.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Bounce extends JApplet implements ActionListener {
JDialog dialog;
JSObject window;
String message;
public void paint(Graphics g) {
g.clearRect(0,0, 400,40);
g.drawString(message,40,20);
}
public void init() {
JFrame frame= null;
dialog= new JDialog(frame, "Bounce App");
JButton setupButton= new JButton("Bounce it back!");
setupButton.addActionListener(this);
JPanel contentPane= new JPanel();
contentPane.add(setupButton);
contentPane.setOpaque(true);
dialog.setContentPane(contentPane);
dialog.setSize(new Dimension(400, 110));
dialog.setVisible(true);
message= "This applet posts an alert panel.";
window= JSObject.getWindow(this);
// String[] params= { "An alert message" };
// window.call("alert", params);
// window.eval("alert('Important Alert!')");
}
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
dialog.dispose();
System.err.println("button has been pushed; focus set");
message= "Somebody pushed my bounce-back button.";
JSObject document= (JSObject)window.getMember("document");
document.setMember("bgColor", "orange");
window.eval("focus()");
repaint();
}
}
And here is the HTML code:
<HTML>
<HEAD><TITLE>The Reappearing Page</TITLE></HEAD>
<body bgcolor="#f0ffc0">
<H2>Make this page reappear</H2>
This page will start an applet (white box below) that sets up an alert.
Before you respond to the alert, hide the window you are reading right now,
using one of these methods:<ul>
<li> cover it with another window, </li>
<li> Hide it using a menu item, </li>
<li> Minimize it, or </li>
<li> move it to another workspace or desktop. </li>
</ul>
Then click on the button in the alert.
<P>
<EMBED type="application/x-java-applet;version=1.3" width="400" height="40"
align="baseline" code="Bounce.class" MAYSCRIPT=true
pluginspage="http://java.sun.com/products/plugin/1.3/plugin-install.html">
<NOEMBED>
No JDK 1.3 support for APPLET!!
</NOEMBED>
</EMBED>
<P>What is supposed to happen is that the main window
will emerge from wherever you hid it and reappear.
Since I don't know how to do this, it is your challenge to actually make it happen.
We need to be able to achieve this magic from any of the situations listed above.</P>
</body>

(Changed from comment to answer so I can post a decent code snippet for you) There is no reliable way to "foreground" a window using JavaScript, unless it's a window you created yourself from a parent page, for obvious reasons ("Congratulations!! You are our 1000th customer, you win a prize!!!!!"). If you've loaded your applet window as a popup using window.open from another window, you could try using window.focus:
var w = window.open(appletPageUrl);
w.focus()
I imagine popup blockers don't appreciate this sort of thing, so YMMV. On a personal note, I would suggest that you have a think about whether a user wants to know about your alert if they've chosen to hide/minimise your app.

Related

How to open another JSP page in popup window in Java

I want to open a new JSP page as a popup window. After the submit button is clicked, the user can provide data without leaving the main page. For now, it simply redirects to another page, which makes the page a bit less user friendly.
I am using this code to redirect to the other page:
response.sendRedirect("http://localhost:8080/APP/add.jsp");
And it works correctly, but it is not satisfying for me.
You can use this code. Here mypopup is a java script function which will show the popup window. It takes a parameter url. You can use this function on your submit button click.
<script type="text/javascript">
function mypopup(url) {
width = window.screen.width;
height = window.screen.height;
mywindow = window.open(url, "Title",
"location=0,status=1,scrollbars=1,resizable=1,menubar=0,toolbar=no,width="
+ width + ",height=" + height);
mywindow.moveTo(0, 0);
mywindow.focus();
}
</script>
<input type="submit"
onclick='mypopup("http://localhost:8080/APP/add.jsp");return false;' value="Submit"/>

multiple modal dialog boxes, unable to select the top most one

I am running a test and am running into unexpected issue managing a modal dialog box.
The user uploads a file in a modal dialog box and if the file already exist on the system another seperate modal dialog opens asking the user if they want to overwrite the existing file.
I am having difficulties in manipulating the buttons on this second dialog.
When I manage the first dialog I do the following, which works:
void switch_to_dialog_window(WebDriver driver){
driver.switchTo().frame(driver.findElement(By.cssSelector("div.d2l-dialog>div>iframe")));
}
The html when both dialogs are open looks like this:
<div class="d2l-dialog" style="top: 70px; width: 700px; height: 520px; left: 630px; z-index: 1002;">
<div class="d2l-dialog-inner" style="height: 518px;">
<iframe class="d2l-dialog-frame" src="/d2l/common/dialogs/file/main.d2l?ou=11346&af=MyComputer%2cOuFiles%2cSharedFiles%2cgooglefiledownloader%2coffice365filedownloader&am=1&fsc=1&asc=0&mfs=0&afid=0&uih=&area=MyComputer&f=&path=%2fcontent%2fenforced%2f11346-Gherkin_Cucumber%2f&d2l_body_type=2" name="d2l_c_10_968" allowfullscreen="" scrolling="no" style="width: 698px; height: 518px; overflow: hidden;" frameborder="0"/>
</div>
</div>
<div class="d2l-dialog" style="top: 90px; width: 475px; height: 415px; left: 800px; z-index: 1004; display: block;">
<div class="d2l-dialog-inner" style="height: 413px;">
<iframe class="d2l-dialog-frame" src="/d2l/lp/fileinput/11346/Duplicates?files=photo.jpg" name="d2l_c_1_182" allowfullscreen="" scrolling="no" style="width: 473px; height: 413px; overflow: hidden;" frameborder="0"/>
</div>
</div>
I'm trying to control the dialog which mentions duplicates.
I tried to modify the method for switch_to_dialog_window to be more specific (as a test to identify the first dialog box to control that):
driver.switchTo().frame(driver.findElement(By.cssSelector("div.d2l-dialog>div>iframe[src^='/d2l/common/dialogs/file/main.d2l']")));
This doesn't work though so i cant implement that way to manage the 2 dialogs.
I tried to switch to the default content and then switch back to the Dialog using the method 'switch_to_dialog_window' but that doesn't work either. I tried just trying to access the button on the dialog box directly but that doesnt work:
public void confirm_duplicate() {
//driver.findElement(By.xpath("//iframe[starts-with(#src, '/d2l/lp/fileinput/11346/Duplicates')]"));
//driver.switchTo().frame(driver.findElement(By.cssSelector("div>div>iframe[src^='/d2l/lp/fileinput/11346/Duplicates']")));
try{
//driver.switchTo().frame(driver.findElement(By.cssSelector("div>div>iframe[name^='d2l_c_1_']")));
driver.findElement(By.linkText("Update")).click();
}catch(Exception e)
{
System.out.println("could not click on the Update button on the top most dialog box");
e.printStackTrace();
}
}
I seem to be running around in circles with this one and is exhausting. Can someone explain how to get control of this top most dialog box?
And also could you possibly teach me as to why the following expression isnt working:
driver.switchTo().frame(driver.findElement(By.cssSelector("div.d2l-dialog>div>iframe[src^='/d2l/common/dialogs/file/main.d2l']")));
Robot API can be used to get handle topmost modal box if there is an issue with switching to frame.
To use Robot API, give the following line of codes
Robot key = new Robot();
key.keyPress(KeyEvent.VK_ENTER);
key.keyRelease(KeyEvent.VK_ENTER);
Make sure that the control is already on the intended button. If the focus is on another button on the modal, then give 'tab' or other keyevent to get the control on the update button.
I have taken a break of a couple of months from automation. I happened to be doing some maintenance on my scripts and found the root cause of this problem.
The issue was not with my code, the code was fine just i forgot one crucial step. During the business process a second window was opened which required user input. I used the code to switch to this popup window.:
public void get_window_ids(){
//Get the handles for the main window and the popup window for the upload button
try {
Set<String> AllWindowHandles = driver.getWindowHandles();
System.out.println(AllWindowHandles.size()+ " distinct windows: " + AllWindowHandles);
window1 = (String) AllWindowHandles.toArray()[0];
System.out.println("\nwindow 1 is " + window1+"\n");
window2 = (String) AllWindowHandles.toArray()[1];
System.out.println("\nwindow 2 is " + window2+"\n");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getWindow1() {
return window1;
}
public String getWindow2() {
return window2;
}
When I switched to the window2 I forgot to switch back to the first window. I just missed the fact that there was a popup window I forgot about. So if you are using these modal popups remember to return control back to the main window.

Bootstrap (actually JQuery) DatePicker does not hide on blur in Wicket modal

I have a wicket bootstrap DateTextField on a panel inside modal. When datepicker is shown from click, datepicker is attached to the root page, not the modal.
That causes a problem: without adding some z-index to datepicker, I cannot see it on top of modal.
When I blur from the picker, it should close. Somehow, due the fact the picker is not child of modal, clicking outside datepicker closes it only, if it is clicked outside the modal. Inside modal nothing happens.
I can tweak this by autoclose, but when you go to input and manually use backSpace to clear the value, there is no a way to close datepicker by clicking somewhere inside the modal.
Some html to make it clear:
<html>
<panel>
<modal>
<input>datefield is here</input>
</modal>
<panel>
<datepicker comes here>
</html>
How to get datepicker attached to modal, or somehow else fix the issue of blur inside the modal?
I have tried to attach the panel a click event that hides datepicker, but it hides the datepicker right away when it opens.
Edit:
Click to modal does nothing, although html is moved artificially there and is placed correctly in DOM tree. Thanks to #Gavriel about insight to moving stuff between DOM elements, though.
Edit2:
Code to reproduce situation:
class MyPanel extends Panel {
DateTextField field = new DateTextField("foo");
(...)
add(field);
}
class MyPage extends WebPage {
(...)
ModalWindow modal = new ModalWindow("modal");
modal.add(new MyPanel());
(...)
}
html for the panel, containing the dateTextField
<html>
..
<input wicket:id="foo"></input>
..
</html>
As you see from snippet, java code generates the jQuery part.
Edit3:
I speak about this creature:
[DateTextField sources] https://github.com/l0rdn1kk0n/wicket-bootstrap/blob/master/bootstrap-extensions/src/main/java/de/agilecoders/wicket/extensions/markup/html/bootstrap/form/DateTextField.java
Edit4:
Hmm.. I added in Javascript a blur event listener inside the input in modal and that blur even did not work. So it turns out that the real question in hand is how to get onblur work inside modal. Because that is what is broken!!
Edit5:
Sorry, cannot give fiddle. From Edit3 you see sources I use for picker and what I really call is this function:
protected CharSequence createScript(final DateTextFieldConfig config) {
return $(this).chain("datepicker", config).get();
}
which is inside java class, so not JavaScript at all although syntax is looking so similar. For my understanding fiddles take no java code inside them. Wicket needs the java part, I am sorry about it.
For fiddle askers I found similar situation on this fiddle: http://jsfiddle.net/VytfY/227/ - works 100% ok, similar technologies I mention here, no use to my problem.
Last edit:
$('html').on('click',function(e){
if(e.target.className.indexOf('datepicker') == -1 &&
e.target.className != 'next' && e.target.className != 'prev' &&
e.target.className != 'year' && e.target.className != 'month'){
if ($('.datepicker').get(0) != undefined){
$('.datepicker').get(0).remove();
}
}
});
Thanks #Mathew you made my day, above is what it ended to be. I added to input element a class datepickerContainer so clicking it does not hide picker.
Thanks folks, this is done!
One more: for IE, use:
var canvas = $('.datepicker').get(0);
canvas.parentNode.removeChild(canvas);
instead of direct remove. Remove not yet supported, even IE11.
The idea is to move the div created by datepicker.
Use http://api.jqueryui.com/datepicker/#option-beforeShow You can see an example how it is used in a slightly different use case: How to add a custom class to my JQuery UI Datepicker
When you append an element to the DOM that was already inside the DOM, it is removed from the original place, in other words if you use $("#dst").append("#src"), then src element is moved to dst.
Update: I think there's a more straightforward way: You provide the id of the div you want it to use. This way you can have this div inside your modal dialog.
$("#button").on('click', function(){
$("#datepicker").datepicker();
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<button id="button">choose date</button>
<div id="datepicker"></div>
<div>footer</div>
$("#button").on('click', function(){
var dt=$("#datepicker").show();
dt.datepicker().on('change', function (ev) {
$(dt).hide();
});
$('html').on('click',function(e){
if(e.target.id !='button'){
$(dt).hide();
}
});
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<button id="button">choose date</button>
<div id="datepicker"></div>
<div>footer</div>

Unable to handle showModalDialog window in Selenium Webdriver(Java)

I am automating a web application using Selenium webdriver(java). I have handled popup windows in other parts of application but i'm not able to handle showModalDialog window. Application has read only text box and I have to fill this by clicking Search button, which will open new popup window.
HTML code for this Textbox and Serach button is as follows.
<tr>
<td><label class="classLabel">Textbox<sup class="mandatory">*</sup></label></td>
<td><input type="text" name="textbox" value="" readonly="readonly" class="someTextbox">
<img src="/Some/url/search.gif" alt="Select Help" onclick="launch2()" />
</td>
</tr>
After clicking Search button, a showModalDialog window will open and there I have to click a radio button to fill text box.
This showModalDialog window has iframe element and below is html code for this.
<iframe src="/some/url.do?parameter=getData" width='100%' height='100%' border=0 >
</iframe>
Below is the code I'm using to switch into popup window and select iframe. Here, test case is simply stopping after clicking Search button and popup window also appearing but it is not handling popup.
driver.findElement(By.cssSelector("img[alt=\"Select Help\"]")).click();
String winHandleBefore = myD.getWindowHandle();
for(String winHandle : myD.getWindowHandles()){
driver.switchTo().window(winHandle);
}
driver.switchTo().frame(0);
driver.findElement(By.name("hier_data_id")).click();
If anybody have idea on how to handle showModalDialog windows, it would be really helpful. Suggestions would be appreciated.
Thanks in advance !
import java.util.Iterator;
import java.util.Set;
private static String popUp;
//get window handle before popup
Set<String> beforePopUp = driver.getWindowHandles();
//do the click
driver.findElement(By.cssSelector("img[alt=\"Select Help\"]")).click();
//get window handles after the click
Set<String> afterPopup = driver.getWindowHandles();
//remove all window handles before the popup
afterPopUp.removeAll(beforePopUp);
if(afterPopUp.size() == 1) {
popUp = (String) afterPopUp.toArray()[0];
} else {// there might be more than on popups that might have been triggered by the click...do some error handling here}
//switch to popUp
driver.switchTo().window(popUp);
//do your stuff

The "Modal" function in Flex is different from Java? Don't pause the thread of the parent component?

I'm beginner in Flex 4. I'm trying to pop up a Flex WindowTitle custom component, and after the user choose some values, the parent window must be refreshed.
I'm showing the modal window, the user can't interact with other components, but the problem I detect is the execution of the program flows, even I choosing to show the Input window as modal, the next methods to refresh the page is called before the user close the modal page. I don't know if flex or ActionScript works different from Java, where I used to code.
Please, see the comments on the code example:
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.core.FlexGlobals;
import mx.managers.PopUpManager;
public function add_clickHandler(event:MouseEvent):void
{
var frm: FrmNovaOpcao = new FrmNovaOpcao();//titleWindow
//add modal window
PopUpManager.addPopUp(frm, this, true);
//center modal window
PopUpManager.centerPopUp(frm);
refreshAll(); //this method is being called before the user close the modal window =[
}
]]>
</fx:Script>
I solved adding event handlers and callback functions to the modal windows.
I research and understood that flex is event driven, and prioritize the UI refresh, and don't work with threads.
Not bad to a UI driven technology.
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.core.FlexGlobals;
import mx.managers.PopUpManager;
protected function add_clickHandler(event:MouseEvent):void
{
var frm: FrmNovaOpcao = new FrmNovaOpcao();
//add modal window
PopUpManager.addPopUp(frm, this, true);
//center modal window
PopUpManager.centerPopUp(frm);
frm.btnAdd.addEventListener(MouseEvent.CLICK, refreshOptions);
}
protected function refreshOptions(mousevent:MouseEvent):void{
refreshAll();
}
]]>

Categories

Resources