0
0
JavascriptHow-ToBeginner · 3 min read

How to Go Back in Browser History Using JavaScript

To go back in browser history using JavaScript, use the window.history.back() method. This tells the browser to load the previous page in the history stack, just like clicking the back button.
📐

Syntax

The main method to go back in browser history is window.history.back(). It takes no arguments and returns no value.

  • window: The global browser object.
  • history: The object that manages the session history.
  • back(): The method that moves the browser one step back in history.
javascript
window.history.back();
💻

Example

This example shows a button that, when clicked, takes the user back to the previous page in their browser history.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Go Back Example</title>
</head>
<body>
  <button id="backBtn">Go Back</button>
  <script>
    const backBtn = document.getElementById('backBtn');
    backBtn.addEventListener('click', () => {
      window.history.back();
    });
  </script>
</body>
</html>
Output
When the user clicks the 'Go Back' button, the browser navigates to the previous page in history.
⚠️

Common Pitfalls

Sometimes window.history.back() does nothing if there is no previous page in the history stack (for example, if the user opened the page directly). Another mistake is calling history.back() without the window prefix in some strict environments, though usually it works.

Also, calling history.go(-1) is an alternative that does the same thing.

javascript
/* Wrong: Assuming back() always works */
window.history.back(); // May do nothing if no history

/* Right: Check history length before going back */
if (window.history.length > 1) {
  window.history.back();
} else {
  console.log('No previous page in history');
}
📊

Quick Reference

MethodDescription
window.history.back()Go back one page in history
window.history.forward()Go forward one page in history
window.history.go(-1)Go back one page (alternative)
window.history.go(1)Go forward one page (alternative)

Key Takeaways

Use window.history.back() to go back one page in browser history.
If no previous page exists, back() will not change the page.
Check window.history.length to avoid errors when going back.
You can also use window.history.go(-1) as an alternative.
Always test navigation behavior in your app to ensure expected results.