Devlog

HTML5 history

For a web application I am developing (Courser) I need to control the history. The application can run in a browser but also as a “standalone” web app in Chrome and Safari. As a standalone app you have no navigation buttons, but I wanted to make the Android Back button work like expected and the only way to do is, is to handle the popstate event. When a user pushed the back button, a popstate event fires as long as there are entries in the history. When there is no entry anymore, the back button push will close the app. These are some of the things I learned while implementing this.

  • The popstate event fires when a user pushes the back of forward button and there is a entry in the history to navigate to. For example, if a user pushes the forward button but you already are on the last entry, nothing happens (no popstate event).
  • The push on a back or forward button can be simulated with history.back(), history.forward() and history.go(). The history.go() expects a number as argument that indidates how many entries you want to go back or forward. For example history.go(-2) tries to go 2 entries back. When this happens, still only 1 popstate event is fired.
  • From within the popstate event, you cannot tell if it caused by forward or back navigation.
  • The history.pushState() method adds one entry after the current entry and activates this new entry and also removes all other entries after it so it will be the last and no forward navigation is possible.
  • The history.replaceState() method replaces the current entry in the history.
  • Both history.pushState() and history.replaceState() do not fire a popstate event.
  • The history.length displays the number of entries in the history – this can be internal and external entries.
  • The history.pushState() and history.replaceState() both expect at least 2 parameters:
    • A state object – will be copied to the history and can be get back by calling history.state. This way you can save data with every history entry and act upon. For exampe: history.pushState({id : 3}, “”) will add an entry when later you get back to this entry, you can call history.state and get back {id : 3}.
    • name – is not used at this point
    • URL – this will be refelected in the URL bar