0

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?

Disco Globeulon
  • 459
  • 1
  • 6
  • 16

2 Answers2

2

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>");
Sergey Grinev
  • 34,078
  • 10
  • 128
  • 141
  • When I try to test the code, I get an error that says, "The type ChangeListener is not generic; it cannot be parameterized with arguments ". Could that be a problem with my version of Java? – Disco Globeulon Jun 29 '12 at 18:53
  • 1
    This is an import problem in your program not a version problem with Java. Import `javafx.concurrent.Worker.State` rather than `Thread.State`. – jewelsea Jun 29 '12 at 20:32
-2

No. The DOM is part of a browser and you don't have a browser.

Michael Lorton
  • 43,060
  • 26
  • 103
  • 144