Enjoy 20% off all plans by following us on social media. Check out other promotions!
Quiz Questions

How do you use `window.history` API?

Topics
JAVASCRIPT
Edit on GitHub

TL;DR

The window.history API allows you to manipulate the browser's session history. You can use history.pushState() to add a new entry to the history stack, history.replaceState() to modify the current entry, and history.back(), history.forward(), and history.go() to navigate through the history. For example, history.pushState({page: 1}, "title 1", "?page=1") adds a new entry to the history.


Using the window.history API

The window.history API provides methods to interact with the browser's history stack. This can be useful for single-page applications (SPAs) where you want to manage the URL and browser history without causing a full page reload.

Methods

history.pushState()

This method adds a new entry to the history stack.

history.pushState({ page: 1 }, 'title 1', '?page=1');
  • The first parameter is a state object associated with the new history entry.
  • The second parameter is the title of the new history entry (currently ignored by most browsers).
  • The third parameter is the URL to be displayed in the address bar.

history.replaceState()

This method modifies the current history entry.

history.replaceState({ page: 2 }, 'title 2', '?page=2');
  • The parameters are the same as pushState(), but this method replaces the current entry instead of adding a new one.

history.back()

This method moves the user back one entry in the history stack, similar to clicking the browser's back button.

history.back();

history.forward()

This method moves the user forward one entry in the history stack, similar to clicking the browser's forward button.

history.forward();

history.go()

This method moves the user a specified number of entries in the history stack.

// Move back one entry
history.go(-1);
// Move forward one entry
history.go(1);
// Reload the current page
history.go(0);

Example

Here's a simple example demonstrating the use of pushState and replaceState:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>History API Example</title>
</head>
<body>
<button id="pushStateBtn">Push State</button>
<button id="replaceStateBtn">Replace State</button>
<button id="backBtn">Back</button>
<button id="forwardBtn">Forward</button>
<script>
document.getElementById('pushStateBtn').addEventListener('click', () => {
history.pushState({ page: 1 }, 'title 1', '?page=1');
});
document
.getElementById('replaceStateBtn')
.addEventListener('click', () => {
history.replaceState({ page: 2 }, 'title 2', '?page=2');
});
document.getElementById('backBtn').addEventListener('click', () => {
history.back();
});
document.getElementById('forwardBtn').addEventListener('click', () => {
history.forward();
});
</script>
</body>
</html>

Further reading

Edit on GitHub