[英]Execute a Javascript function for a WebView from a JavaFX program
I am trying to execute a Javascript function from a Java program. 我试图从Java程序执行Javascript函数。 The Javascript function takes the content of a HTML file and highlights the occurrences of a particular word.
Javascript函数获取HTML文件的内容并突出显示特定单词的出现。
Is it possible to call a Javascript function from a webview object? 是否可以从webview对象调用Javascript函数?
To run javascript in WebView
you can use WebEngine.executeScript()
method. 要在
WebView
运行javascript,您可以使用WebEngine.executeScript()
方法。
And there are plenty of ways to highlight text by javascript. 并且有很多方法可以通过javascript突出显示文本。 Eg Highlight word in HTML text (but not markup)
例如, 突出显示HTML文本中的单词(但不是标记)
All together: 全部一起:
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();
You can use ScriptEngine to execute a javascript. 您可以使用ScriptEngine来执行javascript。 initialize ScriptEngine, then load the script in and evaluate it, as shown in below mentioned code
初始化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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.