Monday, April 20, 2020

JavaScript history object

JavaScript History Object


The window.history property of window object returns the reference to the history object which contains the record of URLs visited by the user within the browser( like pages visited and the frame those belong to the current logged in user). This property specifies an interface to manipulate the browser’s session history. This is a read-only property and provided by the window object.

We can load previous, forward or any particular page using various methods provided by the history object.

Although all major browsers support this object, still there are no public standards applied to history objects worldwide.

Properties


length

This property returns the length of the history URLs visited by the user in that session.

Methods

javascript history object


forward()

This method is used to load the next page. It is equivalent to clicking the back button in the browser.

<html>
<head>
<title>ProgrammingHunk</title>
</head>
<body>
<b>history.forward() example</b><br>
<input type="button" value="Forward" onclick="next()">
<script>
function next() {
     window.history.forward()
}
</script>
</body>
</html>

The script will not work if no page was visited after this page.

back()

This method is used to load the previous page. It is equivalent to clicking the forward button in the browser.

<html>
<head>
<title>ProgrammingHunk</title>
</head>
<body>
<b>history.back() example</b><br>
<input type="button" value="Back" onclick="lastVisitedPage()">
<script>
function lastVisitedPage() {
     window.history.back();
}
</script>
</body>
</html>

The script will not work if no page was visited previously on this page.

go()

This method is used to load the given page number in the browser. The history.go(n) function is equivalent to pressing the back or forward n number of times in our browser to reach the page exactly that we want to load.


<html>
<head>
<title>ProgrammingHunk</title>
</head>
<body>
<b>history.back() example</b><br>
<input type="button" value="go to" onclick="goToPage()">
<script>
function goToPage() {
     window.history.go(3);
}
</script>
</body>
</html>