14

What I'm trying to implement is essentially the cancel button of a browser but using JavaFX's webview. This is the code I have so far:

Worker<Void> loadWorker = webView.getEngine().getLoadWorker();
if (loadWorker != null) {
    Platform.runLater(() -> loadWorker.cancel());
}

but it sometimes work and sometimes doesn't.

What's the proper way of canceling the webview/webengine task of loading a page?

Naman
  • 27,789
  • 26
  • 218
  • 353
Pablo Fernandez
  • 279,434
  • 135
  • 377
  • 622

3 Answers3

2

After canceling the webEngine task, can you try with setting the content of the webEngine to null :

webView.getEngine().load(null);
Naman
  • 27,789
  • 26
  • 218
  • 353
Priyanka
  • 115
  • 2
2

The table in the WebEngine states the JavaScript user interface methods and properties with their corresponding WebEngine callbacks.

Where window.close() corresponds to the onVisibilityChanged callback of the WebEngine.


A quick way to try out, in that case, could be :

webEngine.getOnVisibilityChanged().handle(closeWindowEvent); //event definition below

followed by a

webEngine.executeScript("window.close()");

Another way in which you make sure the window is closed is to define an event which could be dispatched by the WebView's EventDispatcher for the current node.

// Here the event to be dispatched for closing the window shall be 
WebEvent<Boolean> closeWindowEvent = new WebEvent<>(webEngine, VISIBILITY_CHANGED, Boolean.FALSE);

webView.getEventDispatcher().dispatchEvent(closeWindowEvent, null); // no further events

In case of trying to cancel loading the web page only, you can make use of the executeScript to do:

webEngine.executeScript("window.stop()");
Naman
  • 27,789
  • 26
  • 218
  • 353
0
webView.getEngine().getLoadWorker().cancel()

is your boy

Sahib Khan
  • 557
  • 4
  • 19