有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Eclipse SWT:Browser#evaluate()始终返回null

我使用SWT Browser对象加载网页,如下所示:

Browser browser = new Browser(parent, SWT.BORDER);
browser.setUrl("http://localhost:18080/app/test-servlet");

我有一个函数来调用evaluate方法。(该功能通过单击控件上的SWT按钮触发。)

public void evaluate() {
    Object content = browser.evaluate("getClientContent();");
    System.out.println("content: " + content);
}

在网页上,javascript函数getClientContent()是:

<script type="text/javascript">
    function getClientContent() {
        alert("test");
        return "test";
    }
</script>

当我点击SWT应用程序上的测试按钮时,我可以看到警告框显示为“测试”。但是evaluate()总是返回null。代码有什么问题?谢谢


共 (2) 个答案

  1. # 1 楼答案

    返回值仅限于几种类型:

    Returns the result, if any, of executing the specified script.

    Evaluates a script containing javascript commands in the context of the current document. If document-defined functions or properties are accessed by the script then this method should not be invoked until the document has finished loading (ProgressListener.completed() gives notification of this).

    If the script returns a value with a supported type then a java representation of the value is returned. The supported javascript -> java mappings are:

    *javascript null or undefined -> null

    *javascript > number -> java.lang.Double

    *javascript string -> java.lang.String

    *javascript boolean -> java.lang.Boolean

    *javascript array whose elements are all of supported types -> java.lang.Object[]

    举个例子

     Object result = browser.evaluate("return 1;");
    

    如果不支持返回类型。。。null似乎被返回

    举个例子

    Object window = browser.evaluate("return window;");
    

    “评估”状态的文档

    An SWTException is thrown if the return value has an unsupported type, or if evaluating the script causes a javascript error to be thrown.

    我发现这有误导性,因为我希望上面这行会抛出一个异常,因为窗口对象无法返回

  2. # 2 楼答案

    您需要在JavaScript中“返回”结果,如下所示:

    Object content = browser.evaluate("return getClientContent();");