Cyber Week

Save big!

All courses under $5 - for a limited time!

Code has been added to clipboard!

Best Way of Using JavaScript Back and Forward Methods for Browsers

Reading time 2 min
Published Aug 8, 2017
Updated Oct 15, 2019

DOM is a part of the browser window object (BOM). BOM allows JavaScript to communicate with the browser. It has several components you can access: history, location, navigator, screen and document. In this tutorial, you will learn all about BOM history component.

This tutorial explains the JavaScript back and forward methods used to access and store URLs of the previous and next pages a user visits. These methods are similar to Forward and Back buttons in your browser.

JavaScript window.history: Main Tips

  • The window history object holds information about internet browsers history.
  • The window prefix is not necessary when using the object.
  • There are restrictions when using JavaScript window history object to protect the user's privacy.
  • JavaScript window history contains JavaScript back and forward methods.
  • The window.history pushstate method can be used to create and activate new history entries.

Going Back

The JavaScript history back method finds the URL of the previous page and loads it. Basically, JavaScript back method does the exact same function as pressing the browsers BACK button. Let's see an example on how to use history.back() correctly:

Example
function goPrev(){ 
   window.history.back() 
}

Moving Forward

The history.forward() method finds the URL of the next page in history and loads it. In other words, it performs the exact same function as pressing the browsers FORWARD button:

Example
function pageForward() {     
   window.history.forward()    
}

JavaScript window.history: Summary

  • window.history contains information about the browsers history.
  • JavaScript back and forward methods can be used to get URLs of the previous and next pages visited by the user.
  • To make a new history entry manually and activate it, you can use the window.history pushstate method.