search
HomeWeb Front-endJS TutorialAnalysis of History object in js

This article mainly introduces the analysis of History objects in js. It has certain reference value. Now I share it with everyone. Friends in need can refer to it

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 created by the pushState() method , JavaScript objects related to historical records. 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');

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

[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 }

[popstate event]

Whenever the browsing history (i.e. history object) of the same document 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, this event will not be triggered

  使用的时候,可以为popstate事件指定回调函数。这个回调函数的参数是一个event事件对象,它的state属性指向pushState和replaceState方法为当前URL所提供的状态对象(即这两个方法的第一个参数)

  上面代码中的event.state,就是通过pushState和replaceState方法,为当前URL绑定的state对象

  这个state对象也可以直接通过history对象读取

 var currentState = history.state;

往返缓存

  默认情况下,浏览器会在当前会话(session)缓存页面,当用户点击“前进”或“后退”按钮时,浏览器就会从缓存中加载页面

  浏览器有一个特性叫“往返缓存”(back-forward cache或bfcache),可以在用户使用浏览器的“后退”和“前进”按钮时加快页面的转换速度。这个缓存中不仅保存着页面数据,还保存了DOM和javascript的状态;实际上是将整个页面都保存在了内存里。如果页面位于bfcache中,那么再次打开该页面时就不会触发load事件

  [注意]IE10-浏览器不支持

  【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中)

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

pushHistory()

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

相关推荐:

JavaScript中的History历史对象_基础知识

The above is the detailed content of Analysis of History object in js. 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
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Example Colors JSON FileExample Colors JSON FileMar 03, 2025 am 12:35 AM

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

8 Stunning jQuery Page Layout Plugins8 Stunning jQuery Page Layout PluginsMar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

What is 'this' in JavaScript?What is 'this' in JavaScript?Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

Improve Your jQuery Knowledge with the Source ViewerImprove Your jQuery Knowledge with the Source ViewerMar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 Mobile Cheat Sheets for Mobile Development10 Mobile Cheat Sheets for Mobile DevelopmentMar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

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

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools