How to call a JavaScript function from a JavaFX WebView on Button click?
Asked Answered
K

2

10

I am trying to call a JavaScript function from a JavaFX WebView on a JavaFX button click event.

I am using the following code, but it is not working:

try {
  File file = new File("F:\\inputfile\\hello.htm");

  WebEngine webengine = webview.getEngine();
  webengine.load(file.toURI().toURL().toString());
} catch(Exception ex) {
  ex.printStackTrace();
}

On any button click I want to execute the test() JavaScript method in the html file:

webengine.executeScript("test()");

And the JavaScript method in html file is:

<script language="javascript">
  function test()
  {
    window.scrollBy(0, 20); 
  }
</script>
Kernite answered 17/10, 2013 at 7:34 Comment(0)
B
14

I used your code as following and it works

package org.im.oor;

import java.io.File;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

/**
 *
 * @author maher
 */
public class main extends Application {

    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("fire JS");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                if (webengine != null) 
                {
                    webengine.executeScript("test()");
                }
            }
        });

        publishServices();
        StackPane root = new StackPane();
//        root.getChildren().add(btn);
        HBox hh = new HBox();
        hh.getChildren().add(btn);
        hh.getChildren().add(webview);


        root.getChildren().add(hh);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    private WebEngine webengine;
    private static WebView webview;

    private void publishServices() {



        try {
            webview = new WebView();
            webview.setVisible(true);
            webengine = webview.getEngine();
            webengine.setJavaScriptEnabled(true);
            File file = new File("c:\\hello.html");
            System.out.println(file.exists() + " file exitence");
            webengine.load(file.toURI().toURL().toString());
        } catch (Exception ex) {
            System.err.print("error " + ex.getMessage());
            ex.printStackTrace();
        }




    }


    /**
     * The main() method is ignored in correctly deployed JavaFX application.
     * main() serves only as fallback in case the application can not be
     * launched through deployment artifacts, e.g., in IDEs with limited FX
     * support. NetBeans ignores main().
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
}

content of c:\hello.html

<html>
<header>
<script language="javascript">
 function test()
 {
   //window.scrollBy(0,20); 
   document.body.style.backgroundColor="#00f3f3";
   alert('test');

 }
 </script>
</header>
<body>test
<a href='#' onclick="test();">fire for test</a>
</body>
</html>

check this code and let me know .. just some points on that :

  • check if you can really access that file ..

  • make you program simple to test if its working JS<==>JavaFX, then you can go further and use more advanced JS functions

Blas answered 17/10, 2013 at 9:22 Comment(0)
A
0

I was trying to use JavaFX to automatically login to a site. On my windows development machine I was able to find the control and cast it to a HtmlInputElement or HtmlButtonElementImpl and click the item. Moving to openjfx 11.0.2 on linux, this gave me an unimplemented link error After some time and finding several posts I was able to inject javascript in to the page and then execute the javascript to click the button.

    final String injectedScript = "script = document.createElement('script');\n" +
            "var head = document.getElementsByTagName(\"head\")[0];\n" +
            "script.type = 'text/javascript';\n" +
            "var t = document.createTextNode(\"function jsclick(ctrl){document.getElementById(ctrl).click()}\");\n" +
            "script.appendChild(t);" +
            "head.appendChild(script);";

    webEngine.documentProperty().addListener((ov, oldDoc, doc) -> {
        if (doc != null ) {
            webEngine.executeScript(injectedScript);

            processLoginPage(webEngine, doc);
        }
    });

When processing the form, to submit it (doing a form.submit did not work):

        Element d = doc.getElementById("logon_button");
        //HTMLButtonElementImpl b = ((HTMLButtonElementImpl) d);
        //b.click();
        webEngine.executeScript("jsclick('logon_button')");
Alberthaalberti answered 7/6, 2021 at 20:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.