Home Operation and Maintenance Safety How to use the History object in javascript

How to use the History object in javascript

Jun 02, 2023 pm 04:55 PM
javascript history

length

The history.length property stores the number of URLs in the history. Initially, this value is 1. Since the IE10 browser returns 2 initially, there is a compatibility issue, so this value is not commonly used

Jump method

go(), back() and forward()

If the moved position exceeds the boundary of the access history, the above three methods will not report an error, but fail silently

[Note] When using history records, the page is usually loaded from the browser cache. Instead of asking the server to send a new web page again. Does not trigger onload

Add and modify records

HTML5 adds two new methods to the history object, history.pushState() and history.replaceState(), which are used to add and modify the browsing history Record. The state attribute is used to save the record object, and the popstate event is used to monitor changes in the history object

 [Note] IE9 does not support

 [pushState()]

  History.pushState () method adds a state to the browser history. The pushState() method takes three parameters: a state object, a title (now ignored), and an optional URL address

  history.pushState(state, title, url);

  State object - The state object is a JavaScript object created by the pushState() method and related to the history record. When the user is directed to a new state, the popstate event is triggered. The event's state property contains the history's state object. If you don’t need this object, you can fill in null

Title - the title of the new page, but all browsers currently ignore this value, so you can fill in null

here URL - this The parameter provides the address of the new history record. The new URL must be in the same domain as the current URL, otherwise pushState() will throw an exception. This parameter is optional. If it is not specifically marked, it will be set to the current URL of the document

. Assuming that the current URL is example.com/1.html, use the pushState method to add it to the browsing record (history object). A new record

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

After adding the new record above, the browser address bar immediately displays example.com/2.html, but it will not jump to 2.html, or even check 2.html. If it exists, it just becomes the latest entry in your browsing history. If you visit google.com at this time, and then click the back button, the URL of the page will display 2.html, but the content will still be the original 1.html. Click the rewind button again, and the url will display 1.html, with the content unchanged

In short, the pushState method will not trigger a page refresh, but will only cause the history object to change and the displayed address in the address bar to change

If the url parameter of pushState sets a new anchor value (i.e. hash), the hashchange event will not be triggered, even if the new URL is only different from the old one in hash

If set If a cross-domain URL is specified, an error will be reported. The purpose of this design is to prevent malicious code from making users think they are on another website

 [replaceState()]

The parameters of the history.replaceState method are exactly the same as the pushState method, with the difference The replaceState() method will modify the current history entry instead of creating a new entry

Assume that the current web page is example.com/example.html

history.pushState({page: 1}, 'title 1', '?page=1');
history.pushState({page: 2}, 'title 2', '?page=2');
history.replaceState({page: 3}, 'title 3', '?page=3');
history.back()
// url显示为http://example.com/example.html?page=1
history.back()
// url显示为http://example.com/example.html
history.go(2)
// url显示为http://example.com/example.html?page=3
Copy after login

【state】

The history.state property returns the state object of the current page

history.pushState({page: 1}, 'title 1', '?page=1');
history.state// { page: 1 }
Copy after login

 [popstate event]

Whenever the browsing history of the same document (that is, the history object) changes, the popstate event will be triggered

[Note] It should be noted that just calling the pushState method or replaceState method will not trigger this event. Only the user clicks the browser back button and forward button, or uses javascript to call back(), forward() , go() method will only be triggered. In addition, this event only targets the same document. If the browsing history is switched and different documents are loaded, the event will not be triggered.

When used, you can specify a callback function for the popstate event. The parameter of this callback function is an event event object, and its state attribute points to the state object provided by the pushState and replaceState methods for the current URL (that is, the first parameter of these two methods)

In the above code event.state is the state object bound to the current URL through the pushState and replaceState methods

This state object can also be read directly through the history object

  var currentState = history.state;
Copy after login

round trip cache

By default, the browser will cache the page in the current session. When the user clicks the "Forward" or "Back" button, the browser will load the page from the cache.

The browser has a feature Called "back-forward cache" (bfcache), it can speed up page conversions when users use the browser's "back" and "forward" buttons. This cache not only saves page data, but also saves the state of DOM and javascript; in fact, the entire page is saved in memory. If the page is located in bfcache, the load event will not be triggered when the page is opened again

 [Note] IE10-the browser does not support

 [pageshow]

  pageshow事件在页面加载时触发,包括第一次加载和从缓存加载两种情况。如果要指定页面每次加载(不管是不是从浏览器缓存)时都运行的代码,可以放在这个事件的监听函数

  第一次加载时,它的触发顺序排在load事件后面。从缓存加载时,load事件不会触发,因为网页在缓存中的样子通常是load事件的监听函数运行后的样子,所以不必重复执行。同理,如果是从缓存中加载页面,网页内初始化的JavaScript脚本(比如DOMContentLoaded事件的监听函数)也不会执行

  [注意]虽然这个事件的目标是document,但必须将其事件处理程序添加到window

  pageshow事件有一个persisted属性,返回一个布尔值。页面第一次加载时或没有从缓存加载时,这个属性是false;当页面从缓存加载时,这个属性是true

  [注意]上面的例子使用了私有作用域,以防止变量showCount进入全局作用域。如果单击了浏览器的“刷新”按钮,那么showCount的值就会被重置为0,因为页面已经完全重新加载了

  【pagehide】

  与pageshow事件对应的是pagehide事件,该事件会在浏览器卸载页面的时候触发,而且是在unload事件之前触发。与pageshow事件一样,pagehide在document上面触发,但其事件处理程序必须要添加到window对象

  [注意]指定了onunload事件处理程序的页面会被自动排除在bfcache之外,即使事件处理程序是空的。原因在于,onunload最常用于撤销在onload中所执行的操作,而跳过onload后再次显示页面很可能就会导致页面不正常

  pagehide事件的event对象也包含persisted属性,不过其用途稍有不同。如果页面是从bfcache中加载的,那么persisted的值就是true;如果页面在卸载之后会被保存在bfcache中,那么persisted的值也会被设置为true。因此,当第一次触发pageshow时,persisted的值一定是false,而在第一次触发pagehide时,persisted就会变成true(除非页面不会被保存在bfcache中)

window.onpagehide = function(e){
e = e || event;
console.log(e.persisted);
}
Copy after login

使用方法:

1、取消默认的返回操作

function pushHistory(){
 var state = {
    title: "title",
    url: "#"   
  }
 window.history.pushState(state, "title", "#");  
}

pushHistory()
Copy after login

2、history.js用于兼容html4,也可以监听pushState与replaceSate

The above is the detailed content of How to use the History object in javascript. 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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles