How do you cancel a webview loading a web site?
Asked Answered
R

3

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?

Remembrance answered 27/9, 2017 at 17:47 Comment(0)
Y
2

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

webView.getEngine().load(null);
Yang answered 29/9, 2017 at 1:32 Comment(0)
H
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()");
Holms answered 1/10, 2017 at 12:25 Comment(2)
I'm not trying to close a Window, just cancelling the loading of a web page.Remembrance
@Pablo window.stop() shall help you there in that case...?Holms
C
0
webView.getEngine().getLoadWorker().cancel()

is your boy

Chlamys answered 6/10, 2017 at 12:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.