Hurray! Vaadin 8 has finally been released and comes up with a bunch of new features. Maybe the most important one is a new data binding concept. But the feature I’m discussing here is support for the HTML5 History API.
This API enables developers to alter a website’s URL without a page refresh. Why is this important in connection to Vaadin? Vaadin is a single page application. Thus, although you can display different views, you are technically on the same page. Per se, this prohibits normal browser navigation (back-button and bookmark-able deep links).
You are probably familiar with Vaadin’s Navigator class and might say: “Well, Vaadin has solved this problem with page fragments!”. You are right. But what if you could hide those fragments and go from this
http://localhost/app-context#!page1/optionalParameter
to this
http://localhost/app-context/page1/optionalParameter
so your URL looks even prettier?
The HTML5 History API support in Vaadin 8 so far is on a quite low level. The Page object was augmented with a function called pushState(String), which triggers a call on the browser, namely window.history.pushState(..). Unfortunately, there is no out-of-the box support to use that API together with Vaadin’s Navigator.
Luckily, I’ve already written an add-on that makes it super easy to use the Navigator with the History API. The HistoryApiNavigationStateManager Add-on presents you with a Navigator factory class that you can use instead of the Navigator constructor. The factory provides the Navigator with a special NavigationStateManager which maps navigation states (consisting of view name and parameters) to the address parts you see in the URL and alters the URL accordingly.
So instead of creating your Navigator like this
Navigator navigator = new Navigator(ui, panel);
you can use the add-on’s factory and get a Navigator that is capable of pushing URL states
Navigator navigator = HistoryApiNavigatorFactory.createHistoryApiNavigator(ui, panel);
The factory creates a Navigator object with the HistoryApiNavigationStateManager instead of Vaadin’s UriFragmentManager. The HistoryApiNavigationStateManager maps the navigation states to page addresses and calls the Page object’s pushState function. So navigation state page1/param1 becomes /app-context/main/page1/param1 and gets pushed to the browser’s address bar by
page.pushState("/app-context/main/page1/param1");
There is one little issue you have to have in mind: When using empty context roots and an empty view name you cannot have parameters for that view. http://localhost:8080//parameter cannot be pushed because of the double slashes (try window.history.pushState({}, “”, “//param”); in your browser console to see what I mean) and http://localhost:8080/parameter is handled as if parameter is a view name.
Now check out the add-on yourself and go to HistoryApiNavigationStateManager Add-on!
And feel free to add your ratings and comments on the page.
Filed under: All Tagged: Java, vaadin, web application
