Back button handling in Single Page Apps?

J Evans picture J Evans · Dec 20, 2014 · Viewed 8k times · Source

A similar question here has been noted!

I've got an SPA based exclusively on the DHTMLX toolkit (fabulous stuff incidentally). One serious UX problem is with back button handling: there is none.

Their forum recommended 'any js routing library to handle state of the app in the url hash and restore it back'.

I am confused by this as the SPA has only the simplest HTML, is exclusively Javascript and does most communicating via WebSockets ... does this mean I have to store state on each button click/keypress?

So, ...

  1. Does the panel have any recommendations on best practices?
  2. Is there an existing library that will do this?
  3. If said library is light on examples, can anyone provide a basic how-to?

Many thanks

Answer

Brian McGinity picture Brian McGinity · Jan 16, 2015

Dhtmlx is a great framework for building SPAs. Like all SPAs, the back button will simply take the user right out of app. Also the user cannot bookmark anything.

So what you want to do is use javascript's pushState() which will allow you to control the url.

For example, suppose you show a search screen to go to a record. The user enters the search criteria and presses search. You bring in the results via ajax and update a grid. Then the user selects the row and you go to a detail page (typical search functionality here).

At this point, you would want to use pushState() to change the url to something like:
http:/me.com/search/23432

This will allow the user to bookmark the page. Then when the user leaves the detail page, use pushState() and set the url to http:/me.com/search

So you have complete control over the url.

The next thing you need to learn is popState(). This function is called when the url changes. So suppose the user pushes the bookmark to go to "23432". popState() will be called and you'll react accordingly.

That's basically it in a nutshell: pushState() and popState().

Some older browsers do not react to pushState/popState. There are libraries floating around to handle older browsers using url hashing. I am not too familiar with them as I am only supporting html5 browsers.