Search code examples
javascriptbrowser-historyhtml5-history

Move "sideways" through browser pages without adding to browser history


  • At a book page, the user clicks Chapter 1 in the table of contents.
  • At the Chapter 1 page, the user clicks Next Chapter to go to Chapter 2.
  • The user may click Next Chapter any number of times to move through chapters.
  • At any chapter page, if the user clicks the Back button, the user should go back to the book page, not back to a previously viewed chapter page. In other words, movement through chapter pages is kind of "sideways" without adding to the browser history stack.

QUESTION:

What Javascript must be executed when Next Chapter is clicked to effectively remove the current chapter page from the browser history and then go to the new chapter page as so that the history stack looks as if the user had come to the new chapter page from the book page?

EFFORTS:

  • I've read a number of posts and have read the documentation, especially the Mozilla doc on manipulating the browser history.
  • I've tried calling history.back() (to pop the current entry) followed by proceeding to the next chapter, but the current chapter just stays in the history, so that I come back to it when I click the Back button.
  • I've tried history.replaceState(), but that doesn't seem to help.
  • It seems like what I need is something like history.popState() followed by proceeding to the next chapter.
  • I'm sure I'm just missing some simple, key ingredient.

Solution

  • Here's what I ended up doing, with thanks for inspiration from Limbo. The onclick event from a next or previous link calls this function:

    function sidewaysLink()
    {
        history.replaceState({}, "", this.getAttribute("href"));
        history.go(0);
        return false;
    }
    

    Not sure why it took me so much blundering to figure this out. The operation is simple: history.replaceState() replaces the entry at the top of the browser stack and history.go(0) goes to that top entry. The return false keeps the browser from acting on the link upon return.

    I don't know what the first parameter of history.replaceState() should be. It's identified as a "state object" (see https://developer.mozilla.org/en-US/docs/Web/API/History_API, which gives an example). I'm passing an empty object and it seems to work. The second parameter is identified as the "title", which the documentation says can safely be an empty string.

    Grateful to hear from anyone who sees a flaw in this approach or who can suggest improvement. Seems to work well.