views:

946

answers:

3

Is it possible to pass a function/callback from javascript to a java applet?

For example i have an applet with a button that when pressed it will call the passed js callback

function onCommand() {alert('Button pressed from applet');}
applet.onCommand(onCommand);
+1  A: 

You can use JSObject to call back into javascript from Java.

From that page:

import netscape.javascript.*;
import java.applet.*;
import java.awt.*;
class MyApplet extends Applet {
     public void init() {
         JSObject win = JSObject.getWindow(this);
         JSObject doc = (JSObject) win.getMember("document");
         JSObject loc = (JSObject) doc.getMember("location");

         String s = (String) loc.getMember("href");  // document.location.href
         win.call("f", null);                      // Call f() in HTML page
     }
}
moonshadow
is it also possible to pass js function which is an object as the first argument of win.call instead the name of the js function?
ken
No, but instead of passing in the bare callback function you could create a new object containing it, pass that in then use the object.call(name) form.
moonshadow
+2  A: 

I tend to use something I derived from the reflection example at the bottom of this page, as then you don't need to meddle with your classpath to get it to compile

Then I just pass JSON strings around between the applet and javascript

tim_yates
thx for the link, it just contains all the possible methods
ken
+3  A: 

ps. to use JSObject you may need to include "MAYSCRIPT" tag to applet html tag.

Tom