History API

The History API allows you to access the browser navigation history from the server-side. The history is always bound to the current browser window / frame, so you can access it through the Page object (available through the UI).

Java

  1. History history = UI.getCurrent().getPage().getHistory();

Traversing History

With the methods forward(), back() and go(int) you can programmatically traverse the browser’s history entries. The methods correspond to the user actions on the browser’s back and forward buttons.

Java

  1. history.back(); // navigates back to the previous entry
  2. history.forward(); // navigates forward to the next entry
  3. history.go(-2); // navigates back two entries
  4. history.go(1); // equal to history.forward();
  5. history.go(0); // will reload the current page
Note
Triggering the forward, back and go methods will asynchronously trigger a HistoryStateChangeEvent if the history entries are for the same document, e.g. the entries share the same origin.

Handling user navigation

If you want to manually handle navigation events you can replace it by setting a handler for navigation events using the history.setHistoryStateChangeHandler(HistoryStateChangeHandler). It will be notified when:

  • the user navigates back or forward using the browser buttons

  • the navigation was done programmatically from server-side java code or client-side JavaScript

  • the user clicks a link marked with the router-link attribute

Java

  1. history.setHistoryStateChangeHandler(this::onHistoryStateChange);
  2. private void onHistoryStateChange(HistoryStateChangeEvent event) {
  3. // site base url is www.abc.com/
  4. // user navigates back from abc.com/dashboard to abc.com/home
  5. event.getLocation().getPath(); // returns "home"
  6. }
Note
The server side history state change event is not fired if only the hash has changed. Hash is always stripped from the location sent to server. Hash is a browser feature not intended for use on the server side.

Changing history

You can update the history by either pushing new entries to the history, or by replacing the current entry. You may optionally provide a json value as the state parameter. This state value will be available via LocationChangeEvent:getState() when the entry is being revisited the next time.

Java

  1. // adds a new history entry for location "home", no state
  2. history.pushState(null, "home");
  3. // replaces the current entry with location "about" and a state object
  4. JsonValue state = Json.create("preview-mode");
  5. history.replaceState(state, "about");
Note
The url used with pushState and replaceState must be for the same origin as the current url; otherwise browser will throw an exception and the history is not updated.
Note
If you use either pushState or replaceState, the framework internal scroll position restoration on navigation won’t work, since it stores data in the history.state to keep track of the scroll positions.