HTML5 new Features "Pushstate" and "Replacestate"

Source: Internet
Author: User

This paper is the official HTML5 training course for Brother Lian it educational institution, mainly introduces: HTML5 new features "Pushstate" and "Replacestate"

Recently, when dealing with the browser disable brush function, a new attribute is used: history.pushstate ();

The official explanations are as follows:

The History.pushstate () method and the History.replacestate () method allow you to add and modify history entries individually. These methods can work together with window.onpopstate events.

Using History.pushstate () changes the value of the referrer, and the XMLHttpRequest object created after you invoke the method uses this value in the HTTP request header. The value of referrer is the URL of the window where the XMLHttpRequest object is created.

First, attach an instance function:

12345678910111213141516171819202122232425262728         //防止浏览器后退功能    $(document).ready(function(e) {           varurl = window.location.href;        varlast = url.substring(url.lastIndexOf("/"));        if(window.history && window.history.pushState) {            $(window).on(‘popstate‘function() {                    //在IE中必须得有这两行                window.history.pushState(‘forward‘null, url);                window.history.forward(1);            });        }                //屏蔽鼠标右键                $(document).bind("contextmenu",function(e){                 returnfalse;               });                //屏蔽f5和回车功能              $(document).bind("keydown",function(e){                 if(event.keyCode==116)                           {                                   event.keyCode    =    0;                                   event.cancelBubble    =   true;                                  returnfalse;                           }           });            });

and the underlying grammatical differences of "pushstate" and "replacestate":


history.pushstate (state, title, URL)

Adds the current URL and history.state to the history and replaces the current with the new state and URL.

does not cause page refreshes.

State: The status information corresponding to the URL to jump to.

Title: Can not preach

URL: The URL address to jump to, not across domains.

history.replacestate (state, title, URL)

Replace the current with the new state and URL.

does not cause page refreshes.

State: The status information corresponding to the URL to jump to.

Title: Can not preach

URL: The URL address to jump to, not across domains.

The biggest difference is:

Pushstate is added to the history, and replacestate is not added.

Let's start by explaining the syntax between the two:

1. Example

Suppose Http://mozilla.org/foo.html will execute the following JavaScript code:

12 varstateObj = { foo: "bar"};history.pushState(stateObj, "page 2""bar.html");

This will let the browser's address bar display http://mozilla.org/bar.html, but will not load the bar.html page and will not check whether bar.html exists.

Assuming the user navigates to http://google.com and then clicks the Back button, the address bar will display http://mozilla.org/bar.html, and the page will trigger the Popstate event, the state object in the event Object) contains a copy of the stateobj. The page looks like foo.html, although the page content may be modified in the Popstate event.

If we click the Back button again, the URL will change back to http://mozilla.org/foo.html, the document will trigger another Popstate event, this time the state object is null. Fallback also does not change the contents of the document.

2. Pushstate () Method: Add and modify History entries

① Syntax:

1 history.pushState(state, title, url);

Pushstate () has three parameters: A Status object, a caption (now ignored), an optional URL address. The details of these three parameters are examined separately below:

State Object-A JavaScript object associated with a new history entry created with the Pushstate () method. Whenever a user navigates to a newly created state, the Popstate event is triggered, and the state property of the event object contains a copy of the status object of the history entry.

Any serializable object can be treated as a state object. Because the Firefox browser will save the state object to the user's hard disk, so that they can be restored after the user restarts the browser, we forcibly limit the size of the state object is 640k. If you pass a state object to the Pushstate () method that exceeds that limit, the method throws an exception. If you need to store very large data, it is recommended to use Sessionstorage or localstorage.

Title-firefox browser currently ignores this parameter, although it may be used later. Considering that the method might be modified in the future, it would be safer to pass an empty string. Alternatively, you can pass in a short title indicating the state you are going to enter.

Address (URL)-The address of the new history entry. The browser does not load the address after calling the Pushstate () method, but after that it may attempt to load, for example, the user restarts the browser. The new URL is not necessarily an absolute path; if it is a relative path, it will be based on the current URL, and the incoming URL should be homologous to the current URL, otherwise pushstate () throws an exception. The parameter is optional, or the current URL of the document if not specified.

② Sample Example

Created a new browser history set by state, title, and URL.

1234 varstate = { ‘page_id‘: 1, ‘user_id‘: 5 };var title = ‘Hello World‘;varurl = ‘hello-world.html‘;history.pushState(state, title, url);

③ Advantages

In a sense, calling Pushstate () is a bit like setting window.location= ' #foo ', and they both create and activate new history entries within the current document. But Pushstate () has its own advantages:

    • The new URL can be any homologous URL, in contrast, when using the Window.location method, only the hash can be modified to ensure that it stays in the same document.

    • Decide whether to modify the URL according to your individual needs. Instead, set window.location= ' #foo ' to create a new history only if the current hash value is not foo.

    • You can add abstract data to a new history entry. If you use a hash-based method, you can only transcode the relevant data into a very short string.

Note:the Pushstate () method never triggers the Hashchange event, even if the new address only changes the hash.

3, Replacestate () method: Modify the browser's current history entry

The History.replacestate () operation is similar to History.pushstate (), except that the Replacestate () method modifies the current history entry instead of creating a new entry.

Using the Replacestate () method is particularly appropriate when you want to update the status object or URL of the current history entry in response to certain actions of the user.

4. Popstate Events

The Popstate event is triggered whenever a change in the active history occurs. If the active history entry was created by Pushstate, or is affected by the Replacestate method, the State property of the Popstate event will contain a copy of the history's state object.

Calling History.pushstate () or history.replacestate () does not trigger the Popstate event. The Popstate event is only triggered when other browsers are operating, such as clicking the Back button (or calling the History.back () method in JavaScript).

When the Web page loads, browsers have different manifestations of whether the Popstate event triggers, and Chrome and Safari trigger the Popstate event, and Firefox does not.

① syntax

1 window.onpopstate = funcRef;

Funcref is the name of a function.

② instances

If the current page address is http://example.com/example.html, run the following code:

12345678910 window.onpopstate = function(event) {    alert("location: "+ document.location + ", state: "+ JSON.stringify(event.state));};//绑定事件处理函数. history.pushState({page: 1}, "title 1""?page=1");    //添加并激活一个历史记录条目 http://example.com/example.html?page=1,条目索引为1history.pushState({page: 2}, "title 2""?page=2");    //添加并激活一个历史记录条目 http://example.com/example.html?page=2,条目索引为2history.replaceState({page: 3}, "title 3""?page=3"); //修改当前激活的历史记录条目 http://ex..?page=2 变为 http://ex..?page=3,条目索引为3history.back(); // 弹出 "location: http://example.com/example.html?page=1, state: {"page":1}"history.back(); // 弹出 "location: http://example.com/example.html, state: nullhistory.go(2);  // 弹出 "location: http://example.com/example.html?page=3, state: {"page":3}

The Popstate event will still be triggered even if you enter those pages that are not pushstate and Replacestate methods (such as http://example.com/example.html) that do not have a state object associated with them.

5. Read the current status

When the page loads, it may contain a non-empty state object. This happens, for example, if the page uses the Pushstate () or Replacestate () method to set a status object, and then the user restarts the browser. When the page reloads, the page triggers the OnLoad event, but does not trigger the Popstate event. However, if you read the History.state property, you get a status object that is the same as when the Popstate event is triggered.

You can directly read the status of the current history entry without waiting for the Popstate event:

1 varcurrentState = history.state;

6. Browser compatibility

HTML5 new Features "Pushstate" and "Replacestate"

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.