Calling DOM objects using Java's ScriptEngine or WebEngine classes
-
18-06-2021 - |
Question
Is it possible to modify html elements using the ScriptEngine or WebEngine classes from Java? I've tried the following:
/* theSite is a WebEngine object. Assume the id 'Email' is correct */
Element email=(Element) theSite.executeScript("document.getElementById('Email');");
email.setAttribute( "value", "navon.josh" );
I saw something like this in an example, but it didn't seem to work. I also tried this:
final ScriptEngineManager manager = new ScriptEngineManager();
final ScriptEngine engine = manager.getEngineByName( "js" );
try {
engine.eval( "document.getElementById( 'Email' ).value = 'navon.josh'" );
} catch( ScriptException e) {
e.printStackTrace();
}
This also didn't work. Is it because the statement isn't linked to the WebEngine?
Solution
To access DOM model of html loaded into JavaFX 2 WebView you can use WebEngine
API. E.g. here is an example of adding listener to HTML TextArea:
WebEngine webEngine = webView.getEngine();
webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {
public void changed(ObservableValue ov, State oldState, State newState) {
if (newState == Worker.State.SUCCEEDED) {
// note next classes are from org.w3c.dom domain
EventListener listener = new EventListener() {
public void handleEvent(Event ev) {
System.out.println(ev.getType());
}
};
Document doc = webEngine.getDocument();
Element el = doc.getElementById("textarea");
((EventTarget) el).addEventListener("keypress", listener, false);
}
}
});
webEngine.loadContent("<textarea id='textarea'></textarea>");
OTHER TIPS
No. The DOM is part of a browser and you don't have a browser.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow