#677 Browser History

medium
typescript
browser-api
history
data-structure

Every browser tab keeps a list of the pages you opened in it. The back and forward buttons walk along that list, and opening a new link from the middle of the list throws away everything ahead of you. Build a small model of that list: a BrowserHistory class.

const history = new BrowserHistory("home");

history.visit("docs");
history.visit("blog");
history.current;        // "blog"
history.length;         // 3

history.back();         // "docs"
history.back();         // "home"
history.back();         // "home"   (already at the first entry)
history.forward(5);     // "blog"   (stops at the last entry)

history.go(-1);         // "docs"
history.visit("about"); // "blog" is gone now
history.length;         // 3        (home, docs, about)
history.canGoForward;   // false

history.replace("contact");
history.current;        // "contact"
history.length;         // 3        (replace does not add an entry)

API

  • new BrowserHistory(initialUrl?) starts with one entry. If no url is given, use "about:blank".
  • current is the url of the entry you are on.
  • length is the number of entries in the list.
  • canGoBack / canGoForward say whether there is an entry before or after the current one.
  • visit(url) removes every entry after the current one, adds url at the end, and moves to it. Visiting the same url as the current one still adds an entry.
  • replace(url) changes the url of the current entry in place. Entries before and after it stay.
  • back(steps = 1) and forward(steps = 1) move by that many entries and return the new current.
  • go(delta) moves by a signed number of entries (go(-2) is two steps back, go(0) stays) and returns the new current.
  • Moves never go past the first or last entry. They stop at the end instead.

Follow-up: the real window.history does not let a page read the urls of other entries. Why do you think browsers hide them, and what does history.pushState add on top of this model?