Home  >  Article  >  Web Front-end  >  BOM history object

BOM history object

黄舟
黄舟Original
2017-02-10 09:55:461418browse

Previous words

The history object saves the history of the user's Internet access, starting from the moment the window is opened. Due to security considerations, developers cannot get the URL of the user's browser, but with the list of pages the user has visited, they can go back and forward without knowing the actual URL. This article will introduce in detail the history object in the BOM

length

The history.length property stores the number of URLs in the history record. Initially, this value is 1. If the current window has visited three URLs, the history.length property is equal to 3

Since the IE10+ browser returns 2 initially, there is a compatibility issue, so this value is not commonly used

history.length // 初始时,该值为1history.length // 访问三个网址后,该值为3

Jump method

The history object provides a series of methods that allow moving between browsing history, including go(), back( ) and forward()

【go()】

Use the go() method to jump arbitrarily in the user's history. This method receives a parameter, an integer value representing the number of pages to jump backward or forward. Negative numbers represent jumping backward (similar to the back button), positive numbers represent jumping forward (similar to the forward button)

history.go(-1history.go(1history.go(2

 go() method None Parameter, equivalent to history.go(0), you can refresh the current page

//刷新当前页面history.go();//刷新当前页面history.go(0);

【back()】

 back() method Used to imitate the browser's back button, equivalent to history.go(-1)

【forward()】

The forward() method is used to imitate the browser's forward button, equivalent to history.go(1)

//后退一页history.back()//前进一页history.forward()

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

[Note] When using history records, the page is usually loaded from the browser cache instead of re-asking the server to send a new web page

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 records in the browsing history. 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-browser does not support

[pushState()]

The 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 —— 状态对象是一个由pushState()方法创建的、与历史纪录相关的javascript对象。
当用户定向到一个新的状态时,会触发popstate事件。事件的state属性包含了历史纪录的state对象。如果不需要这个对象,此处可以填null
title —— 新页面的标题,但是所有浏览器目前都忽略这个值,因此这里可以填null
URL —— 这个参数提供了新历史纪录的地址。新URL必须和当前URL在同一个域,否则,pushState()将丢出异常。这个参数可选,如果它没有被特别标注,会被设置为文档的当前URL

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

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

After adding the above new record, the browser address bar immediately displays example.com/2.html, but it does not jump to 2.html, nor does it even check whether 2.html exists. Just become 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 only causes 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 and the old one are only different 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

// 报错history.pushState(null, null, 'https://twitter.com/hello');

【replaceState()】

history The parameters of the .replaceState method are exactly the same as the pushState method. The difference is that 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://www.php.cn/history.back()// url显示为http://www.php.cn/history.go(2)// url显示为http://www.php.cn/

【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 of the same document (that is, the history object) changes, the popstate event will be triggered

It should be noted that only pushState is called method or replaceState method, this event will not be triggered. It will only be triggered when the user clicks the browser's back button and forward button, or uses javascript to call the back(), forward(), and go() methods. 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)

window.onpopstate = function (event) {
  console.log('location: ' + document.location);
  console.log('state: ' + JSON.stringify(event.state));
};

The event.state in the above code 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;

 

往返缓存

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

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

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

【pageshow】

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

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

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

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

(function(){    var showCount = 0;
    window.onload = function(){
        console.log('loaded');
    }
    window.onpageshow = function(e){
        e = e || event;
        showCount ++;
        console.log(e.persisted,showCount + 'times');
    }
})();

  [注意]上面的例子使用了私有作用域,以防止变量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);
}


以上就是BOM之history对象的内容,更多相关内容请关注PHP中文网(www.php.cn)!



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