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

May 07, 2018 pm 05:44 PM
Detailed explanation

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!

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of the mode function in C++ Detailed explanation of the mode function in C++ Nov 18, 2023 pm 03:08 PM

Detailed explanation of the mode function in C++ In statistics, the mode refers to the value that appears most frequently in a set of data. In C++ language, we can find the mode in any set of data by writing a mode function. The mode function can be implemented in many different ways, two of the commonly used methods will be introduced in detail below. The first method is to use a hash table to count the number of occurrences of each number. First, we need to define a hash table with each number as the key and the number of occurrences as the value. Then, for a given data set, we run

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of remainder function in C++ Detailed explanation of remainder function in C++ Nov 18, 2023 pm 02:41 PM

Detailed explanation of the remainder function in C++ In C++, the remainder operator (%) is used to calculate the remainder of the division of two numbers. It is a binary operator whose operands can be any integer type (including char, short, int, long, etc.) or a floating-point number type (such as float, double). The remainder operator returns a result with the same sign as the dividend. For example, for the remainder operation of integers, we can use the following code to implement: inta=10;intb=3;

Detailed explanation of the usage of Vue.nextTick function and its application in asynchronous updates Detailed explanation of the usage of Vue.nextTick function and its application in asynchronous updates Jul 26, 2023 am 08:57 AM

Detailed explanation of the usage of Vue.nextTick function and its application in asynchronous updates. In Vue development, we often encounter situations where data needs to be updated asynchronously. For example, data needs to be updated immediately after modifying the DOM or related operations need to be performed immediately after the data is updated. The .nextTick function provided by Vue emerged to solve this type of problem. This article will introduce the usage of the Vue.nextTick function in detail, and combine it with code examples to illustrate its application in asynchronous updates. 1. Vue.nex

Detailed explanation of php-fpm tuning method Detailed explanation of php-fpm tuning method Jul 08, 2023 pm 04:31 PM

PHP-FPM is a commonly used PHP process manager used to provide better PHP performance and stability. However, in a high-load environment, the default configuration of PHP-FPM may not meet the needs, so we need to tune it. This article will introduce the tuning method of PHP-FPM in detail and give some code examples. 1. Increase the number of processes. By default, PHP-FPM only starts a small number of processes to handle requests. In a high-load environment, we can improve the concurrency of PHP-FPM by increasing the number of processes

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of the linux system call system() function Detailed explanation of the linux system call system() function Feb 22, 2024 pm 08:21 PM

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

See all articles