The window.history property points to the History object, which represents the browsing history of the current window.

The History object holds the url of all pages visited by the current window.

The following code indicates that the current window has visited a total of three urls.

window.history.length / / 3
Copy the code

For security reasons, the browser does not allow the script to read these addresses, but does allow navigation between them.

// Go back to the previous url
history.back()

/ / is equivalent to
history.go(-1)
Copy the code

The “forward” and “back” buttons on the browser toolbar actually operate on the History object.

attribute

  • History.length: Number of urls visited by the current window (including the current page)
  • History.state: state value at the top of the History stack (see below)

methods

Back (), forward(), go()

These three methods are used to move through history

  • History.back() : Move to the previous url, equivalent to hitting the browser’s back button. This method has no effect on the first url visited.

  • History.forward() : Moves to the next url, equivalent to clicking the browser’s forward button. This method has no effect on the last url visited.

  • History.go() : takes an integer as an argument and moves to the url specified by the argument based on the current url, for example, go(1) equals forward() and go(-1) equals back(). If the parameter exceeds the actual url range, the method has no effect. If no parameter is specified, the default parameter is 0, which means refreshing the current page

  history.back();
  history.forward();
  history.go(-2);
Copy the code

History.go (0) is equivalent to refreshing the current page.

  history.go(0);
Copy the code

Note that when you move to a previously visited page, the page is usually loaded from the browser cache, rather than re-asking the server to send a new page.

pushState()

The history.pushState () method is used to add a record to the History.

window.history.pushState(state, title, url)
Copy the code

The method accepts three parameters, in order:

  • State: A state object associated with the added record, primarily for popState events. When this event is fired, the object is passed a callback function. That is, the browser will serialize the object and keep it locally, so it can be retrieved when the page is reloaded. If this object is not needed, null can be used here.

  • Title: Title of the new page. However, all browsers now ignore this parameter, so you can fill in the blank string here.

  • Url: The new url must be in the same domain as the current page. The browser’s address bar will display the url.

Assuming the current url is example.com/1.html, use the pushState() method to add a new record to the History object.

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

When a new record is added, the browser’s address bar immediately shows example.com/2.html, but it doesn’t jump to 2.html or even check for the existence of 2.html, it just becomes the most recent record in your browsing history. Enter a new address in the address bar (e.g. Google.com) and click the back button. The page URL will display 2.html. You click the back button again and the URL will display 1.html.

In summary, the pushState() method does not trigger a page refresh, but only causes the History object to change and the address bar to respond.

After using this method, you can read out the state object with the history.state property.

var stateObj = { foo: 'bar' };
history.pushState(stateObj, 'page 2'.'2.html');
history.state // {foo: "bar"}
Copy the code

If the URL parameter to pushState sets a new anchor value (that is, a hash), the Hashchange event is not triggered. Conversely, if the anchor value of the URL changes, a browsing record is created in the History object.

If the pushState() method sets a cross-domain URL, an error is reported.

/ / an error
// The current website is http://example.com
history.pushState(null.' '.'https://twitter.com/hello');
Copy the code

In the code above, pushState attempts to insert a cross-domain URL, causing an error. This is designed to prevent malicious code from making users think they are on a different site, since it does not lead to a page jump.

replaceState()

The history.replacEstate () method modifies the current record of the History object, just as the pushState() method does.

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

history.pushState({page: 1}, 'title 1', '? Page = 1 ') / / URL to http://example.com/example.html?page=1history.pushState ({2} page:, 'the title 2', '? Page = 2 '); / / URL to http://example.com/example.html?page=2history.replaceState ({3} page:, 'title 3', '? Page = 3); / / URL to http://example.com/example.html?page=3history.back () / / URL to display http://example.com/example.html?page=1history.back () / / URL for http://example.com/example.htmlhistory.go (2) / / URL to display http://example.com/example.html?page=3Copy the code

Popstate event

The PopState event is triggered every time the browsing history (that is, the history object) of the same document changes.

Note that calling the pushState() or replaceState() method alone does not trigger this event, only if the user clicks the browser back button and forward button, Or when the history.back (), history.forward (), and history.go () methods are called using JavaScript. In addition, this event is only for the same document and will not be triggered if a switch in browsing history results in a different document being loaded.

When used, you can specify a callback function for popState events.

window.onpopstate = function (event) {  console.log('location: ' + document.location);  console.log('state: ' + JSON.stringify(event.state)); };// or window.addeventListener (' popState ', function(event) {console.log('location: '+ document.location); console.log('state: ' + JSON.stringify(event.state)); });
Copy the code

The argument to the callback function is an Event event object whose state property points to the state object provided by the pushState and replaceState methods for the current URL (that is, the first argument to both methods). The event.state in the above code is the state object that is bound to the current URL using the pushState and replaceState methods.

The state object can also be read directly from the history object.

var currentState = history.state;
Copy the code

Note that the browser does not trigger the PopState event when the page first loads.

URLSearchParams API

The URLSearchParams API is used to process the query string in the URL, the part after the question mark. Browsers that do not deploy this API can use the url-search-params shim library.

var paramsString = 'q=URLUtils.searchParams&topic=api';
var searchParams = new URLSearchParams(paramsString);
Copy the code
  • Has () : Returns a Boolean value indicating whether a parameter is present

  • Get () : Returns the first value of the specified argument

  • GetAll () : Returns an array of all the values of the specified arguments

  • Set () : Sets specified parameters

  • Delete () : deletes the specified parameter

  • Append () : Appends a key-value pair to the query string

  • ToString () : Returns the entire query string

var paramsString = 'q=URLUtils.searchParams&topic=api';
var searchParams = new URLSearchParams(paramsString);

searchParams.has('topic') // true
searchParams.get('topic') // "api"
searchParams.getAll('topic') // ["api"]

searchParams.get('foo') // null, note that Firefox returns an empty string
searchParams.set('foo'.2);
searchParams.get('foo') / / 2

searchParams.append('topic'.'webdev');
searchParams.toString() // "q=URLUtils.searchParams&topic=api&foo=2&topic=webdev"

searchParams.append('foo'.3);
searchParams.getAll('foo') / / [2, 3]

searchParams.delete('topic');
searchParams.toString() // "q=URLUtils.searchParams&foo=2&foo=3"
Copy the code

URLSearchParams also has three methods that iterate over all parameters.

  • keys(): Traverses all parameter names
  • values(): Traverses all parameter values
  • entries(): Traverses the key-value pairs of all parameters

The above three methods all return Iterator objects.

var searchParams = new URLSearchParams('key1=value1&key2=value2');

for (var key of searchParams.keys()) {
  console.log(key);
}
// key1
// key2

for (var value of searchParams.values()) {
  console.log(value);
}
// value1
// value2

for (var pair of searchParams.entries()) {
  console.log(pair[0] +', '+ pair[1]);
}
// key1, value1
// key2, value2
Copy the code

In Chrome, the URLSearchParams instance is itself an Iterator and returns the same value as the Entries method. So, we could write it like this.

for (var p of searchParams) {
  console.log(p);
}
Copy the code

Here is an example of replacing the current URL.

/ / URL: https://example.com?version=1.0
var params = new URLSearchParams(location.search.slice(1));
params.set('version'.2.0);

window.history.replaceState({}, ' '.`${location.pathname}?${params}`);
/ / URL: https://example.com?version=2.0
Copy the code

URLSearchParams instances can be sent as POST data, and all data is URL-encoded.

let params = new URLSearchParams();
params.append('api_key'.'1234567890');

fetch('https://example.com/api', {
  method: 'POST'.body: params
}).then(...)
Copy the code

The searchParams property of the DOM’s A element node is an instance of URLSearchParams.

var a = document.createElement('a');
a.href = 'https://example.com?filter=api';
a.searchParams.get('filter') // "api"
Copy the code

URLSearchParams can also be used in conjunction with the URL interface.

var url = new URL(location);
var foo = url.searchParams.get('foo') | |'somedefault';
Copy the code

Transport links