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 > < 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 > </ 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: