[Introduction] There is a very interesting function in current browsers. You can modify the browser URL without refreshing the page; during the browsing process, you can store the browsing history. When you are in the browser When you click the back button, you can browse the browsing history to get the rewind information. This does not sound like it. In today's browsers, there is a very interesting feature. You can browse the page without refreshing the page. Modify the browser URL when browsing; during the browsing process, you can store the browsing history. When you click the back button in the browser, you can get the back information in the browsing history. This does not sound complicated. It's doable, 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 now, click the 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?
The above is the detailed content of Introduction to how to use JavaScript to modify the URL address. For more information, please follow other related articles on the PHP Chinese website!