Do you really know the history object in BOM, BOMhistory object?

Source: Internet
Author: User

Do you really know the history object in BOM, BOMhistory object?

Previous

The history object stores the user's online history, starting from the moment the window is opened. Due to security considerations, developers cannot obtain the URL of the user's browser. However, by using the page list accessed by the user, you can move back and forward without knowing the actual URL. This topic describes the history object in BOM in detail.

Length

The history. length attribute stores the number of historical URLs. Initially, this value is 1. If three URLs are accessed in the current window, the history. length attribute is equal to 3.

The IE10 + browser returns 2 at the beginning, which causes compatibility issues. Therefore, this value is not commonly used.

History. length // At the beginning, the value is 1 history. length // 3 after three URLs are accessed

Redirect Method

The history Object provides a series of methods that can be moved between browsing history, including go (), back (), and forward ()

Go ()

You can use the go () method to jump to any of your historical records. This method receives a parameter, indicating an integer of the number of pages that are redirected backward or forward. A negative number indicates a backward jump (similar to a backward button), and a positive number indicates a forward jump (similar to a forward button)

// Return a page of history. go (-1) // advance a page of history. go (1); // advance two pages of history. go (2 );

When the go () method has no parameters, it is equivalent to history. go (0) and can refresh the current page.

// Refresh the current page history. go (); // refresh the current page history. go (0 );

Back ()

The back () method is used to simulate the browser's back button, which is equivalent to history. go (-1)

Forward ()

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

// Return history. back () // return history. forward ()

If the location to be moved exceeds the access history boundary, the above three methods do not report an error, but fail silently.

[Note] when using history records, pages are usually loaded from the browser cache, instead of re-requesting the server to send new pages.

Add Change Record

HTML5 adds two new methods to the history object, history. pushState () and history. replaceState (), to add and modify records in the browsing history. The state attribute is used to save the record object, while the popstate event is used to listen for changes to the history object.

[Note] IE9-not supported by browsers

PushState ()

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

history.pushState(state, title, url);

State object-- A State object is a javascript Object created by the pushState () method related to historical records. A popstate event is triggered when the user directs to a new state. The state attribute of the event contains the state object of the historical record. If you do not need this object, enter null here.
Title-- The title of the new page, which is ignored by all browsers currently. Therefore, null can be entered here.
URL-- This parameter provides the address of the new history. 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

Assume that the current website address is example.com/1.html. Use pushstate to add a new record to the page view (history object ).
Var stateObj = {foo: 'bar '};
History. pushState (stateObj, 'page 2', '2.html ');

After the new record is added, the browser address bar immediately displays. . Click "back" and click "back". The URL will display 1.html, And the content will remain unchanged.

In short, the pushState method does not trigger page refresh, but changes the history object and the display address in the address bar.

If the pushState url parameter is set with a new anchor value (hash), The hashchange event is not triggered, even if the new URL is different from the old one

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

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

ReplaceState ()

The parameters of the history. replaceState method are the same as those of the pushState method. The difference is that the replaceState () method modifies the entries in the current history rather than creating new entries.

Assume that the current webpage 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 () // The url is displayed as a http://example.com/example.html? Page = 1 history. back () // The url is displayed as the http://example.com/example.html history. go (2) // The url is displayed as the 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

A popstate event is triggered whenever the browsing history of the same document (that is, the history Object) changes.

It should be noted that only the pushState method or the replaceState method is called, and this event is not triggered. Only the user clicks the browser backward button and forward button, or calls back () and forward () using javascript () and go () method. In addition, this event is only for the same document. If the browsing history is switched, different documents will be loaded, and this event will not be triggered.

You can specify a callback function for the popstate event. The callback function parameter is an event object. 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 the two methods)

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

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

Round-trip Cache

By default, the browser caches the page in the current session. When you click "Forward" or "back", the browser loads the page from the cache.

The browser has a feature called back-forward cache or bfcache, which can speed up page conversion when you use the browser's "back" and "forward" buttons. This cache not only saves page data, but also saves the DOM and javascript states. In fact, the whole page is saved in the memory. If the page is in bfcache, the load event is not triggered when the page is opened again.

[Note] IE10-not supported by browsers

Pageshow

The pageshow event is triggered when a page is loaded, including loading for the first time and loading from the cache. If you want to specify the code that runs every time the page is loaded (whether it is cached from the browser or not), you can place it in the event listening function.

The trigger sequence of the first load event is after the load event. When loading from the cache, the load event will not be triggered, because the cache of the webpage is usually like the running status of the load event listening function, so you do not have to execute it repeatedly. Similarly, if the page is loaded from the cache, the JavaScript script initialized in the webpage (such as the DOMContentLoaded event listening function) will not be executed.

[Note] Although this event is intended for document, it must be added to the window

The pageshow event has a persisted attribute and returns a Boolean value. When the page is loaded for the first time or is not loaded from the cache, this attribute is false; when the page is loaded from the cache, this attribute is 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');  }

[Note] the preceding example uses a private scope to prevent the variable showCount from entering the global scope. If you click the "refresh" button in the browser, the value of showCount is reset to 0 because the page has been completely reloaded.

Pagehide

The pagehide event corresponds to the pageshow event, which is triggered when the browser uninstalls the page and before the unload event. Like the pageshow event, pagehide is triggered on the document, but its event handler must be added to the window object.

[Note] the page with the onunload Event Handler specified is automatically excluded from the bfcache, even if the event handler is empty. The reason is that onunload is most often used to cancel the operations performed in onload, and skipping onload and displaying the page again may cause the page to be abnormal.

The event object of the pagehide event also contains the persisted attribute, but its usage is slightly different. If the page is loaded from bfcache, the value of persisted is true. If the page is saved in bfcache after being detached, the value of persisted is set to true. Therefore, when pageshow is triggered for the first time, the value of persisted must be false. When pagehide is triggered for the first time, persisted will become true (unless the page is not saved in bfcache)

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

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.