Home > Article > Web Front-end > JavaScript implementation of url storage in browser_Basic knowledge
There is a very interesting feature in current browsers. You can modify the browser URL without refreshing the page; during the browsing process, you can store the browsing history and click Back when you click on the browser. When pressing the button, you can browse the browsing history to get the rollback information. This does not sound complicated and can be implemented. Let's write some code. Let's see how it works.
var stateObject = {}; var title = "Wow Title"; var newUrl = "/my/awesome/url"; history.pushState(stateObject,title,newUrl);
History object pushState() This method has 3 parameters, as you can see from the example above. The first parameter is a Json object, which stores any historical information about the current URL. The second parameter, title, is equivalent to passing the title of a document, and the third parameter is used to pass the new URL. You will I see that the browser's address bar changes but the current page does not refresh.
Let’s look at an example where we will store some arbitrary data in each individual URL.
for(i=0;i<5;i++){ var stateObject = {id: i}; var title = "Wow Title "+i; var newUrl = "/my/awesome/url/"+i; history.pushState(stateObject,title,newUrl); }
Run it now and click your browser’s back button to see how the URL changes. For each URL change, it stores the historical state "id" and the corresponding value. But how do we recapture the historical state and do something based on it? We need to add an event listener to "popstate", which will be triggered every time the state of the history object changes.
for(i=0;i<5;i++){ var stateObject = {id: i}; var title = "Wow Title "+i; var newUrl = "/my/awesome/url/"+i; history.pushState(stateObject,title,newUrl); alert(i); } window.addEventListener('popstate', function(event) { readState(event.state); }); function readState(data){ alert(data.id); }
Now you will see that whenever you click the back button, a "popstate" event will be fired. Our event listener then retrieves the URL the history state object is associated with and prompts for the value of "id".
It's very simple and fun, isn't it?