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

Usage analysis of pushState and replaceState in H5

不言
Release: 2018-06-14 11:02:57
Original
1672 people have browsed it

This article mainly introduces relevant information about the usage of pushState and replaceState in H5. The content is quite good. I will share it with you now and give it as a reference.

1. Introduction

HTML5 introduces the history.pushState() and history.replaceState() methods, which can be added respectively and modification history entries. These methods are typically used in conjunction with window.onpopstate.

2. Example of pushState() method

Assume that the following JavaScript is executed in http://mozilla.org/foo.html Code:

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

This will cause the browser address bar to display http://mozilla.org/bar.html, but it will not cause the browser to load bar.html, or even check whether bar.html is exist.

Suppose the user now visits http://google.com and clicks the back button. At this time, the address bar will display http://mozilla.org/bar.html, and the page will trigger the popstate event. The event object state contains a copy of stateObj. The page itself is the same as foo.html, although its content may be modified in the popstate event.

If we click the back button again, the page URL will change to http://mozilla.org/foo.html, and the document object document will trigger another popstate event. This time the event object state object is null. The same here, returning does not change the content of the document. Although the document may change its content when receiving the popstate event, its content will still be consistent with the previous presentation.

3. pushState() method

pushState() requires three parameters: a state object, a title (currently used Ignore), and (optional) a URL. Let us explain the details of these three parameters:

State object - The state object state is a JavaScript object that creates a new history record through pushState () entry. Whenever the user navigates to a new state, the popstate event is fired, and the event's state property contains a copy of the history entry's state object.

Title — This parameter is currently ignored, but may be used in the future. Passing an empty string is safe here, but unsafe in the future. Alternatively, you can pass a short title for the jump state.

URL — This parameter defines the new historical URL record. Note that the browser will not load this URL immediately after calling pushState(), but it may load this URL under certain circumstances later, such as when the user reopens the browser. The new URL does not have to be an absolute path. If the new URL is a relative path, then it will be treated as relative to the current URL. The new URL must have the same origin as the current URL, otherwise pushState() will throw an exception. This parameter is optional and defaults to the current URL.

4. The difference between the pushState() method and setting the hash value

In a sense, calling pushState() and setting the window. location = "#foo" is similar, both will create and activate a new history record on the current page. But pushState() has the following advantages:

The new URL can be any URL that has the same origin as the current URL. And setting window.location only keeps the same file if you only modified the hash.

If necessary, a history record can be created without changing the URL. Setting window.location = "#foo"; will only create a new history item if the current hash is not #foo.

We can associate any data with new history items. With the hash value-based method, all relevant data must be encoded into a short string.

5. replaceState() method

The use of history.replaceState() is very similar to history.pushState(), the difference is that replaceState( ) modifies the current history item rather than creating a new one.

6. Popstate event

Whenever the active history entry changes, the popstate event will be on the corresponding window object trigger. If the currently active history entry was created by the history.pushState() method, or modified by the history.replaceState() method, the state property of the popstate event object contains a copy of the history entry's state object. .

We can also get the state directly on the history object, as follows:

var currentState = history.state;
Copy after login

It should be noted that calling history.pushState() or history.replaceState() will not trigger the popstate event. The opstate event will only be triggered under certain actions of the browser, such as clicking the back and forward buttons (or calling the history.back(), history.forward(), and history.go() methods in JavaScript).

7. Example of popstate event

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

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,条目索引为1
history.pushState({page: 2}, "title 2", "?page=2");    //添加并激活一个历史记录条目 http://example.com/example.html?page=2,条目索引为2
history.replaceState({page: 3}, "title 3", "?page=3"); //修改当前激活的历史记录条目 http://ex..?page=2 变为 http://ex..?page=3,条目索引为3
history.back(); // 弹出 "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // 弹出 "location: http://example.com/example.html, state: null
history.go(2);  // 弹出 "location: http://example.com/example.html?page=3, state: {"page":3}
Copy after login

8. Purpose of pushState()

王二使用 pushState() 主要是它可以监听到浏览器上的返回事件,这在移动端上也同样适用,参考如下一段代码(可以直接运行):

<body>
    <p>window.onpopstate可以监听到返回键事件</p>
    <script>
        history.pushState({}, ""); 
        window.onpopstate = function(event) {
            //这里可以监听到浏览器的返回事件,并做你想做的事情,
            //例如:跳转到另一个网页
            location.href = "https://www.baidu.com";
        };
    </script>
</body>
Copy after login

当然,用 window.onhashchange 也可以监听到浏览器上的返回事件,参考如下一段代码(可以直接运行):

<body>
    <p>window.onhashchange可以监听到返回键事件</p>
    <script>
        setTimeout(()=>{
            location.hash="a"
        },100);
        setTimeout(()=>{
            window.onhashchange = function(event) {
                location.href = "https://www.baidu.com";
            }
        },200);
    </script>
</body>
Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

HTML5表单验证的解析

关于HTML5 input placeholder 的颜色修改

The above is the detailed content of Usage analysis of pushState and replaceState in H5. For more information, please follow other related articles on the PHP Chinese website!

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