Open In App

How to navigate between web pages using javascript history API ?

Last Updated : 18 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we’ll look at how to use history API to navigate between pages. We use History API to navigate programmatically between web pages. 

History API provides us with a way to access the browser’s session history. It exposes useful methods and properties that let you navigate back and forth through the user’s history, and manipulate the contents of the history stack.

Methods in History API:

1.  window.history.back: This is the same as clicking the back button of the browser.

Syntax:

window.history.back()

2. window.history.forward: This is the same as clicking the forward button.

Syntax:

window.history.forward()

3. window.history.go: This can be used to jump to another page specified as a number. The current page is represented by the number 0. So, the negative number is any page before and the positive number is the page after.

Syntax:

window.history.go(number)

Example 1: Now, let’s implement the above-given methods to navigate between pages. We have two HTML files here and we are able to move between these files using back-and-forward methods.

  • Create two files with name base.html and app.html and paste the below codes
  • Click on the link first
  • Click on the buttons to navigate

base.html

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>NAVIGATION</title>
</head>
  
<body>
    <h1 style="color:green">
        From GEEKS FOR GEEKS to HELLO WORLD
    </h1>
    <a href="file:///E:/codes/app.htm">link 1</a>
    <button onclick="window.history.forward()">
        FORWORD
      </button>
</body>
  
</html>


app.html

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>NAVIGATION</title>
</head>
  
<body>
    <h1 style="padding:10px;color:blue">
        From HELLO WORLD to GEEKS FOR GEEKS
    </h1>
    <button onclick="window.history.back()">
      BACK</button>
</body>
  
</html>


Output:

 

Example 2:  Let’s implement go() method with the same example above:

  • Create two files with name base.html and app.html and paste the below codes
  • Click on the link first
  • Click on the go button to navigate back

base.html

HTML




<html>
<head>
    <title>NAVIGATION</title>
</head>
<body>
    <h1 style="color:green">
        From GEEKS FOR GEEKS to HELLO WORLD
    </h1>
    <a href="file:///E:/codes/app.htm">link 1</a>
</body>
</html>


app.html

HTML




<!DOCTYPE html>
<html>
<head>
    <title>NAVIGATION</title>
</head>
<body>
    <h1 style="padding:10px;color:blue">
        From HELLO WORLD to GEEKS FOR GEEKS
    </h1>
    <button onclick="window.history.go(-1)">GO(-1)</button>
</body>
</html>


Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads