openjdk-jfx icon indicating copy to clipboard operation
openjdk-jfx copied to clipboard

Issue with calling Java method from JavaScript

Open arunan123 opened this issue 4 years ago • 1 comments

I have the following code, when I run and click anywhere in the webpage, it should invoke fromDom() with the string passed right. But it is not working as expected. It seems stackoverflow community for javafx is dead, no one answers over there. If it is not a bug please forgive me.

`import javafx.application.Application; import javafx.concurrent.Worker; import javafx.scene.Scene; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; import javafx.stage.Stage; import netscape.javascript.JSObject; import static org.joox.JOOX.$;

public class Main extends Application {

public String fromDom(String e){
    System.out.println(e);
    return e;
}
@Override
public void start(Stage stage) throws Exception {
    Main main = new Main();
    try {
        stage.setTitle("Test");

        WebView w = new WebView();
        WebEngine e = w.getEngine();
        e.load("https://webscraper.io/test-sites/e-commerce/ajax");
        // create a scene
        Scene scene = new Scene(w, w.getPrefWidth(),
                w.getPrefHeight());
        stage.setScene(scene);
        stage.show();

        JSObject obj = (JSObject) e.executeScript("window");
        obj.setMember("main",main);
        obj.setMember("window.onclick","function(e){\n"+
                "main.fromDom('Hello');\n" +
                "}");
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}
public static void main(String[] args) {
    launch(args);
}

}`

arunan123 avatar Mar 04 '20 09:03 arunan123

public abstract void setMember(String name, Object value) throws JSException Sets a named member of a JavaScript object. Equivalent to "this.name = value" in JavaScript.

The above is the javadoc for JSObject's setMember method. So when I am passing the following,

obj.setMember("window.onclick","function(e){\n"+ "main.fromDom('Hello');\n" + "}");

It should be like this.window.onclick = function(e){ main.fromDom('hello');} right? Or am i wrong?

arunan123 avatar Mar 04 '20 09:03 arunan123