pushState vs popstate

This how-to shows examples and the differences between the pushState() method of the window history API and the window popstate event that fires.

Remember, these URLs (routers) that are updated with pushState and replaceState are non-existent. If you refresh the browser, you'll receive an error.

popstate event was fired

pushState without listening for the popstate event

If you click on the squares, the URL and history tab will change. However, if you click on the browser back or forward buttons, the popstate event will be fired, the URL will change, but the squares will not change size because they are not listening for a popstate event.

square 1
square 2
square 3

pushState with listening for the popstate event

If you click on the circles, the URL and history tab will change. As opposed to the squares, the circles will change size when you click on the browser back or forward buttons because they are listening for the popstate event.

circle 1
circle 2
circle 3
popstate event was fired

pushState vs replaceState

The main difference between the pushState and replaceState methods are that pushState adds an entry to the browser history, whereas replaceState doesn't. replaceState only updates the URL. View your browser history after clicking on replaceState.

Click to replaceState()