Now in the browser, there is a very interesting feature, you can not refresh the page to modify the browser URL; In the browsing process. You can store your browsing history, and when you click the Back button in your browser, you can surf the history to get a fallback message, which sounds uncomplicated and achievable, and we write code. Let's see how it works.
Copy Code code as follows:
var stateobject = {};
var title = "Wow title";
var newurl = "/my/awesome/url";
History.pushstate (Stateobject,title,newurl);
History Object Pushstate () This method has 3 parameters, which you can see from the example above. The first argument, which is a JSON object, stores any historical information about the current URL. The second argument, title, is the equivalent of passing the title of a document, and the third parameter is used to pass the new URL. You will see that the browser's address bar has changed and the current page is not refreshed.
Let's take a look at an example where we'll store some arbitrary data in each individual URL.
Copy Code code as follows:
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 on the browser's return button to see how the URL changes. For each URL change, it stores the history status "id" and the corresponding value. But how do we regain the state of history and do something about it on this basis? We need to add an event listener to "Popstate", which will be triggered every time the state of the historical object changes.
Copy Code code as follows:
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'll see that whenever you click the return button, a "Popstate" event is triggered. Our event listener then retrieves the URL associated with the history state object and prompts the value of "id".
It's very simple and fun, isn't it?
English Original: http://hasin.me/2013/10/16/manipulating-url-using-javascript-without-freshing-the-page/