For JavaFX WebEngine, how do I get JavaScript error notification?

I am trying to run an SVG containing Javascript in a JavaFX WebView. I know that some of the scripts I'm trying to run have errors, and I'm trying to figure out how to print them to the console so that I can debug them. I tried the following, but WebErrorEvent is never called:

WebEngine webEngine = browser.getEngine(); webEngine.setOnError(new EventHandler<WebErrorEvent>() { @Override public void handle(WebErrorEvent event) { System.err.println(event); } }); 

Is this the right way to get JavaScript feedback using this control?

+5
source share
1 answer

setOnError listener only works if there is an error loading this document.

One way to solve this problem is to call the Java method when calling console.log . You can do it.

Your FX application

 WebEngine engine = mainWebView.getEngine(); engine.load("http://whereever.com"); engine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() { @Override public void changed(ObservableValue<? extends Worker.State> observable, Worker.State oldValue, Worker.State newValue) { JSObject window = (JSObject) engine.executeScript("window"); window.setMember("java", new Bridge()); engine.executeScript("console.log = function(message) { java.log(message); }"); // Now where ever console.log is called in your html you will get a log in Java console } }); 

Class your bridge

 public class Bridge { public void exit() { Platform.exit(); } public void log(String text) { System.out.println(text); } } 

Your html

 <h1>Text Page</h1> <button onclick="java.log('This is log')">Log</button> <button onclick="console.log('This produces the same result as above')">Console.log</button> <button onclick="java.exit()">Exit</button> 

Hope this helps.

0
source

All Articles