执行一个JavaScript函数从一个JavaFX程序的WebView(Execute a Java

2019-07-17 13:21发布

我试图从Java程序执行JavaScript函数。 JavaScript函数需要一个HTML文件的内容,并强调一个特定的词的出现。

是否有可能调用从网页视图对象的JavaScript函数?

Answer 1:

要在运行JavaScript WebView可以使用WebEngine.executeScript()方法。

而且有很多办法来突出由JavaScript文本。 例如, 在HTML文本高亮显示词(但不标记)

全部一起:

    WebView webView = new WebView();
    final WebEngine engine = webView.getEngine();
    engine.load("https://stackoverflow.com/questions/14029964/execute-a-javascript-function-for-a-webview-from-a-javafx-program");

    engine.getLoadWorker().stateProperty().addListener(
            new ChangeListener<State>() {
                @Override
                public void changed(ObservableValue ov, State oldState, State newState) {
                    if (newState == State.SUCCEEDED) {
                        engine.executeScript(
                                "function highlightWord(root,word){"
                                + "  textNodesUnder(root).forEach(highlightWords);"
                                + ""
                                + "  function textNodesUnder(root){"
                                + "    var n,a=[],w=document.createTreeWalker(root,NodeFilter.SHOW_TEXT,null,false);"
                                + "    while(n=w.nextNode()) a.push(n);"
                                + "    return a;"
                                + "  }"
                                + ""
                                + "  function highlightWords(n){"
                                + "    for (var i; (i=n.nodeValue.indexOf(word,i)) > -1; n=after){"
                                + "      var after = n.splitText(i+word.length);"
                                + "      var highlighted = n.splitText(i);"
                                + "      var span = document.createElement('span');"
                                + "      span.style.backgroundColor='#f00';"
                                + "      span.appendChild(highlighted);"
                                + "      after.parentNode.insertBefore(span,after);"
                                + "    }"
                                + "  }"
                                + "}"
                                + "\n"
                                + "highlightWord(document.body,'function');");
                    }
                }
            });


    Scene scene = new Scene(webView, 500, 500);

    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();


Answer 2:

您可以使用的ScriptEngine执行的JavaScript。 初始化的ScriptEngine,然后加载在脚本和评价它,如在下述代码

ScriptEngineManager manager = new ScriptEngineManager();  
ScriptEngine engine = manager.getEngineByName("JavaScript");  

// JavaScript code in a String  
String script = "function hello(arg) { print(arg); }";  

// evaluate script  
engine.eval(script);


文章来源: Execute a Javascript function for a WebView from a JavaFX program