I haven’t been familiar with historypushStatewithreplaceStateMethods, today take time to understand, this article reprinted a large part of MDNManipulating the browser historyAs well aswindow.onpopstateInterested students can refer to these articles directly

A list,

HTML5 introduces history.pushState() and history.replacestate () methods, which add and modify history entries, respectively. These methods are usually used in conjunction with window.onpopState.

Examples of pushState() methods

Assume that performs the following JavaScript code in http://mozilla.org/foo.html:

var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2"."bar.html");
Copy the code

This will make your browser’s address bar display for http://mozilla.org/bar.html, but will not cause the browser to load bar. The HTML, and even does not check bar. The HTML exists.

Suppose the user now visits http://google.com again and clicks the back button. At that moment, the address bar will show http://mozilla.org/bar.html and page will trigger the popstate event, the event object state includes stateObj a copy. The page itself is the same as foo.html, although it may modify its content in a PopState event.

If we click back button again, the page URL will be http://mozilla.org/foo.html, document object document will trigger another popstate event, this time the event object state of the object is null. Here, too, the return does not change the content of the document, although the document may change its content when it receives the PopState event, its content remains the same as the previous presentation.

PushState (

PushState () takes three arguments: a state object, a title (currently ignored), and (optionally) a URL. Let’s explain the three parameters in detail:

State object – The state object state is a JavaScript object that creates a new history entry with pushState (). Whenever the user navigates to a new state, the POPState event is fired, and the state property of the event contains a copy of the history entry state object.

Title – Ignore This parameter is ignored for now, but may be used in the future. Passing an empty string is safe here, but not safe in the future. Alternatively, you can pass a short title for the state of the jump.

URL – This parameter defines a new historical URL record. Note that the browser does not load the URL immediately after calling pushState(), but it may load it later in certain circumstances, such as when the user reopens the browser. The new URL does not have to be an absolute path. If the new URL is a relative path, it is treated as relative to the current URL. The new URL must be of the same origin as the current URL, otherwise pushState() will throw an exception. This parameter is optional. The default value is the current URL.

PushState () differs from setting the hash value

In a sense, calling pushState() is similar to setting window.location = “#foo”; both create and activate a new history on the current page. But pushState() has several advantages:

The new URL can be any URL of the same origin as the current URL. Setting window.location only keeps the same file if you only change the hash value.

If desired, you can create a history without changing the URL. Setting window.location = “#foo” instead; , a new history entry will only be created if the current hash is not #foo.

We can associate arbitrary data with a new history entry. In the hash-based approach, all the relevant data must be encoded into a short string.

5. ReplaceState (

The use of history.replacEstate () is very similar to history.pushState(), except that replaceState() modifies the current history entry rather than creating a new one.

Popstate event

Whenever the active history entry changes, the popState event is fired on the corresponding Window object. If the currently active history entry was created by the history.pushState() method or modified by the history.replacestate () method, The state property of the POPState event object contains a copy of the state object for this history entry.

We can also get state directly on the history object as follows:

var currentState = history.state;
Copy the code

Note that calling history.pushState() or history.replacEstate () does not trigger the popState event. The opState event is only triggered when the browser does something, such as clicking the back or forward button (or calling the history.back(), history.forward(), or history.go() methods in JavaScript).

Example of popState event

If the current web address is http://example.com/example.html, run the following code:

window.onpopstate = function(event) {
  alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
// Bind event handlers.
history.pushState({page: 1}, "title 1"."? page=1");    / / add and activate a history entry http://example.com/example.html?page=1, entry index of 1
history.pushState({page: 2}, "title 2"."? page=2");    / / add and activate a history entry http://example.com/example.html?page=2, entry index of 2
history.replaceState({page: 3}, "title 3"."? page=3"); // Modify the currently active history entry http://ex.. ? Page = 2 to http://ex.. ? Page =3 and the entry index is 3
history.back(); / / the pop-up "location: http://example.com/example.html?page=1, state: {" page" : 1}"
history.back(); / / the pop-up "location: http://example.com/example.html, state: null
history.go(2);  / / the pop-up "location: http://example.com/example.html?page=3, state: {3}" page ":
Copy the code

PushState (

The main reason we use pushState() is that it can listen for return events on the browser. This also works on mobile devices. See the following code:

<body>
    <div>Window. onpopState can listen for return key events</div>
    <script>
        history.pushState({}, ""); 
        window.onpopstate = function(event) {
            // Here you can listen to the browser return event and do whatever you want,
            // For example, jump to another page
            location.href = "https://www.baidu.com";
        };
    </script>
</body>
Copy the code

Of course, window.onhashchange can also listen for return events on the browser, as shown in the following code (which can be run directly) :

<body>
    <div>Window. onhashchange can listen for return key events</div>
    <script>
        setTimeout((a)= >{
            location.hash="a"
        },100);
        setTimeout((a)= >{
            window.onhashchange = function(event) {
                location.href = "https://www.baidu.com"; }},200);
    </script>
</body>
Copy the code

9. Refer to the article

PushState and replaceState MDN

‘OnPopState ‘MDN document

The original article was published on Wang Yulue’s personal website