JavaScript is used to modify the implementation code of the browser URL address bar

  • 2020-03-26 21:35:40
  • OfStack

In today's browsers, there's a very interesting feature where you can change the browser URL without refreshing the page; In the process of browsing, you can store the browsing history, when you click the back button in the browser, you can go back to the browsing history and get the information. Let's see how it works.


var stateObject = {};
var title = "Wow Title";
var newUrl = "/my/awesome/url";
history.pushState(stateObject,title,newUrl);

The History object pushState() has three arguments, as you can see from the above example. The first parameter is a 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'll 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);
}

Now run, click the browser's back button to see how the URL has changed. For each URL change, this is because it stores the historical state "id" and the corresponding value. But how do we get back to that historical state and do something about it? We need to add an event listener to "popstate", which will be triggered every time the state of the historical 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 triggered. Our event listener then retrieves the URL associated with the historical state object and prompts for the value of the "id."
It's very simple and fun, isn't it?

English text: (link: http://hasin.me/2013/10/16/manipulating-url-using-javascript-without-freshing-the-page/)


Related articles: