简体   繁体   中英

Is it possible to register a javascript event that triggers when java applet is fully loaded?

I have a web application that uses java applet defined in a <applet> tag. Is it possible to add a javascript event that is triggered after the applet is fully loaded? This is some initialization javascript that is dependent on that the applet is fully loaded and valid.

javascript invoking is rather simple:

Your init() method can include the jsObject declaration and javascript invoking:

@Override
public void init() {
// some code
  JSObject jsObject = JSObject.getWindow(this);
  jsObject.eval("your javascript");

}

If you don't have source code control over the applet, you can poll for the applet to be loaded before calling methods on it. Here is a utility function I wrote that does just that:

/* Attempt to load the applet up to "X" times with a delay. If it succeeds, then execute the callback function. */
function WaitForAppletLoad(applet_id, attempts, delay, onSuccessCallback, onFailCallback) {
    //Test
    var to = typeof (document.getElementById(applet_id));
    if (to == 'function' || to == 'object') {
        onSuccessCallback(); //Go do it.
        return true;
    } else {
        if (attempts == 0) {
            onFailCallback();
            return false;
        } else {
            //Put it back in the hopper.
            setTimeout(function () {
                WaitForAppletLoad(applet_id, --attempts, delay, onSuccessCallback, onFailCallback);
            }, delay);
        }
    }
}

Call it like this:

WaitForAppletLoad("fileapplet", 10, 2000, function () {
        BuildTree("c:/");
    }, function () {
        alert("Sorry, unable to load the local file browser.");
    });

You have an initializer function (i think it is run) in java applet. From there you can call a javascript in the web page after initialization work. To work you must add the MAYSCRIPT attribute to your applet definition

<applet id="someId" code="JavaApplet.class" codebase="/foo" archive="Applet.jar" MAYSCRIPT>
</applet>

Code example to invoke a JavaScript:

public String invokeJavaScript(Object caller, String cmd) throws TiNT4Exception {
    printDebug(2, "Start JavaScript >>" + cmd + "<<");
    try {
      // declare variables
      Method getw = null;
      Method eval = null;
      Object jswin = null;

      // create new instance of class netscape.javascript.JSObject
      Class c = Class.forName("netscape.javascript.JSObject"); // , true, this.getClass().getClassLoader()); // does it in IE too

      // evaluate methods
      Method ms[] = c.getMethods();
      for (int i = 0; i < ms.length; i ++) {
        if (ms[i].getName().compareTo("getWindow") == 0) { getw = ms[i]; }
        else if (ms[i].getName().compareTo("eval") == 0) { eval = ms[i]; }
      } // for every method

      printDebug(3, "start invokings");
      Object a[] = new Object[1];
      a[0] = caller;
      jswin = getw.invoke(c, a);
      a[0] = cmd;
      Object result = eval.invoke(jswin, a);

      if (result == null) {
        printDebug(3, "no return value from invokeJavaScript");
        return "";
      }

      if (result instanceof String) {
        return (String)result;
      } else {
        return result.toString();
      }
    } catch (InvocationTargetException ite) {
      throw new TiNT4Exception(ite.getTargetException() + "");
    } catch (Exception e) {
      throw new TiNT4Exception(e + "");
    }
  } // invokeJavaScript

You can use the param tag to pass the name of a JS function into your applet:

<applet id="myapplet" code="JavaApplet.class" codebase="/foo"
        archive="Applet.jar" MAYSCRIPT>
  <param name="applet_ready_callback" value="myJSfunction"/>
</applet>

In your applet, get the value of the param and call the function when ready:

@Override
public void init() {
  String jsCallbackName = getParameter("applet_ready_callback");
  JSObject jsObject = JSObject.getWindow(this);
  jsObject.eval(jsCallbackName + "()");
}

I used another way to call a JavaScript function from an applet.

try {
    getAppletContext().showDocument(new URL("javascript:appletLoaded()"));
} catch (MalformedURLException e) {
    System.err.println("Failed to call JavaScript function appletLoaded()");
}

...must be called in the applet class which extends Applet or JApplet. I called the JavaScript function at the end of my start() method.

It is possible with Java 7 SE. You can register onLoad() event or just poll status , see Handling Initialization Status With Event Handlers for an example.

In order to use this functionality, you should deploy the applet with java_status_events parameter set to true .

The article Applet Status and Event Handlers outlines the status and events:

Status

  • LOADING = 1 - Applet is loading
  • READY = 2 - Applet has loaded completely and is ready to receive JavaScript calls
  • ERROR = 3 - Error while loading applet

Events

  • onLoad : Occurs when applet status is READY . Applet has finished loading and is ready to receive JavaScript calls.
  • onStop : Occurs when applet has stopped.
  • onError : Occurs when applet status is ERROR . An error has occurred while loading the applet.

You can register or determine an event handler in the JavaScript code of a web page as shown in the following code snippets.

 // use an anonymous function applet.onLoad(function() { //event handler for ready state } // use a regular function function onLoadHandler() { // event handler for ready state } // Use method form applet.onLoad(onLoadHandler); // Use attribute form applet.onLoad = onLoadHandler; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM