Here are the source code files to a Java applet that utilizes
LiveConnect to communicate with Javascript, and the HTML file.
The thing works both in IE 6.0 and FireFox 1.4. but with some problems.
IE crashes when one refreshes the page or leave the page. This happens
only after calling the Java method more than once. It does not crash if
the Java method is called just once and then the page is refreshed.
FireFox does not crash at all and no error whatsoever. However, it
takes a good minute or two to display the newly created element. And,
if during that time if one calls the Java method, it gives an error
and it never works afterwords. But, once the Java method returns after
the first time, it works robustly no matter how many times the Java
method is called or if the page is refreshed or closed.
Can any LiveConnect guru please take a look at this code and let me
know whats wrong with it.
Thank you very much in advance.
D.K. Mishra
======== Hello.class ========
import java.applet.App let;
import java.awt.Graphi cs;
import netscape.javasc ript.*;
public class Hello extends Applet {
private JSObject win;
private JSObject doc;
public void init() {
}
public void start() {
win = JSObject.getWin dow(this);
doc =(JSObject) win.getMember(" document");
}
//A set of 2 overloaded helper methods to create object array to pass
// as the 2nd argument to doc.call(string ,Object[]).
public Object[] objArr(JSObject jso) {
Object[] ret = {jso};
return ret;
}
public Object[] objArr(String str) {
Object[] ret = {str};
return ret;
}
//This cretes a filled HTML Tag like <p>Hello</p> or
//<i>world!</i>.
public JSObject createFilledTag (String strTag, String strText) {
JSObject fragDoc = (JSObject)
doc.call("creat eDocumentFragme nt",null);
JSObject tagEle = (JSObject)
doc.call("creat eElement",objAr r(strTag));
JSObject tagTextEle =
(JSObject)doc.c all("createText Node",objArr(st rText));
tagEle.call("ap pendChild",objA rr(tagTextEle)) ;
fragDoc.call("a ppendChild",obj Arr(tagEle));
return fragDoc;
}
//This method is called from javascript. It inserts
//*** Hello World! ***" into the empty <p id="para"></p>
//element
public void insertText(Stri ng str) {
JSObject paraEle = (JSObject) doc.call("getEl ementById",
objArr(str));
JSObject tmpEle = createFilledTag ("b","*** Hello World! ***");
paraEle.call("a ppendChild",obj Arr(tmpEle));
}
}
======== hello.htm ========
<html>
<head>
<title> New Document </title>
<script>
function addElement() {
app = document.getEle mentById("Hello ");
app.insertText( "para");
}
</script>
</head>
<body>
<input type="button" onclick="addEle ment()" value="Fill"/>
<p id="para"></p>
<applet id="Hello" code="Hello.cla ss" width="1" height="1"
mayscript="true " scriptable="tru e">
</applet>
</body>
</html>