Edit Template
  • Home
  • /
  • JS History Object
Edit Template
  • Home
  • /
  • JS History Object

JavaScript History Object

The history object in JavaScript is a part of the browser’s window object. It helps you navigate through the user’s browser session — just like using the forward and back buttons manually, but through code.

This is especially useful in Single Page Applications (SPAs), where you want to change the URL or move between views without refreshing the page.

Checking the Length of History

You can find out how many pages are stored in the browser’s session history:

				
					console.log(history.length);
// Example Output: 3 (means user has visited 3 pages in the session)

				
			

Navigate Back and Forward

Use these to go back or forward one page:

				
					history.back();     // Go back one step
history.forward();  // Go forward one step


				
			

Note: These only work if there’s history to navigate through.

Go to a Specific Step in History

Use history.go() to move to a specific position:

				
					history.go(-2);  // Go back 2 steps
history.go(1);   // Go forward 1 step

				
			

Changing the URL Without Reload

You can add a new entry to the browser history without refreshing the page:

				
					history.pushState({page: "about"}, "About Page", "/about");


				
			
  • state: Any JavaScript object you want to associate.

  • title: Usually ignored by browsers.

  • url: The new URL to display (must be from the same domain).

Use Case: Changing the URL when a user clicks a button in a single-page site.

Replace Current History Entry

Instead of adding a new entry, you can replace the current one:

				
					history.replaceState({page: "contact"}, "Contact Page", "/contact");

				
			

This is useful when you want to update the URL without letting the user go back to the previous version.

Listening to History Changes

When the user navigates through the history, you can react to it:

				
					window.onpopstate = function(event) {
  console.log("Location changed:", document.location.pathname);
  console.log("State object:", event.state);
};

				
			

Conclusion

FeatureDescriptionExample
history.lengthNumber of entries in historyhistory.length
history.back()Go to previous pagehistory.back()
history.forward()Go to next pagehistory.forward()
history.go(n)Jump to specific history stephistory.go(-1)
pushState()Add a new URL to the history stackhistory.pushState(..., ..., "/about")
replaceState()Replace current entry in the historyhistory.replaceState(..., ..., "/home")
onpopstateHandle back/forward button clickswindow.onpopstate = function(e) { ... }
Scroll to Top