JavaScript implementation of url storage in the browser

  • 2020-07-21 06:52:32
  • OfStack

Today's browsers have an interesting 10 out of 10 feature that lets you modify URL without refreshing the page. And while you're browsing, you can store your browsing history, and when you click the back button in the browser, you can go back through the browsing history and get back information, which doesn't sound too complicated, but it's possible, so 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);

The pushState() method takes three arguments, as you can see from the above example. The first parameter, Json, is an Json object that 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.

Let's look at an example where we will store 1 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);
}

Now run and click the browser's Back button to see how URL has changed. For each change to URL, it stores the historical state "id" and the corresponding value. But how do we regain that historical state and do something about it? We need to add an event listener to "popstate" that 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);
}

You will now see that whenever you click the back button, an "popstate" event is triggered. Our event listener then retrieves the URL associated with the history state object and prompts for the value "id".

It's very simple and interesting, isn't it?


Related articles: