Home > Web Front-end > H5 Tutorial > body text

HTML5 history new features pushState, replaceState and the difference between the two _html5 tutorial skills

WBOY
Release: 2016-05-16 15:46:05
Original
1588 people have browsed it

The window object in the DOM provides access to browser history through the window.history method, allowing you to move forward and backward in the user's access record.

Starting with HTML5, we can start manipulating this history stack.

1. History

Use the back(), forward(), and go() methods to move forward in the user's history and Back

Forward and Back

Back:


Copy code
The code is as follows:

window.history.back();

This method will act like the user clicked the back key on the browser toolbar.

Similarly, the following method can also be used to generate user forward behavior:


Copy code
The code is as follows:

window.history.forward();

Move to a specific position in the history

You can use go() Method loads a specific page from session history.

Move one page backward:


Copy the code
The code is as follows:

window.history.go(-1);

Move forward one page:


Copy code
The code is as follows:

window.history.go(1);

Similarly, you can move forward or Go back multiple pages.

You can also find the total number of pages in the history stack by checking the length property of the browser history.


Copy code
The code is as follows:

var numberOfEntries = window.history .length;

Note: IE supports passing URL parameters to the go() method.

2. Add and modify history entities

Introduced since Gecko2 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)

HTML5 introduced the two methods history.pushState() and history.replaceState(), which allow adding and modifying history entities. At the same time, these methods will work with the window.onpostate event.

Use the history.pushState() method to modify the referrer. This method can be used in the http header created for the xmlhttpRequest object after modifying the state. This referrer will be the URL of the document when creating the XMLHttpRequest.

pushState is used to add the record of the current page to history, while replaceState is used exactly the same as pushState. The only difference is that it is used to modify the record of the current page in history.

Example

Suppose http://mozilla.org/foo.html page executes JS


Copy code
The code is as follows:

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

This method will cause the URL address bar to display http://mozilla.org/bar.html, but the browser will not load the bar.html page, even if this page exists.

Now again assume the user continues to http://google.com and clicks back. At this time, the url address bar will be, http://mozilla.org/bar.html, and the page will get the popstate event (chrome). This state object will contain a copy of stateObj. This page looks like foo.html.

At this time, we click back again, the URL will become http://mozilla.org/foo.html, and the document will get another popstate event and a null state object. This return action does not change the content of the document. (Maybe try loading...chrome after a while)

pushState method

pushState() has three parameters: state object, title (now is ignored and not processed), URL (optional). Specific details:

· state object – The state object is a JavaScript object, which is related to the new history entity created by the pushState() method. Used to store information about the entry you want to insert into the history. State object can be any Json string. Because Firefox will use the user's hard disk to access the state object, the maximum storage space of this object is 640k. If it is greater than this value, the pushState() method will throw an exception. If you really need more space for storage, use local storage.

· title—firefox now ignores this parameter, although it may be used in the future. The safest way to use it now is to pass an empty string to prevent future modifications. Or you can pass a short title to represent state

· URL—This parameter is used to pass the URL of the new history entity. Note that the browser will not load this URL after calling the pushState() method. But maybe it will try to load this URL after a while. For example, after the user restarts the browser, the new URL may not be an absolute path. If it is a relative path, it will be relative to the existing url. The new url must be in the same domain as the existing url, otherwise pushState() will throw an exception. This parameter is optional. If it is empty, it will be set to the current URL of the document.

In a sense, calling the pushState() method is very similar to setting window.location = "#foo". Both of them will create and activate another history entity associated with the current document, but pushState() )There are also some advantages:

The new url can be any url in the same domain as the current url. In contrast, if you only set the hash, window.location will remain in the same document.

You don’t need to modify the url if you don’t need to. In contrast, setting window.location = "#foo"; only generates a new history entity. If your current hash is not #foo

you can associate arbitrary data with your new history entity. Using hash-based methods, all relevant data needs to be encoded into a short string.

Note that the pushState() method will not cause the hashchange time to occur, even if the old and new URLs only have different hashes.

replaceState() method

history.replaceState() is used much like pushState(), except that replaceState() is used to modify the current history entity instead of creating a new one. This method is sometimes useful. When you need to update a state object or the current history entity in response to certain user actions, you can use it to update the state object or the URL of the current history entity.

popstate event

When the history entity is changed, the popstate event will occur. If the history entity is generated by pushState and replaceState methods, the state attribute of the popstate event will contain a copy of the state object from the history entity

For details, see window.onpopstate

Read the current state

Read existing state

When the page loads, it may have a non-empty state object. This may happen when the user restarts the browser after the page sets a state object (using pushState or replaceState). When the page reloads, the page will receive the onload event, but there will be no popstate event. However, if you read the history.state property, you will get the state object after the popstate event occurs
var currentState = history.state;
Browsers: Tested and Working In

HTML5 Browsers

Chrome 8,9,10
Firefox 4
Safari 5
Opera 11
Safari iOS 4.3
HTML4 Browsers

IE6,7,8,9
Firefox 3
Opera 10
Safari 4
Safari iOS prior to version 4.3

pushState and replaceState Difference

history.pushState(state, title, url)

--------------------- -------------------------------------------------- ---------

Add the current URL and history.state to history, and replace the current one with the new state and URL. It will not cause the page to refresh.

state: State information corresponding to the URL to be jumped to.

title: 전달할 필요가 없습니다.

url: 이동할 URL 주소, 도메인을 넘을 수 없습니다.

history.replaceState(상태, 제목, URL)

------------- ------------------------------------------------ --

현재 상태와 URL을 새 것으로 바꿉니다. 페이지가 새로 고쳐지지는 않습니다.

state: 이동할 URL에 해당하는 상태 정보입니다.

제목: 전달할 수 없음

url: 이동할 URL 주소, 도메인을 넘을 수 없음.

------------------------------- ------ ----------

그런 것 같아요 둘 사이에는 차이가 없지만 실제로 가장 큰 차이점은 pushState가 기록 레코드를 추가하는 반면, replacementState는 그렇지 않다는 것입니다.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!