HTML5 new features "pushstate" and "replacestate"

Source: Internet
Author: User

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:

        //prevent Browser fallback function $ (document). ready (function (e)  {var url  = window.location.href;var last = url.substring (url.lastindexof ("/"));if  ( Window.history && window.history.pushstate)  {$ (window). on (' popstate ',  function   ()  {        //must have these two lines window.history.pushState (' forward ') in IE ,  null, url); Window.history.forward (1);}); Block right mouse button         $ (document). bind ("contextmenu", function (e) {              return false;            });//mask F5 and enter function       $ (document). Bind ("keydown", function (e) {     if     (event.keycode==116)                         {                                 event.keyCode    =    0;                                 event.cancelBubble    =    true;                               return    false;                  (      }       });});


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:

var stateobj = {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:

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.

var state = {' page_id ': 1, ' user_id ': 5};var title = ' Hello world '; var url = ' 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


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:

window.onpopstate = function  (event)  {    alert ("location: "  + document.location +  ", state: "  + json.stringify (event.state));};/ /bind event Handler.  history.pushstate ({page: 1},  "title 1",  "? page=1");     //adds and activates a history entry  http://example.com/example.html?page=1 with an entry index of 1history.pushstate ({page: 2},   "title 2",  "page=2")     //add and activate a history entry  http://example.com/ example.html?page=2, the entry index is 2history.replacestate ({page: 3},  "title 3",  "? page=3");  // Modify the current active history entry  http://ex ... page=2  into  http://ex ...? page=3, Entry index is 3history.back (); //  pop-up   "location: http://example.com/example.html?page=1,  state: {"page": 1} "history.back (); //  pop-up  " location: http://example.com/ Example.html, state: nullhistory.go (2);  //  Pop-up   "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:

var currentstate = history.state;


6. Browser Compatibility

650) this.width=650; "src=" http://7xj89g.com1.z0.glb.clouddn.com/FqUzfrcRTeLlbsk2ok8LadLoGNBn "title=" pushstate_ Compatibility.png "alt=" pushstate_compatibility.png "style=" border:0px; "/>



This article is from the "beautiful Dē‖java Question" blog, Please be sure to keep this source http://teny32.blog.51cto.com/8027509/1854631

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.