# 从 Applet 调用 JavaScript 代码

> 原文： [https://docs.oracle.com/javase/tutorial/deployment/applet/invokingJavaScriptFromApplet.html](https://docs.oracle.com/javase/tutorial/deployment/applet/invokingJavaScriptFromApplet.html)

Java applet 可以调用与 applet 位于同一 Web 页面中的 JavaScript 函数。 [LiveConnect 规范](http://www.oracle.com/technetwork/java/javase/plugin2-142482.html#LIVECONNECT)描述了 JavaScript 代码如何与 Java 代码通信的详细信息。

`netscape.javascript.JSObject`类使 Java applet 能够检索对 JavaScript 对象的引用并与 Web 页面进行交互。接下来描述的数据小结小程序调用 JavaScript 代码从网页检索信息并将数据小结写回网页。

假设您有一个包含一些 JavaScript 函数的网页。示例 [``AppletPage.html``](examples/dist/applet_InvokingJavaScriptFromApplet/AppletPage.html)具有 JavaScript 函数来检索年龄，地址和电话号码。还有一个名为`userName`的变量，它在开始时没有值。

```
<head>
<title>Data Summary Applet Page - Java to JavaScript LiveConnect</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
<script language="javascript">
    var userName = "";

    // returns number
    function getAge() { 
        return 25;
    }
    // returns an object
    function address() { 
        this.street = "1 Example Lane";
        this.city = "Santa Clara";
        this.state = "CA";
    }
    // returns an array
    function getPhoneNums() { 
        return ["408-555-0100", "408-555-0102"];
    } 
    function writeSummary(summary) {
        summaryElem =
            document.getElementById("summary");
        summaryElem.innerHTML = summary;
    }
    </script>

    <!-- ... -->      
</head>
<body>
    <script src =
      "https://www.java.com/js/deployJava.js"></script>
    <script> 
        <!-- ... -->
        deployJava.runApplet(attributes, parameters, '1.6'); 
    </script>          
    <!-- ... -->
    <p id="summary"/>  // this HTML element contains
                             // the summary 
    <!-- ... -->
</body>

```

接下来，考虑一个名为`DataSummaryApplet`的 applet 类。 `DataSummaryApplet`类执行以下操作。

*   调用`JSObject`的`setMember`方法将`userName`变量设置为“John Doe”。
*   检索年龄，地址和电话号码，并构建包含此数据小结的字符串。
*   调用`writeSummary` JavaScript 函数将小结写回网页。

此 applet 首先需要检索对`JSObject`的引用，如下所示：

```
...
JSObject window = JSObject.getWindow(this);
...

```

将前面的语句放在 try ... catch ..块中以处理`netscape.javascript.JSException`。

现在 applet 引用了`JSObject`，它可以使用`JSObject`的`eval`和`call`方法调用相关的 JavaScript 函数。

```
package javatojs;

import java.applet.Applet;
import netscape.javascript.*; // add plugin.jar to classpath during compilation

public class DataSummaryApplet extends Applet {
    public void start() {
        try {
            JSObject window = JSObject.getWindow(this);

            String userName = "John Doe";

            // set JavaScript variable
            window.setMember("userName", userName);

            // invoke JavaScript function
            Number age = (Number) window.eval("getAge()");

            // get a JavaScript object and retrieve its contents
            JSObject address = (JSObject) window.eval("new address();");
            String addressStr = (String) address.getMember("street") + ", " +
                    (String) address.getMember("city") + ", " +
                    (String) address.getMember("state");

            // get an array from JavaScript and retrieve its contents
            JSObject phoneNums = (JSObject) window.eval("getPhoneNums()");
            String phoneNumStr = (String) phoneNums.getSlot(0) + ", " +
                    (String) phoneNums.getSlot(1);

            // dynamically change HTML in page; write data summary
            String summary = userName + " : " + age + " : " +
                    addressStr + " : " + phoneNumStr;
            window.call("writeSummary", new Object[] {summary})   ;
        } catch (JSException jse) {
            jse.printStackTrace();
        }
    }
}

```

要编译在`netscape.javascript`包中引用类的 Java 代码，请在类路径中包含`&lt;your JDK path&gt;/jre/lib/plugin.jar`。在运行时，Java Plug-in 软件自动使这些类可用于 applet。

“数据小结”小程序在网页上显示以下结果：

```
Result of applet's Java calls to JavaScript on this page

John Doe : 25 : 1 Example Lane, Santa Clara, CA : 408-555-0100, 408-555-0102

```

在浏览器中打开 [``AppletPage.html``](examples/dist/applet_InvokingJavaScriptFromApplet/AppletPage.html)以查看“数据小结”小程序。

* * *

**Note:**  If you don't see the applet running, you need to install at least the [Java SE Development Kit (JDK) 6 update 10](http://www.oracle.com/technetwork/java/javase/downloads/index.html) release.

* * *

* * *

**Note:**  If you don't see the example running, you might need to enable the JavaScript interpreter in your browser so that the Deployment Toolkit script can function properly.

* * *

[从[AppG 示例下载 _ 调用 JavaScript 代码的源代码 _](examplesIndex.html#InvokingJavaScriptFromApplet)进一步试验。