🚨 Time is Running Out: Reserve Your Spot in the Lucky Draw & Claim Rewards! START NOW

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() 
}
DataCamp
Pros
  • Easy to use with a learn-by-doing approach
  • Offers quality content
  • Gamified in-browser coding experience
  • The price matches the quality
  • Suitable for learners ranging from beginner to advanced
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable
Udacity
Pros
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
Main Features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid Certificates of completion
Udemy
Pros
  • Easy to navigate
  • No technical issues
  • Seems to care about its users
Main Features
  • Huge variety of courses
  • 30-day refund policy
  • Free certificates of completion

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.