This piece of code works in IE and Firefox but not in Chrome.
---
import javax.swing.*;
import java.applet.Applet;
import java.awt.Component;
import java.awt.event.*;
import netscape.javascript.JSObject;
import static javax.swing.SwingUtilities.invokeLater;
public class Focus extends Applet {
private Object jsFocus() {
final JSObject jsObject = JSObject.getWindow(Focus.this);
try {
jsObject.eval("document.getElementById('text1').tabIndex = 0;");
jsObject.eval("document.getElementById('text1').focus();");
Object doc = jsObject.getMember("document");
Object element = ((JSObject) doc).call("getElementById", new Object[]{"text1"});
Object focusResult = ((JSObject) element).call("focus", new Object[]{});
System.out.println("jsFocus completed");
}
catch (Exception e) {
e.printStackTrace();
}
return new Object();
}
public void whoHasFocus(Object o) {
final JSObject jsObject = JSObject.getWindow(Focus.this);
jsObject.eval("document.getElementById('text2').value = (document.getElementById('text1') == document.activeElement);");
System.out.println("whoHasFocus after event " + o);
}
public void init() {
invokeLater(new Runnable() {
public void run() {
final JTextField text = new JTextField("press 't' to transfer focus, 'e' to evaluate who has focus via javascript");
text.addKeyListener(new KeyAdapter() {
public void keyTyped(final KeyEvent e) {
if (e.getKeyChar() == 't') {
jsFocus();
whoHasFocus(e);
e.consume();
}
if (e.getKeyChar() == 'e') {
whoHasFocus(e);
e.consume();
}
}
});
text.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
whoHasFocus(e);
}
public void focusLost(FocusEvent e) {
whoHasFocus(e);
}
});
Focus.this.add(text);
text.requestFocus();
}
});
}
}
---
On the html page
<body onload="document.getElementById('text2').focus()"><br>
transfer to this box <input type='text' id='text1' /><br>
This box do nothing <input type='text' id='text2' />
What is observed in IE/Firefox, on startup, "false" is observed in input text2. nothing". When 't' is pressed in applet textfield, the focus is transferred to html input "text1" and input text2 shows "true".
On Chrome, when 't' is pressed in applet textfield, the focus is NOT transferred to html input "text1" and input text2 still show "true". Chrome thinks that it got the focus but didnt grab focus from applet.