I have the following Javascript executed in a webengine. Source: Execute a Javascript function for a WebView from a JavaFX program
This Javascript highlights a specific word on a website.
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');");
}
}
});
I want to check, whether a website contains a specific word and I thought this code is a good starting point, since it worked fine and highlights words. What I need now is, that the Javascript should count when highlighting. Then, if a word is contained (counter >= 1), I want to get a boolean return value, that I can access in JavaFX.
I tried some things but I really dont know how to midify the Script to add a counter and a return value that can be accessed outside the script.
Thank you all for reading.