javafx WebView and WebEngine Get the page history of a WebView

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

WebHistory history = webView.getEngine().getHistory();

The history is basically a list of entries. Each entry represents a visited page and it provides access to relevant page info, such as URL, title, and the date the page was last visited.

The list can be obtained by using the getEntries() method. The history and the corresponding list of entries change as WebEngine navigates across the web. The list may expand or shrink depending on browser actions. These changes can be listened to by the ObservableList API that the list exposes.

The index of the history entry associated with the currently visited page is represented by the currentIndexProperty(). The current index can be used to navigate to any entry in the history by using the go(int) method. The maxSizeProperty() sets the maximum history size, which is the size of the history list

Below is an example of how to obtain and process the List of Web History Items.

A ComboBox (comboBox) is used to store the history items. By using a ListChangeListener on the WebHistory the ComboBox gets updated to the current WebHistory. On the ComboBox is an EventHandler which redirects to the selected page.

final WebHistory history = webEngine.getHistory();

comboBox.setItems(history.getEntries());
comboBox.setPrefWidth(60);
comboBox.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent ev) {
        int offset =
                comboBox.getSelectionModel().getSelectedIndex()
                - history.getCurrentIndex();
        history.go(offset);
    }
});

history.currentIndexProperty().addListener(new ChangeListener<Number>() {

    @Override
    public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
        // update currently selected combobox item
        comboBox.getSelectionModel().select(newValue.intValue());
    }
});

// set converter for value shown in the combobox:
//   display the urls
comboBox.setConverter(new StringConverter<WebHistory.Entry>() {

    @Override
    public String toString(WebHistory.Entry object) {
        return object == null ? null : object.getUrl();
    }

    @Override
    public WebHistory.Entry fromString(String string) {
        throw new UnsupportedOperationException();
    }
});


Got any javafx Question?