【问题标题】:How to call a JavaScript function from a JavaFX WebView on Button click?如何在单击按钮时从 JavaFX WebView 调用 JavaScript 函数?
【发布时间】:2013-10-25 14:10:48
【问题描述】:

我正在尝试在 JavaFX 按钮单击事件上从 JavaFX WebView 调用 JavaScript 函数。

我正在使用以下代码,但它不起作用:

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

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

在任何按钮上单击我想在 html 文件中执行 test() JavaScript 方法:

webengine.executeScript("test()");

而html文件中的JavaScript方法是:

<script language="javascript">
  function test()
  {
    window.scrollBy(0, 20); 
  }
</script>

【问题讨论】:

    标签: javascript javafx-2 javafx


    【解决方案1】:

    我使用你的代码如下,它可以工作

    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);
        }
    }
    

    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>
    

    检查此代码并告诉我.. 只是一些观点:

    • 检查您是否真的可以访问该文件..

    • 让你的程序变得简单,测试它的 JS 是否工作JavaFX,然后你可以更进一步,使用更高级的 JS 函数

    【讨论】:

      【解决方案2】:

      我试图使用 JavaFX 自动登录到一个站点。在我的 Windows 开发机器上,我能够找到控件并将其转换为 HtmlInputElement 或 HtmlButtonElementImpl 并单击该项目。移动到 linux 上的 openjfx 11.0.2,这给了我一个未实现的链接错误 一段时间后,我找到了几篇帖子,我能够将 javascript 注入页面,然后执行 javascript 以单击按钮。

          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);
              }
          });
      

      在处理表单时,提交它(做一个form.submit 不起作用):

              Element d = doc.getElementById("logon_button");
              //HTMLButtonElementImpl b = ((HTMLButtonElementImpl) d);
              //b.click();
              webEngine.executeScript("jsclick('logon_button')");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-11
        • 1970-01-01
        • 2020-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多