When a blank page (i.e. about:blank) is loaded in a WebView by its WebEngine, the WebHistory doesn't add that Entry. That information is relevant for properly implementing back and forward buttons (similar to current browsers).
One possible solution would be to add an Entry to WebHistory, but that's not allowed.
If that behavior is intentional, how can you implement back and forward buttons considering blank pages without creating your own history List?
Here is a minimal example that reproduces the issue:
import java.util.List;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.control.Button;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebHistory;
import javafx.scene.web.WebView;
import javafx.concurrent.Worker;
public class App extends Application {
private WebView webView;
private WebEngine webEngine;
private WebHistory webHistory;
@Override
public void start(Stage stage) throws Exception {
webView = new WebView();
webEngine = webView.getEngine();
webHistory = webEngine.getHistory();
webEngine.getLoadWorker().stateProperty().addListener((obs, oldVal, newVal) -> {
if (Worker.State.SUCCEEDED.equals(newVal)) {
print();
}
});
Button button1 = new Button("Google");
Button button2 = new Button("Stack Overflow");
Button button3 = new Button("Empty");
button1.setOnAction(e -> webEngine.load("http://www.google.com"));
button2.setOnAction(e -> webEngine.load("http://www.stackoverflow.com"));
button3.setOnAction(e -> webEngine.load(""));
HBox buttons = new HBox(10, button1, button2, button3);
VBox root = new VBox(10, buttons, webView);
stage.setScene(new Scene(root));
stage.show();
}
private List<String> history() {
return webHistory.getEntries().stream().map(WebHistory.Entry::getUrl).toList();
}
private void print() {
System.out.println("Location: " + webEngine.getLocation());
System.out.println("Current index: " + webHistory.getCurrentIndex());
System.out.println("History: " + history() + System.lineSeparator());
}
public static void main(String[] args) {
launch();
}
}
In this example, if you press the buttons from left to right, you get:
Location: https://www.google.com/?gws_rd=ssl
Current index: 0
History: [https://www.google.com/?gws_rd=ssl]
Location: https://stackoverflow.com/
Current index: 1
History: [https://www.google.com/?gws_rd=ssl, https://stackoverflow.com/]
Location: about:blank
Current index: 1
History: [https://www.google.com/?gws_rd=ssl, https://stackoverflow.com/]
Instead, I would expect the last entry to be:
Location: about:blank
Current index: 2
History: [https://www.google.com/?gws_rd=ssl, https://stackoverflow.com/, about:blank]