Sami
Sami

Reputation: 1389

Calling Java function from JavaScript

I am trying to call a Java Function as a callback from JavaScript using JavaFX. First, I added the Java class as a member of window during initialization:

JSObject jsobj = (JSObject) currentWebEngine.executeScript("window");
jsobj.setMember("java", this);

The Java request function is described as follows inside the Platform.runLater():

String script = "document.makeRequest('"+inputString+"')";
currentWebEngine.executeScript(script);

After the asynchronous request is done in the javascript side, it should call a java function to return the result. However, I am getting exceptions in that side. I even tried calling a function without argument and still doesn't work:

window.java.returnResult();

But I get the following exception:

Exception in runnable netscape.javascript.JSException: TypeError: 'undefined' is not an object

It has nothing to do with the asynchronous request since I even tried calling it directly in makeRequest() function and got the same error. Any idea what I did wrong in that area? The previous code is integrated in a Desktop JFrame application, not an applet.

Upvotes: 2

Views: 2463

Answers (2)

Sami
Sami

Reputation: 1389

I managed to find the solution of the problem. The following code was called a bit early and therefore the class is not registered within javascript:

JSObject jsobj = (JSObject) currentWebEngine.executeScript("window");
jsobj.setMember("java", this);

I just called it at the listener of the web engine and it worked.

Upvotes: 3

Abhilash Ranjan
Abhilash Ranjan

Reputation: 743

Use DWR, You can use java methods through JavaScript.

Upvotes: 0

Related Questions