Reputation: 601
I use SWT Browser object to load a web page like this:
Browser browser = new Browser(parent, SWT.BORDER);
browser.setUrl("http://localhost:18080/app/test-servlet");
I have a function to call the evaluate method. (The function is triggered by clicking a SWT Button on the control.)
public void evaluate() {
Object content = browser.evaluate("getClientContent();");
System.out.println("content: " + content);
}
On the web page, the javascript function getClientContent() is:
<script type="text/javascript">
function getClientContent() {
alert("test");
return "test";
}
</script>
When I click the test button on SWT application, I could see the alert box shown up with "test". But the evaluate() always returns null. What is wrong with the code? Thanks
Upvotes: 2
Views: 1615
Reputation: 12360
The return values are restricted to a few types:
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[]
Try for example
Object result = browser.evaluate("return 1;");
If the return type is not supported ... null seems to be returned.
Try for example
Object window = browser.evaluate("return window;");
The documentation for "evaluate" states
An SWTException is thrown if the return value has an unsupported type, or if evaluating the script causes a javascript error to be thrown.
which I find misleading since I would expect the above line to throw an exception since the window object can not be returned.
Upvotes: 0
Reputation: 111216
You need to 'return' the result in the JavaScript, like this:
Object content = browser.evaluate("return getClientContent();");
Upvotes: 4