Using SPA (Single page application) and browser back button

2

Does anyone who works with SPA know the best way to work with the browser back button?

For example, we have a list of users and the detail of these users through a click. As we are on the "page" of detail of some user we need that, when clicking the return button of the navigator, return to the list of users.

    
asked by anonymous 02.06.2014 / 16:56

1 answer

4

There are two ways to do this:

Hash Links

Is given by the use of hash links, such as www.meusite.com#conteudo . Since conteudo changes every transition you want to be returnable. For example, you would have site.com#listagem and when you click it you should change to site.com#detalhamentoItem=15 . This technique takes advantage of the fact that everything after the '#' is considered anchor and does not cause a page reload.

Pros

  • The pro of this method is compatibility since it has been in use since the 1990s.
  • Works fine for pages that are written purely in js (without backend).

Cons

  • "Ugly" links;
  • Watching the hash change can be extremely tiring on older browsers (and ignoring them ends with your advantage). However there are dozens of libraries that do this dirty work for you. Personally, I like the link and used it on some projects.

HTML5 history API

Newer method that allows full control of the url. See more at link

Pros

  • Perfect when your server can generate a page as site.com?detalhamento=15 or site.com/detalhamento/15 , but it can also serve the result via AJAX (which saves bandwidth). So you have the speed of ajax without losing navigation by history;
  • Full control of url that will be as beautiful as your server and your creativity will allow.

Against

  • Using this method is almost impossible without a serverside language;
  • Is html5. Say goodbye to compatibility.
02.06.2014 / 20:55