Sunday, November 1, 2020

Understanding popState and pushState of browser history

The pushState method and popState event can be used to manage browser history when user clicks browser's back and forward button. Although the way to use those methods are not very straight forward.

When a browser visits a url, that url showing on the browser address bar is the current state. If user clicks back button, or call history.back(), the browser will load the previous url of the browser.

If application calls history.pushState(newStateObj, title, url, param), then the current state and url shown in the address bar will be pushed into the browser history, and then the url and state parameters in the pushState call becomes the current state and url, the new url will also show on the browser address bar. However, the browser will not actually load the new url set by pushState method.

When user clicks back button, the popState event is triggered, the last state and url before the current state and url (the url showing on browser before history.pushState method is called) is loaded in the browser, however, the page content will not change, and the application must update the page content by implementing the logic in popState event handler.