javascript history Object Explanation

  • 2021-07-18 06:57:51
  • OfStack

Previous words

The history object keeps the user's online history from the moment the window is opened. Because of security concerns, developers can't get the URL of the user's browser, but with the list of pages visited by the user, they can go back and forward without knowing the actual URL. This article describes the history object in BOM in detail

length

The history. length property holds the historical number of URL. Initially, the value is 1. If the current window has visited three URLs, the history. length property equals 3

Because the IE 10 + browser initially returns 2, there is a compatibility problem, so this value is not commonly used


history.length //  Initially, the value is 1
history.length //  Visit 3 After the URL, the value is 3

Jump method

The history object provides a series of methods that allow you to move between browse histories, including go (), back (), and forward ()

"go ()"

The go () method allows you to jump arbitrarily in the user's history. This method takes a parameter that represents an integer value of the number of pages that jump backward or forward. Negative numbers indicate backward jumps (similar to the back button), and positive numbers indicate forward jumps (similar to the forward button)


// Backward 1 Page 
history.go(-1)
// Advance 1 Page 
history.go(1);
// Advance two pages 
history.go(2);

When the go () method has no parameters, it is equivalent to history. go (0) and can refresh the current page


// Refresh the current page 
history.go();
// Refresh the current page 
history.go(0);

"back ()"

The back () method is used to mimic the browser's back button and is equivalent to history. go (-1)

"forward ()"

The forward () method is used to mimic the browser's forward button and is equivalent to history. go (1)


// Backward 1 Page 
history.back()
// Advance 1 Page 
history.forward()

If you move beyond the boundaries of the access history, the above three methods do not report errors, but fail silently

[Note] When using history, pages are usually loaded from the browser cache, rather than re-asking the server to send new pages

Addition and alteration of records

HTML5 adds two new methods to the history object, history. pushState () and history. replaceState (), to add and modify records in the browsing history. The state property is used to hold the record object, and the popstate event is used to listen for changes to the history object

[Note] IE9-Not supported by browsers

"pushState ()"

The history. pushState () method adds a state to the browser history. The pushState () method takes three parameters: a state object, a title (now ignored), and an optional URL address

history.pushState(state, title, url);

state object-The state object is an javascript object created by the pushState () method and associated with the history. When the user directs to a new state, the popstate event will be triggered. The state property of the event contains the state object of the history. If you don't need this object, you can fill in null here

title-The title of the new page, but all browsers ignore this value at present, so you can fill in null here

URL-This parameter provides the address of the new history. The new URL must be in the same domain as the current URL, otherwise pushState () throws an exception. This parameter is optional, and if it is not specifically marked, it will be set to the current URL of the document

Assuming the current URL is example. com/1. html, add a new record to the browse record (history object) using the pushState method


var stateObj = { foo: 'bar' };
history.pushState(stateObj, 'page 2', '2.html');

After adding the new record above, the browser address bar immediately displays example. com/2. html, but it doesn't jump to 2. html or even check whether 2. html exists. It just becomes the latest record in the browsing history. If you visit google. com and click the Backward button, the url on the page will show 2. html, but the content will remain the same as 1. html. Click the Backward button once more, and url will display 1. html with the same content

In a word, the pushState method does not trigger a page refresh, but only causes the history object to change and the display address of the address bar to change

If the url parameter of pushState is set with a new anchor value (i.e. hash), the hashchange event will not be triggered, even though the new URL and the old hash are different only on the hash

If a cross-domain URL is set, an error will be reported. The purpose of this design is to prevent malicious code from making users think that they are on another website


//  Report an error 
history.pushState(null, null, 'https://twitter.com/hello');

"replaceState ()"

The parameters of the history. replaceState method are similar to those of the pushState method 1, except that the replaceState () method modifies the current history entry instead of creating a new one

Assume that the current web page is example. com/example. html


history.pushState({page: 1}, 'title 1', '?page=1');
history.pushState({page: 2}, 'title 2', '?page=2');
history.replaceState({page: 3}, 'title 3', '?page=3');
history.back()
// url Display as http://example.com/example.html?page=1
history.back()
// url Display as http://example.com/example.html
history.go(2)
// url Display as http://example.com/example.html?page=3

"state"

The history. state property returns the state object for the current page


history.pushState({page: 1}, 'title 1', '?page=1');
history.state// { page: 1 }

"popstate Event"

The popstate event is triggered whenever the browsing history of the same document (that is, the history object) changes

It should be noted that only calling the pushState method or the replaceState method does not trigger this event, but only when the user clicks the browser backward button and forward button, or calls the back (), forward (), go () methods using javascript. In addition, this event is only for the same document. If different documents are loaded due to the switching of browsing history, this event will not be triggered

When used, you can specify callback functions for popstate events. The argument to this callback function is an event event object whose state property points to the state object provided by the pushState and replaceState methods for the current URL (that is, the first argument of both methods)


window.onpopstate = function (event) {
 console.log('location: ' + document.location);
 console.log('state: ' + JSON.stringify(event.state));
};    

The event. state in the above code is the state object bound to the current URL through the pushState and replaceState methods

This state object can also be read directly through the history object

var currentState = history.state;

Round trip cache

By default, the browser caches the page in the current session (session), and when the user clicks the Forward or Back button, the browser loads the page from the cache

The browser has a feature called "round trip cache" (back-forward cache or bfcache), which can speed up page conversion when users use the browser's "Back" and "Forward" buttons. This cache holds not only the page data, but also the state of DOM and javascript; In fact, the whole page is saved in memory. If the page is in bfcache, the load event will not be triggered when the page is opened again

[Note] IE10-Not supported by browsers

"pageshow"

The pageshow event is triggered when the page is loaded, including the first load and loading from the cache. If you want to specify the code that runs every time the page is loaded (whether it is cached from the browser or not), you can put the listener function for this event

When it is loaded for the first time, it is triggered in the order after load event. When loading from the cache, the load event does not fire, because the Web page usually looks in the cache as the listener function for the load event runs, so it does not have to be repeated. Similarly, if the page is loaded from the cache, the JavaScript script initialized in the page (such as the DOMContentLoaded event listener function) will not be executed

[Note] Although the target of this event is document, its event handler must be added to window

The pageshow event has an persisted property and returns a Boolean value. This property is false when the page is loaded for the first time or when it is not loaded from the cache; When the page is loaded from the cache, this property is true


(function(){
 var showCount = 0;
 window.onload = function(){
  console.log('loaded');
 }
 window.onpageshow = function(e){
  e = e || event;
  showCount ++;
  console.log(e.persisted,showCount + 'times');
 }
})();

[Note] The above example uses private scope to prevent the variable showCount from entering global scope. If the browser's Refresh button is clicked, the value of showCount is reset to 0 because the page has been completely reloaded

"pagehide"

Corresponding to the pageshow event is the pagehide event, which is triggered when the browser unloads the page and before the unload event. Like pageshow Event 1, pagehide fires on top of document, but its event handler must be added to the window object

[Note] Pages that specify an onunload event handler are automatically excluded from bfcache, even if the event handler is empty. The reason is that onunload is most commonly used to undo operations performed in onload, and skipping onload and displaying the page again is likely to cause the page to be abnormal

The event object of the pagehide event also contains the persisted attribute, although its purpose is slightly different. If the page is loaded from bfcache, the value of persisted is true; If the page is saved in bfcache after unloading, the value of persisted is also set to true. Therefore, when pageshow is fired for the first time, the value 1 of persisted will be false, and when pagehide is fired for the first time, persisted will become true (unless the page will not be saved in bfcache)


// Backward 1 Page 
history.go(-1)
// Advance 1 Page 
history.go(1);
// Advance two pages 
history.go(2);
0

Related articles: