Home > Web Front-end > HTML Tutorial > Detailed explanation of the steps to use pushState and replaceState

Detailed explanation of the steps to use pushState and replaceState

php中世界最好的语言
Release: 2018-05-07 17:44:19
Original
2774 people have browsed it

This time I will bring you a detailed explanation of the steps for using pushState and replaceState. What are the precautions for using pushState and replaceState? Here is a practical case, let’s take a look.

1. Introduction

HTML5 introduces the history.pushState() and history.replaceState() methods, which can add and modify history respectively. Record entry. These methods are typically used in conjunction with window.onpopstate.

2. Example of pushState() method

Assume that the following is executed in http://mozilla.org/foo.htmlJavaScript 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, not even Will check if bar.html exists.

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 ignored), and (optionally) a URL. Let us explain the details of these three parameters:

State object - The state object state is a JavaScript object, created by pushState () history 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

每当处于激活状态的历史记录条目发生变化时,popstate 事件就会在对应window对象上触发。 如果当前处于激活状态的历史记录条目是由history.pushState()方法创建,或者由history.replaceState()方法修改过的, 则popstate事件对象的state属性包含了这个历史记录条目的state对象的一个拷贝。

我们也可以直接在history对象上获取state,如下:

var currentState = history.state;
Copy after login

需要注意的是,调用 history.pushState() 或者 history.replaceState() 不会触发 popstate 事件。 opstate事件只会在浏览器某些行为下触发, 比如点击后退、前进按钮(或者在JavaScript中调用history.back()、history.forward()、history.go()方法)。

七、popstate 事件的例子

假如当前网页地址为 http://example.com/example.html ,则运行下述代码后:

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

八、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中文网其它相关文章!

推荐阅读:

H5+WebWorkers多线程开发使用详解

CSS3二级导航菜单制作步骤详解

The above is the detailed content of Detailed explanation of the steps to use pushState and replaceState. 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