History.pushstate () and history.replacestate () are two new methods for the history object,

Is a great way to manipulate history;

history.State()

History.state () adds a record to the browser’s history. Let’s see how to use this method:

Let’s create an HTML page file, add a button to the page, and see what it looks like




We see the address of the file in the address bar, and now we don’t refresh the page, we don’t jump to another address,

How to change the address in the address bar without changing the original web page?



To add javascript code to our previous page, shown in red above, we used the pushState () method;

Then we open the page and start with the same address bar. Let’s click the button to see:



The page itself has not changed anything, only the address bar has changed, achieving no refresh changes to the address bar, and in the history of the record

A new record was added to the


history.replaceState()

History.replacestate () replaces the current history. Let’s see how to use this method:

In the history.pushState() method above, we first created an index.html page,

In the second step, we add a history using the pushState() method. This is the second history.

Now let’s make a change, using the replaceState() method:

<body> 

 <button id="abc">test</button> 

 <script> 

 var abc=document.getElementById("abc");

abc.onclick=function(){ window.history.pushState(null,null,'? page=1'); history.replaceState(null, null, '? page=2'); }

 </script> 



We go to the page again, and we click the button, and we trigger the JS function,

At this time, the address in the address bar is: file:/// /F:/web_pro/pro_p/index.html? page=2

We use the replaceState () method to file:///F:/web_pro/pro_p/index.html? page=1

Instead: file:///F:/web_pro/pro_p/index.html? Page = 2;

The whole process is fairly clear;

Summary: pushState() adds a new record to the history;

The replaceState() method is to replace the current historical record with the legendary capture rebirth!