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)
" +
"{
" +
" java.log(message);
" +
"};");
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…