JavaScript history object explained

JavaScript history object explained

Preface:

When we browse a web page, we may not pay much attention to the operations of moving forward and backward. However, when developing, have you ever thought about what happens when you jump between pages, how the browser saves page information, and whether you need to reload the page when you return to the previous page? There will be many questions. To solve these problems, you first need to know the history object under window in the browser. This article will summarize the relevant knowledge points of this object in detail.

history object represents the user's navigation history since the current window was first used. Because history is a property of window , each window has its own history object. For security reasons, this object does not reveal the URLs that the user has visited, but it allows you to move forward and backward without knowing the actual URL.

1. Route navigation

history.go() method navigates in any direction through the user's history, either forward or backward. This method accepts only one parameter, which can be an integer representing how many steps to move forward or backward.

 history.go(-1);// Go back one pagehistory.go(1);// Go forward one pagehistory.go(2);// Go forward two pages//

go() has two shorthand methods: back() and forward().

history.back(); // Go back one page history.forward(); // Go forward one page

The history object also has a length attribute. history.length == 1 means that this is the first page in the user window.

histroy 's go method, back method, forword method, and the user's manual forward and back buttons on the browser will cause the page to refresh and jump.

2. History State Management API

(1) hashchange event

hashchange:history object is hashchange , which is triggered when the hash of the page URL changes, and developers can perform certain operations at this time. The hashchange event is fired when the fragment identifier of a URL changes (the portion of the URL following the # sign, including the # sign). The state management API allows developers to change the browser URL without loading a new page.

For example: pushState and replaceState methods, the page will not be refreshed, but the route will change.

(2) popstate event

When the active history entry changes, a popstate event is fired. If the history entry being activated was created by a call to history.pushState () , or was affected by a call to history.replaceState() , the state property of the popstate event contains a copy of the history entry's state object. Note that calling history.pushState() or history.replaceState() will not trigger a popstate event. This event is triggered only when a browser action is taken, such as when the user clicks the browser's back button (or calls history.back() or history.forward() in Javascript code).

(3) history.pushState() method

pushState() method adds a state to the history stack of the current browser session. This method receives three parameters: a state object, a title for the new state, and an (optional) relative URL. After pushState() method is executed, the state information is pushed to the history record and the browser address bar changes to reflect the new relative URL. The URL bar shows the new address, but does not load the page or even check if the page exists. This method increases history.length

(4) history.replaceState() method

replaceState() method modifies the current history entry. This method receives three parameters: a state object, a title for the new state, and an (optional) relative URL. After r eplaceState() method is executed, the current state object or the URL of the current history entity will be updated to respond to the user's action. The URL bar will display the new address, but the page will not be loaded or even checked to see if the page exists. This method does not increase history.length .

<body>
  <button onclick="handleNext()">Click me to the next page</button><br>
  <button onclick="handleLast()">Click me to the previous page</button><br>
  <script>
    window.onload = function () {
      console.log(window.history);
    }
    window.addEventListener('hashchange', function () {
      console.log('The hash has changed!')
    }, false);
    window.addEventListener('popstate', (event) => {
      console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
    });
    function handleNext() {
      const state = { userId: "1234", page: "2" }
      const title = 'Two'
      const url = 'page2.html'
      window.history.pushState(state, title, url)
      console.log(window.history);
    }
    function handleLast() {
      const state = { userId: "1234", page: "21" }
      const title = '一'
      const url = 'page21.html'
      window.history.replaceState(state, title, url)
      console.log(window.history);
    }
  </script>
</body>

The results are as follows:

3. Supplement: URL hash

hash of the URL is the anchor (#), which essentially changes href attribute of window.location . We can change the href by directly assigning location.hash , but the page will not refresh.

As shown in the following figure:

Last words:

This is the end of this article about the detailed explanation of the avaScript history object. For more information about the history object, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of JavaScript BOM composition and common events
  • Detailed explanation of BOM and DOM in JavaScript
  • Principle analysis of javascript History object
  • JavaScript navigator.userAgent obtains browser information case explanation
  • Use JS location to implement search box history function
  • JavaScript BOM location object + navigator object + history object

<<:  MySQL table return causes index invalidation case explanation

>>:  Using VMware IOInsight to perform refined virtual machine storage performance monitoring

Recommend

Essential Handbook for Web Design 216 Web Safe Colors

The color presentation on a web page will be affec...

Use docker to deploy tomcat and connect to skywalking

Table of contents 1. Overview 2. Use docker to de...

Using System.Drawing.Common in Linux/Docker

Preface After the project is migrated to .net cor...

JavaScript to achieve fancy carousel effect

This article shares two methods of implementing t...

How to change password in MySQL 5.7.18

How to change the password in MySQL 5.7.18: 1. Fi...

mysql row column conversion sample code

1. Demand We have three tables. We need to classi...

js, css, html determine the various versions of the browser

Use regular expressions to determine the IE browse...

Detailed explanation of the execution process of mysql update statement

There was an article about the execution process ...

How to Change Colors and Themes in Vim on Linux

Vim is a text editor that we use very often in Li...

About the configuration problem of MyBatis connecting to MySql8.0 version

When learning mybatis, I encountered an error, th...

Tutorial on installing mysql5.7.18 on mac os10.12

I searched the entire web and found all kinds of ...

Native JS to achieve special effects message box

This article shares with you a special effect mes...

How to perform query caching in MySQL and how to solve failures

We all know that we need to understand the proper...

Complete step record of vue encapsulation TabBar component

Table of contents Implementation ideas: Step 1: C...

Not a Chinese specialty: Web development under cultural differences

Web design and development is hard work, so don&#...