简体   繁体   English

是否可以注册一个Java程序完全加载时触发的javascript事件?

[英]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. 我有一个Web应用程序,它使用在<applet>标记中定义的java applet。 Is it possible to add a javascript event that is triggered after the applet is fully loaded? 是否可以添加在Applet完全加载后触发的javascript事件? This is some initialization javascript that is dependent on that the applet is fully loaded and valid. 这是一些初始化javascript,取决于小程序已完全加载且有效。

javascript invoking is rather simple: javascript调用非常简单:

Your init() method can include the jsObject declaration and javascript invoking: 您的init()方法可以包含jsObject声明和javascript调用:

@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. 如果您没有对applet的源代码控制,则可以在调用applet上的方法之前轮询要加载的applet。 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. 您在Java小程序中有一个初始化函数(我认为它已运行)。 From there you can call a javascript in the web page after initialization work. 初始化工作后,您可以从那里在网页中调用JavaScript。 To work you must add the MAYSCRIPT attribute to your applet definition 要工作,必须将MAYSCRIPT属性添加到小程序定义中

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

Code example to invoke a JavaScript: 调用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: 您可以使用param标记将JS函数的名称传递到小程序中:

<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. 我使用了另一种方式从applet调用JavaScript函数。

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. ...必须在扩展Applet或JApplet的applet类中调用。 I called the JavaScript function at the end of my start() method. 我在start()方法的末尾调用了JavaScript函数。

It is possible with Java 7 SE. Java 7 SE是可能的。 You can register onLoad() event or just poll status , see Handling Initialization Status With Event Handlers for an example. 您可以注册onLoad()事件或仅轮询status ,有关示例,请参见使用事件处理程序处理初始化状态

In order to use this functionality, you should deploy the applet with java_status_events parameter set to true . 为了使用此功能,应在java_status_events参数设置为true部署小程序。

The article Applet Status and Event Handlers outlines the status and events: Applet状态和事件处理程序一文概述了状态和事件:

Status 状态

  • LOADING = 1 - Applet is loading LOADING = 1-Applet正在加载
  • READY = 2 - Applet has loaded completely and is ready to receive JavaScript calls READY = 2-Applet已完全加载并准备接收JavaScript调用
  • ERROR = 3 - Error while loading applet ERROR = 3-加载小程序时出错

Events 大事记

  • onLoad : Occurs when applet status is READY . onLoad :当小程序状态为READY时发生。 Applet has finished loading and is ready to receive JavaScript calls. Applet已完成加载,可以接收JavaScript调用了。
  • onStop : Occurs when applet has stopped. onStop :当applet停止时发生。
  • onError : Occurs when applet status is ERROR . onError :在applet状态为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. 您可以在网页的JavaScript代码中注册或确定事件处理程序,如以下代码段所示。

 // 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; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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