Course contentsShow
← Web Development
Lesson 969 of 2,98217. URL and History ManagementFree lesson

Programmatic Navigation: history.back() and history.forward()

Triggering browser navigation through JavaScript instead of user clicks.

Programmatic Navigation: history.back() and history.forward()

You'll learn how to programmatically trigger the browser's back and forward buttons from JavaScript.

The Core Idea

While users typically navigate using their browser's back/forward buttons, JavaScript lets you trigger these same actions programmatically. The History API provides history.back() and history.forward() methods that simulate clicking the browser's navigation buttons.

Think of it like having a remote control for the browser's navigation buttons. Instead of the user physically clicking back or forward, your code can press those buttons on their behalf.

The Methods

history.back() – Navigates to the previous page in the session history, equivalent to clicking the browser's back button.

history.forward() – Navigates to the next page in the session history (only if there is one), equivalent to clicking the forward button.

// Go back one page
history.back();

// Go forward one page (if available)
history.forward();

Common Use Cases

You might trigger these methods from custom UI elements, like a "Return to Previous Page" button in your application, or programmatically after certain user actions complete:

const backButton = document.querySelector('.custom-back');
backButton.addEventListener('click', () => {
  history.back();
});

Important Notes

These methods work asynchronously – they initiate navigation but don't wait for it to complete. The actual navigation follows the same rules as user-initiated navigation, including triggering popstate events you've learned about.

Also, history.forward() only works if there's actually a forward entry in the history stack (meaning the user previously went back).

Key Takeaway: history.back() and history.forward() let you programmatically trigger browser back/forward navigation, useful for custom navigation controls in your application.