Illustrates how to use the HTML5 popstate to convert the browser history, html5popstate
I. What is popstate used?
In short, it is the newly added HTML5 api used to control browser history.
2. How to manipulate browser history in the past?
Window. history object, which contains two values of length and state. It inherits back, forward, go, and other functions on its _ proto _.
Before popstate, we can use back, forward, and go to perform back and forward operations on history.
For example:
History. back (); (you can also use history. go (-1) to implement the rewind effect)
Disadvantages:Operations can only move forward and backward, but cannot control where to go after the move, history. length will only maintain the original state
3. How to Use popstate?
The new HTML5 API extends window. history to make the history record point more open. It can store the pushState of the Current Historical Record Point, replaceState the current historical record point, and listen to the historical record point popstate.
PushState and replaceState are similar in usage.
Usage:
History. pushState (data, title, url );
// The first parameter data is the value of state. The second parameter title is the title of the page. However, this parameter is ignored by all browsers and it is good to pass an empty string; the third parameter url is the link you want to go;
ReplaceState usage is similar, for example, history. replaceState ("Homepage", "", location. href + "# news ");
Differences: PushState changes history. length, while replaceState does not change history. length.
Through comparison, we can see the difference between pushState and replaceState (pay attention to the changes in history. length ):
<! DOCTYPE html>
4. Listening to browser status changes
It can be understood that the browser's backward and forward operations will be triggered as long as the browser moves backward or forward. In the demo above, we performed the following operations in advance: Open the page, click "news", click "Music", and then click "news". Four history records were generated. Then listen to the browser's backward and forward status changes, as shown in: