0

As I stated in the title, is it possible to run WebEngine in another thread than FX Application Thread?

Code:

...
WebEngine webEngine = new WebEngine();

Thread thread = new Thread(() -> 
    webEngine.load("https://www.google.com"));
thread.setDaemon(true);
thread.start();
...

Exception:

Exception in thread "Thread-6" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-6
    at com.sun.javafx.tk.Toolkit.checkFxUserThread(Toolkit.java:279)
    at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(QuantumToolkit.java:423)
    at javafx.scene.web.WebEngine.checkThread(WebEngine.java:1243)
    at javafx.scene.web.WebEngine.load(WebEngine.java:913)
    at sample.Main.lambda$start$0(Main.java:44)
    at java.lang.Thread.run(Thread.java:748)
Mert Akozcan
  • 163
  • 1
  • 10
  • 1
    You already got your answer yourself... it seems? Anyways, `WebEngine::load()` is asynchronous, though you must call from JavaFX Application Thread. – Jai Jun 08 '18 at 09:20
  • 1
    Do you want to tell us why you want to do that? Afaik the web engine starts another thread for loading stuff, anyway. – Jan B. Jun 08 '18 at 09:22
  • In my application, when a user clicks something for example, application is supposed to redirect user to a website and execute some JS code on browser based on user's input. What I wanted is keeping WebEngine already loaded on the backgroud and when user clicks, show browser and execute JS code. Obviously, this would be much faster. – Mert Akozcan Jun 08 '18 at 09:41
  • @MertAkozcan just call it from the fx application thread, load the page and only add it to the scene when the user clicks – Selim Jun 10 '18 at 12:16
  • Loading in "another thread" does not solve this problem at all. Loading a web page *is slow*, there is no magic to make it load instantly. The only way is to anticipate the need to load a webpage, and pre-load it way before you need it. You can always not show the `WebView` until you need to show it. Yes, this method is going to cost you memory and processing if you make a wrong "guess." – Jai Jun 11 '18 at 01:09

1 Answers1

1

Regarding the Oracle documentation it's not possible.

WebEngine objects must be created and accessed solely from the JavaFX Application thread. This rule also applies to any DOM and JavaScript objects obtained from the WebEngine object.

Jan B.
  • 6,030
  • 5
  • 32
  • 53