Dom Christie

Today I Learned

I have been experimenting with the History API, working out a way to determine the direction of a popstate event. popstate is dispatched when navigating Back and Forward, and there’s no direction information in the event. However, reading Astro’s View Transition code, I noticed that Matthew Phillips had implemented this by storing an index in the History state, and keeping track of the current index on history.pushState. The direction can be then determined by comparing the current index with the index from the popstate event.

What was most surprising was the following:

if (history.state) {
  // we reloaded a page with history state
  // (e.g. history navigation from non-transition page or browser reload)
  // …

It turns out that the History state is persisted between page refreshes:

history.state // null
history.pushState({ index: 1 }, null)
history.state.index // 1
history.state.index // 1