Web History Api in JavaScript
The Web History API in JavaScript allows you to manipulate the browser's session history — enabling forward and backward navigation without full page reloads.
? Core History API Methods
1. history.pushState(stateObj, title, url)
Adds a new entry to the browser's history stack without reloading the page.
history.pushState({ page: 1 }, "Title 1", "/page1");2. history.replaceState(stateObj, title, url)
Replaces the current history entry (instead of adding a new one).
history.replaceState({ page: 1 }, "Title 1", "/page1");3. window.onpopstate
Fires when the active history entry changes (e.g., via back/forward buttons).
window.onpopstate = function(event) { console.log("location: " + document.location + ", state: ", event.state);};? stateObj
An object associated with the history entry (you define it). It can be accessed via event.state.
? Example
<button id="goPage2">Go to Page 2</button><script> document.getElementById('goPage2').addEventListener('click', function () { history.pushState({ page: 2 }, "Page 2", "/page2"); document.body.innerHTML = "<h1>This is Page 2</h1>"; }); window.onpopstate = function(event) { if (event.state && event.state.page === 2) { document.body.innerHTML = "<h1>This is Page 2</h1>"; } else { document.body.innerHTML = "<h1>Home Page</h1>"; } };</script>?? Notes
Does not reload the page.
Works best in single-page applications (SPAs).
Only URLs within the same origin can be used.
Let me know if you want to integrate this into a React or Vue app, or want deep-linking examples!