I'm using both JavaFX and the javascript engine inside JavaFX WebEngine to develop an application. I'd like to get feedback from javascript for debugging purposes. What happens to the console output inside the WebEngine? Is there any way I can access it, or redirect to System.out in java?
The following code redirects console.log()
to JavaBridge.log()
:
import netscape.javascript.JSObject;
[...]
public class JavaBridge
{
public void log(String text)
{
System.out.println(text);
}
}
// Maintain a strong reference to prevent garbage collection:
// https://bugs.openjdk.java.net/browse/JDK-8154127
private final JavaBridge bridge = new JavaBridge();
[...]
webEngine.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) ->
{
JSObject window = (JSObject) webEngine.executeScript("window");
window.setMember("java", bridge);
webEngine.executeScript("console.log = function(message)\n" +
"{\n" +
" java.log(message);\n" +
"};");
});