The history object

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

navigation

The go() method can navigate through the user’s history in any direction, either forward or backward. This method accepts only one argument, which can be an integer indicating how many steps forward or backward. A negative value means moving backward in history (similar to clicking the browser’s back button), while a positive value means moving forward in history (similar to clicking the browser’s forward button). Here are a few examples:

// go(-1); // go(1); // go(2);Copy the code

In older versions of some browsers, the argument to the go() method can also be a string, in which case the browser navigates to the first location in history that contains the string. The closest position may involve either going backwards or forwards. If there is no match in the history, the method does nothing, as follows:

// Navigate to the nearest wrox.com page history.go("wrox.com"); // Navigate to the nearest nczonline.net page history.go("nczonline.net");Copy the code

There are two abbreviations for go() : back() and forward(). As the name suggests, these methods emulate the browser’s back and forward buttons:

// back a page history.back(); // forward a page history.forward();Copy the code

The history object also has a Length attribute, indicating that there are multiple entries in the history. This property reflects the number of historical records, including pages that can be moved forward and backward. For the first page loaded in a window or TAB, history.length is equal to 1. Test this value to determine if the user’s browser is starting from your page:

If (history.length == 1){// This is the first page in the user window}Copy the code

The history object is typically used to create the Back and forward buttons, and to determine if the page is the first record in the user’s history.

Note that if the page URL changes, a new entry is generated in the history. For major browsers released since 2009, this includes changing the hash value of the URL (so setting location.hash to a new value adds a record to the history of those browsers). This behavior is often used by single-page application frameworks to simulate forward and backward so that navigation does not trigger a page refresh.

History Status Management

One of the most difficult aspects of modern Web application development is history management. Gone are the days when every click triggered a page refresh. Gone are the days when “back” and “forward” buttons meant “Help me switch a state” to users. To solve this problem, the first event to appear is the Hashchange event (discussed in Chapter 17). HTML5 also adds handy state management features for history objects.

Hashchange is triggered when the hash of the page URL changes, and the developer can perform certain actions at this point. The state management API lets developers change the browser URL without loading a new page. To do this, use the history.pushstate () method. This method takes three parameters: a state object, a title for the new state, and an (optional) relative URL. Such as:

let stateObject = {foo:"bar"};
history.pushState(stateObject, "My title", "baz.html");
Copy the code

After the pushState() method is executed, the status information is pushed into the history and the browser address bar changes to reflect the new relative URL. In addition to these changes, the browser page does not send a request to the server, even though the location.href returns the contents of the address bar. The second parameter is not used by the current implementation, so you can pass either an empty string or a short title. The first parameter should contain the information necessary to properly initialize the state of the page. To prevent abuse, the size of objects in this state is limited, usually within 500KB to 1MB.

Because pushState() creates a new history, the Back button is enabled accordingly. Clicking the Back button at this point triggers the PopState event on the Window object. The popState event’s event object has a state property that contains the state object passed in via the first argument to pushState() :

window.addEventListener("popstate", (event) => { let state = event.state; If (state) {// The state of the first page is null processState(state); }});Copy the code

Based on this state, you should reset the page to the state represented by the state object (because the browser doesn’t automatically do this for you). Remember, the page has no state when it first loads. So when you click the Back button until you return to the original page, event.state will be null. You can get the current state object with history.state, or you can update the state with replaceState() and pass in the same first two arguments as pushState(). Updating the status does not create a new history, only overwrites the current state:

history.replaceState({newFoo: "newBar"}, "New title");
Copy the code

The state objects passed to pushState() and replaceState() should only contain information that can be serialized. Therefore, DOM elements and the like are not suitable for storing in state objects.

Note that when using HTML5 state management, make sure that each “fake” URL created with pushState() corresponds to a real physical URL on the server. Otherwise, clicking the Refresh button results in a 404 error. All Single Page Application (SPA) frameworks must solve this problem through some configuration on the server or client side.

Note The above content is excerpted from the book “JavaScript Advanced Programming (4th edition)” and is for learning record only. If there is infringement, contact delete.

The resources

The front end of a more complete universe