Push pop and replace state

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the javascript category.

Last Updated: 2024-11-23

PushState

Using the browser’s history.pushState function, we can add a new entry as the "current" entry of the history list.

Specifics:

Function Signature

history.pushState(state, title, url);
// - The first parameter -- the (optional) `state` object -- is pushed into the state stack and will be available during the `popstate` event handler. Feel free to set this to null if you prefer.
// - The `title` param is often null because it is not used by browsers at time of writing
// - The `url` URL doesn't need to exist in the backend.
window.history.pushState({ threadId: 2, pageLoad }, '', url);

// basic version
history.pushState(null, null, '/other-page');

You will often w

BTW if you want to go to a new page and refreh (normal navigation), just do:

window.location='/new-page

ReplaceState

// Change URL in browser to another page but does not trigger a page refresh OR add something new to the history list. I.e. overrides current history entry
window.history.replaceState({ threadId: 3 , pageLoad }, '', url);

Replace

Note that this is on location, not history

// Change URL in browser to another page but does not trigger a page refresh OR add something to the
// This causes the page to change to `url` and for the back
// button to forget about the current back and instead bring up to the
// back _before_ the current page
window.location.replace(url);

PopState

// This gets called when you press back
window.addEventListener('popstate', (event) => {
  // Maybe you'll need to do something special if it is none
  if (! event.state) {
    return
  }

  const { threadId, pageLoad }  = event.state
  updatePage(my, Vars)
}