Using the HTML5 's history API

Source: Internet
Author: User

The HTML5 History API provides a feature that allows developers to modify the URL of a site without refreshing the entire page. This feature is useful, for example, to load the contents of a page locally through a piece of JavaScript code, and you want to react to changes in the page content by changing the URL of the current page, which can come in handy.

For example, when a user enters the help page from the homepage, we use AJAX to load the content of the help page. Then the user goes to the product page, and we need to replace the content of the page with an AJAX request again. When the user wants to share the URL of the page, through the history API, we can change the URL of the page to reflect the content changes, so that whether the user to share or save the URL can be corresponding to the content of the page.

Basic knowledge

To see what functionality this API provides is very simple, open the Developer Tools Tool Panel in your browser and enter history in the console. If your browser supports the history API, you will see that this object comes with a number of methods.

Note the two methods of pushstate and replacestate . We can do some simple tests in the console to see what happens to URLs when we use these two methods. We'll analyze all the parameters in the two methods later, and now we need to focus on the last parameter:

History.replacestate (nullnull, ' hello ');

The replacestate method in the above code changes the URL of the current page and adds a '/hello ' later. However, no request was made and the current window remains on the previous page. But here's a question, when you click on the browser's Back button, the page does not fall back to the URL that we modified by the replacestate method, but instead goes back to the previous page (that is, the page we entered before this page). This is because the replacestate method does not modify the history of the browser, it simply replaces the URL in the address bar.

To solve this problem we need to use the pushstate method:

History.pushstate (nullnull, ' hello ');

Now click on the browser's Back button and you'll see that it works the way you expect. Because the pushstate method adds the URL that we passed to it to the history of the browser, which changes the history of the browser. What happens if we pass another full site URL to it? For example, we test on the home page of baidu.com and then enter the following in the console.

History.pushstate (nullnull, ' Https://twitter.com/hello ');

The browser will error. Because the URL passed to the pushstate method must belong to the same source as the URL of the current page (that is, it cannot cross the domain), there is a large security vulnerability that developers might borrow to trick users into thinking they are accessing a completely different site. And that's not the case.

Take a look at all the parameters passed to the pushstate method:

History.pushstate ([data], [title], [url]);
    1. The first parameter is used to pass the data we need, and we can receive the data when the state of the page changes. If the user clicks on the browser's back and forward buttons. It is important to note that only up to 640K of data is allowed in Firefox.
    2. The second parameter, title, is a string, but until now, almost all browsers have ignored the parameter.
    3. The last parameter is the URL we want to replace.
A brief look at

The main function of these history APIs is to not reload the page. In the past, we could only modify the URL of the current page by changing the value of the window.location, but this would result in the entire page being reloaded. If you modify only the hash in the URL, it will not cause the page to be refreshed.

Use the old Hashbang method to change the URL of the page without refreshing the page. The famous Twitter is the method used, but it is also widely criticized, after all, the hash is not treated as a real resource in location.

As an early supporter of the history API, Twitter later abandoned the traditional Hashbang approach. In 2012, the Twitter team introduced their new approach and listed some of the issues and also gave a detailed description of how each browser should implement the specification.

An example of using Pushstate and Ajax

https://css-tricks.com/examples/State/

In this example, we want users to find actors in the movie Ghost Squad (an American film) through our website. When the user chooses a picture, we need to show the actor's corresponding text description below, and give the picture a selected effect. When you click the Back button, the page should switch to the previous selected picture state, and the text below the picture should also be toggled. The same is true when you click the Forward button.

Here's one:

The HTML code for this example is very simple: Div.gallery contains all the links, and there is a picture in each link. Next we placed an empty div.content to store the text that was displayed when the actor's picture was clicked.

<Divclass= "Gallery">  <ahref= "https://cdn.css-tricks.com/peter.html">    <imgsrc= "Bill.png"alt= "Peter"class= "Peter"Data-name= "Peter">  </a>  <ahref= "https://cdn.css-tricks.com/ray.html">    <imgsrc= "Ray.png"alt= "Ray"class= "Ray"Data-name= "Ray">  </a>  <ahref= "https://cdn.css-tricks.com/egon.html">    <imgsrc= "Egon.png"alt= "Egon"class= "Egon"Data-name= "Egon">  </a>  <ahref= "https://cdn.css-tricks.com/winston.html">    <imgsrc= "Winston.png"alt= "Winston"class= "Winston"Data-name= "Winston">  </a></Div><Pclass= "Selected">Ghostbusters</P><Pclass= "Highlight"></P><Divclass= "Content"></Div>

If the page is still working without JavaScript, click on the image to jump to the corresponding page and then click the Back button to go back to the previous page. This is to consider the page's accessible rows and graceful demotion.

Next we'll add the JavaScript code. We add an event handler to each link in the Div.gallery element through event propagation , like this:

var container = Document.queryselector ('. Gallery '); Container.addeventlistener (function (e) {  if (e.target! = e.currenttarget) {    e.preventdefault ()    ; // E.target is the image inside the link we just clicked.   }  false);

In the IF statement, we get the value of the Data-name property of the selected picture, and then add '. html ' to the next page address to be accessed and pass it as the third argument to pushstate Method (but in the real case we may be able to modify the URL after the AJAX request succeeds).

var data = E.target.getattribute (' data-name '= data + ". html"; history.pushstate (null  null, URL);     // Change the current classes style here // then use the value of the data variable to update // and through the AJAX request. Content element // Finally, the title of the current document is updated.

(Of course, we can also use the value of the href attribute of link directly here)

I have replaced the contents of the real code with comments so that we can only focus on the use of the pushstate method.

Now we click on the image, URL and Ajax request content will be automatically updated, but when we click on the Back button will not fall back to the previous selected actor picture. Here we also need to update the content with another AJAX request when the user taps the back and forward buttons, and once again use the pushstate method to update the URL of the page.

We use the first parameter in the pushstate method, which is state, to hold the status information:

null, URL);

The data parameter in the above code can be obtained when the popstate event is triggered. The popstate event is triggered when the browser's back and forward buttons are clicked.

function (e) {  //  e.state represents the Data-attribute} of the last clicked Image);

We can pass some of the information we need through this parameter, for example, in this example we pass the previous selected ghost Squad actor as a parameter to the requestcontent method, where We use the jquery load method to make an AJAX request.

functionrequestcontent (file) {$ ('. Content '). Load (file + '. Content '));} Window.addeventlistener (' Popstate ',function(e) {varcharacter =e.state; if(character = =NULL) {removecurrentclass (); Textwrapper.innerhtml= " "; Content.innerhtml= " "; Document.title=Defaulttitle; } Else{updatetext (character); Requestcontent (character+ ". html");      Addcurrentclass (character); Document.title= "Ghostbuster |" +character; }});

If the user clicks on actor Ray's picture, event listener is triggered and then the value of the data property of the picture is saved in the pushstate event. When the user clicks on another image and clicks on the browser's Back button, the popstate event is triggered to reload the ray.html page.

What does that mean? When we click on an actor's picture and then share the changed URL, the corresponding HTML file will be loaded automatically when the user accesses the URL. This leads to a better user experience and a consistent URL and page content that reduces some of the confusion that can be brought to the user.

The above example simply loads content dynamically through jquery, and of course we can pass some more complex objects in the pushstate method. But this example is enough to illustrate the problem and help us get started with the ability to use the history API. We must learn to walk before we can run.

Next

If we want to use this technology on a large scale, we should consider using some proprietary tools, such as Pjax. It is a jquery plugin that can greatly improve the speed at which we use both the Ajax and pushstate methods, but it only supports modern browsers that use the History API interface.

  History JS can be compatible with the old browser, for browsers that do not support the History API interface, it still uses the old URL hash method to achieve the same function.

About URLs

Here I specifically quoted Kyle Neath's description of the URLs:

URLs is a generic concept that works in Firefox, Chrome, Safari, Internet Explorer, Curl, wget, and even on your iphone, Android and sticky notes. It is a common syntax in the web. Don't take that as a matter of course. Anyone who knows a little bit about technology can browse more than 90% of your app without deliberately remembering the structure of those URLs. To achieve this effect, you need to consider the usefulness of URLs.

This means that no matter what kind of hacks or performance optimizations you want to make, as Web developers, you should focus on URLs. With the help of the HTML5 history API, we can easily solve some of the problems in the examples above.

Problems
    • It is usually a good idea to embed the address of an AJAX request into the href attribute of the A tag.
    • Make sure that you return true in the Click event handler of JavaScript, so that when someone uses a middle-click or command click, it does not cause the program to be accidentally overwritten.
Add
    • Mozilla's documentation on manipulating browser history
    • Ajax sample Collection Dive into HTML5
    • Twitter about Pushstate's implementation
Browser support
Chrome Safari Firefox Opera IE Android IOS
31+ 7.1+ 34+ 11.50+ + 4.3+ 7.1+

Original address: https://css-tricks.com/using-the-html5-history-api/

Using the HTML5 's history API

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.