Ben Hocking
Ben Hocking

Reputation: 8092

Is there a simple way to get the JavaScript output in Java (using Eclipse)?

I'm trying to get the return value of a JavaScript function I've written. I can do it using a very complicated method involving listeners, but I'm wanting to use Eclipse's Browser.evaluate method.

As a toy problem, I have the following code in a Java file:

Object result = this.browser.evaluate("new String(\"Hello World\")");

where this.browser is created in a class extending org.eclipse.ui.part.EditorPart in the overridden function createPartControl:

public void createPartControl(Composite parent) {
  // Create the browser instance and have it 
  this.browser = new Browser(parent, SWT.NONE);
  this.browser.addFocusListener(new FocusAdapter() {
    @Override
    public void focusGained(FocusEvent e) {
      SomeEditor.this.getSite().getPage().activate(SomeEditor.this);
    }
  });
  new ErrorReporter(this.browser);
  this.browser.setUrl(Activator.getResourceURL("html/java-shim.html").toString());
  ...more stuff snipped...
}

However, instead of result being a Java String with the contents "Hello World", it's null. Am I using this method incorrectly, or is it broken?

Upvotes: 5

Views: 596

Answers (1)

Udo Klimaschewski
Udo Klimaschewski

Reputation: 5315

You have to return a value in JavaScript:

Object result = browser.evaluate("return 'Hello World'");

works for me.

Upvotes: 3

Related Questions