Search code examples
javajavascriptgwtappletjsni

GWT JSNI call applet method


I want to add a Java applet to a GWT page and call some of the applet's methods. This is possible in javascript by doing:

document.applet_id.someAppletMethod("value");

However when I try to implement the same idea using JSNI native function in GWT it fails. Basically it cannot find the applet object. Here's the JSNI code:

public native void callStringMethod(String methodName, String arg) /*-{
    var temp = "document." + [email protected]_project.AppletWrapper::appletName + "." + methodName + "(\"" + arg + "\");";             
    eval(temp);                                     //<----- FAIL

    //SOME TEST CODE
    $doc.applet_id.someAppletMethod("test value")   //<----- FAIL as well
    alert(typeof $doc.applet_id);                   //Undefined
    alert(typeof document.applet_id);               //Undefined
    alert(typeof $wnd.applet_id);                   //Undefined
}-*/;

Note1: I know "document" is not a valid name to be used from JSNI, you use $doc instead (explanation). I don't quite know how to encode this in eval() statement so the compiler replaces $doc with proper reference, and also the javascript generated contains the user specified method name and argument. As you may be aware it's not possible to just mix input Java variables and Javascript (explanation)

Note2: The following JavaScript runs from the web browser address bar

javascript:document.applet_id.someAppletMethod("asdf")

So the applet is there on the page, under document object and I can access it from Javascript. It's just not quite working from JSNI.

Note3: I'm adding the actual applet tag to a panel by subclassing GWT's HTML class. Along the lines of:

public AppletWrapper(String appletName, String jarName, String className) {
    StringBuilder applet = new StringBuilder();
    applet.append("<applet archive=\"").append(jarName).append("\" ");
    applet.append("code=\"").append(className).append("\" ");
    applet.append("name=\"").append(appletName).append("\" ");
    applet.append("id=\"").append(appletName).append("\" ");
    applet.append("width=\"100%\" height=\"450\">");
    applet.append("Browser doesn't support Java");
    applet.append("</applet>");
    this.setHTML(applet.toString());
}

Thanks for any help on getting this working.


Solution

    1. Try adding mayscript="mayscript" to the <applet> tag.
    2. Maybe naive - is the callStringMethod() called after the applet is added to the page?
    3. There are 2 other at least 2 other questions like this: GWT JSNI: invoking applet methods? and GWT problem with calling Java methods from JSNI