5

我正在尝试从 Java 程序执行 Javascript 函数。Javascript 函数获取 HTML 文件的内容并突出显示特定单词的出现。

是否可以从 webview 对象调用 Javascript 函数?

4

2 回答 2

7

要在其中运行 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();
于 2012-12-25T22:10:02.870 回答
-1

您可以使用 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);
于 2012-12-25T11:31:45.723 回答