search
HomeWeb Front-endHTML TutorialDetailed explanation of the steps to use pushState and replaceState

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");

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;

需要注意的是,调用 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}

八、pushState()的用途

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

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

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

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

相信看了本文案例你已经掌握了方法,更多精彩请关注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!

Statement
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
What are self-closing tags? Give an example.What are self-closing tags? Give an example.Apr 27, 2025 am 12:04 AM

Self-closingtagsinHTMLandXMLaretagsthatclosethemselveswithoutneedingaseparateclosingtag,simplifyingmarkupstructureandenhancingcodingefficiency.1)TheyareessentialinXMLforelementswithoutcontent,ensuringwell-formeddocuments.2)InHTML5,usageisflexiblebutr

Beyond HTML: Essential Technologies for Web DevelopmentBeyond HTML: Essential Technologies for Web DevelopmentApr 26, 2025 am 12:04 AM

To build a website with powerful functions and good user experience, HTML alone is not enough. The following technology is also required: JavaScript gives web page dynamic and interactiveness, and real-time changes are achieved by operating DOM. CSS is responsible for the style and layout of the web page to improve aesthetics and user experience. Modern frameworks and libraries such as React, Vue.js and Angular improve development efficiency and code organization structure.

What are boolean attributes in HTML? Give some examples.What are boolean attributes in HTML? Give some examples.Apr 25, 2025 am 12:01 AM

Boolean attributes are special attributes in HTML that are activated without a value. 1. The Boolean attribute controls the behavior of the element by whether it exists or not, such as disabled disable the input box. 2.Their working principle is to change element behavior according to the existence of attributes when the browser parses. 3. The basic usage is to directly add attributes, and the advanced usage can be dynamically controlled through JavaScript. 4. Common mistakes are mistakenly thinking that values ​​need to be set, and the correct writing method should be concise. 5. The best practice is to keep the code concise and use Boolean properties reasonably to optimize web page performance and user experience.

How can you validate your HTML code?How can you validate your HTML code?Apr 24, 2025 am 12:04 AM

HTML code can be cleaner with online validators, integrated tools and automated processes. 1) Use W3CMarkupValidationService to verify HTML code online. 2) Install and configure HTMLHint extension in VisualStudioCode for real-time verification. 3) Use HTMLTidy to automatically verify and clean HTML files in the construction process.

HTML vs. CSS and JavaScript: Comparing Web TechnologiesHTML vs. CSS and JavaScript: Comparing Web TechnologiesApr 23, 2025 am 12:05 AM

HTML, CSS and JavaScript are the core technologies for building modern web pages: 1. HTML defines the web page structure, 2. CSS is responsible for the appearance of the web page, 3. JavaScript provides web page dynamics and interactivity, and they work together to create a website with a good user experience.

HTML as a Markup Language: Its Function and PurposeHTML as a Markup Language: Its Function and PurposeApr 22, 2025 am 12:02 AM

The function of HTML is to define the structure and content of a web page, and its purpose is to provide a standardized way to display information. 1) HTML organizes various parts of the web page through tags and attributes, such as titles and paragraphs. 2) It supports the separation of content and performance and improves maintenance efficiency. 3) HTML is extensible, allowing custom tags to enhance SEO.

The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools