History does two things. It lets you:
- Navigate to a specific page in the browser history
- Change the URL without a page refresh
Navigating a specific page in the browser history
You can use the following methods to navigate the history stack.
history.backโ goes backward one pagehistory.forwardโ goes forward one pagehistory.goโ goes to a specific page
history.back() // Goes back 1 pagehistory.forward() // Goes forward one pagehistory.go lets you navigate to a specific page in the browser history. It takes in an integer to determine which page to go.
- Negative numbers indicate the number of pages to go back.
- Positive numbers indicate the number of pages to go forward.
- 0 reloads the current page
history.go(-1) // Go back one pagehistory.go(2) // Go forward 2 pageshistory.go(0) // Reloads the pageIf you pass in a value thatโs out-of-bounds, history.go will fail silently and do nothing. An out-of-bounds value means the browser couldnโt find a page at the value you passed in.
Changing URL with History
You can change the URL with history.pushState and history.replaceState.
pushStateadds a new entry into the browser historyreplaceStateoverwrites the current entry in the browser history.
Both pushState and replaceState has the same syntax.
history.pushState(state, title, url)history.replaceState(state, title, url)stateletโs you define an object which you can retrieve on apopstateevent. (More onpopstatelater).titleis the title of the page to navigate to.urlis the URL you want to navigate to.
Hereโs an example where we have a button that changes the path from / to /hello.
const button = document.querySelector('button')
button.addEventListener('click', _ => { history.pushState({ value: 'hello world' }, 'Hello', '/hello')})Most browsers donโt respect the title attribute at the time of writing (February 2021), so we need still need to set the title with document.title.
The code looks like this:
history.pushState(state, title, url)document.title = titleNote: Chrome is a little weird. If you place document.title after history.pushState, the document title will only update after 1 second. This doesnโt happen on Safari and Firefox โ document title gets updated immediately. Iโd say itโs an inconsequential problem so we donโt have to worry too much about the order.
Popstate
The popstate event fires when the history is used to move the user forward or backwards to a page. There are two possible ways for this to happen
- The user clicks on the
backorforwardbutton - We use
history.back,history.forwardorhistory.go.
If you added a state object with history.pushState or history.replaceState, you can retrieve the object with the popstate event.
replaceStateadds thestateobject to the current pagepushStateadds thestateobject to the page youโre navigating to.
Hereโs an example. When a user clicks a button, we replace the current location with history.replaceState first. Then, we change the location with history.pushState.
const button = document.querySelector('button')
button.addEventListener('click', _ => { history.replaceState({ value: 'First Page' }, '', '/hello') history.pushState({ value: 'Second Page' }, '', '/second')})We can retrieve this state object in a popstate event.
window.addEventListener('popstate', event => { console.log(event.state)})When you navigate back to the first page via history, youโll see First Page. When you navigate back to the second page via history, youโll see Second Page.
Real world use-case for the state object?
The popstate event doesnโt occur when users navigate to the page with an URL. Since the popstate event doesnโt occur, we cannot reliably use the state object for any critical information on that page.
Twitter wrote about how they used the state object in an article in 2012 โ thatโs many years ago, so Iโm not sure whether itโs still current.
History and Servers
Try loading a page with the URL changed by history. You will most likely reach a page-not-found error. (A simple way to test this is refresh the page after a pushState)
This means we need to use a custom server thatโs able to manage these โhistoriedโ URLs. Otherwise, people navigating to our sites will reach pages that cannot be found.
Welcome! Unfortunately, you donโt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson