CodesCompiler
πŸ”
HTMLCSSJavaScriptPythonSQLPHPSEOPostsBooksKids About Contact πŸš€ Get Started Free

JavaScript - History Object

JavaScript - History Object

Window History Object

In JavaScript, the window β€˜history’ object contains information about the browser’s session history. It contains the array of visited URLs in the current session.

The β€˜history’ object is a property of the β€˜window’ object. The history property can be accessed with or without referencing its owner object, i.e., window object.

Using the β€˜history’ object’s method, you can go to the browser’s session’s previous, following, or particular URL.

History Object Methods

The window history object provides useful methods that allow us to navigate back and forth in the history list.

Follow the syntax below to use the β€˜history’ object in JavaScript.

JAVASCRIPT CODE
window.history.methodName();
OR
history.methodName();

You may use the β€˜window’ object to access the β€˜history’ object.

JavaScript History back() Method

The JavaScript back() method of the history object loads the previous URL in the history list.

Syntax

Follow the syntax below to use the history back() method.

JAVASCRIPT CODE
history.back();

Example

In the below code’s output, you can click the β€˜go back’ button to go to the previous URL. It works as a back button of the browser.

Preview

JavaScript History forward() Method

The forward() method of the history object takes you to the next URL.

Syntax

Follow the syntax below to use the forward() method.

JAVASCRIPT CODE
history.forward();

Example

In the below code, click the button to go to the next URL. It works as the forward button of the browser.

Preview

JavaScript History go() Method

The go() method of the history object takes you to the specific URL of the browser’s session.

Syntax

Follow the syntax below to use the go() method.

JAVASCRIPT CODE
history.go(count);

In the above syntax, β€˜count’ is a numeric value representing which page you want to visit.

Example

In the below code, we use the go() method to move to the 2nd previous page from the current web page.

Preview

Example

In the below code, we use the go() method to move to the 2nd previous page from the current web page.

Preview

Following is the complete window history object reference including both properties and methods βˆ’

History Object Property List

The history object contains only the β€˜length’ property.

PropertyDescriptionlengthIt returns the object’s length, representing the number of URLS present in the object.

History Object Methods List

The history object contains the below 3 methods.

MethodDescriptionback()It takes you to the previous web page.forward()It takes you to the next web page.go()It can take you to a specific web page.