The body ~
An overview of the
The browser window has a History object to save the browsing history.
If the current window has visited three urls, the history object contains three, and the history.length property is equal to 3.
history.length // 3
The History object provides a series of methods that allow you to move between browsing histories.
Back () : Moves to the previous page, equivalent to the browser’s back key.
Forward () : Moves to the next page, equivalent to the browser’s forward key.
Go () : Takes an integer as an argument and moves to the page specified by that integer, such as go(1) equals forward() and go(-1) equals back().
history.back();
history.forward();
history.go(-2);
If you move beyond the boundaries of access history, these three methods do not fail, but fail silently.
History.go (0) is equivalent to refreshing the current page.
history.go(0);
The common “back to previous page” link looks like this.
document.getElementById(‘backLink’).onclick = function () {
window.history.back();
}
Note that when you go back to the previous page, the page is usually loaded from the browser cache, rather than re-asking the server to send a new page.
history.pushState()
HTML5 has added two new methods to the history object, history.pushstate () and history.replacestate (), for adding and modifying records to the browsing history.
if (!! (window.history && history.pushState)){
// Support the History API
} else {
/ / does not support
}
The code above can be used to check whether the current browser supports the History API. If not, consider using the Polyfill library history.js.
The history.pushState method takes three arguments, in order:
State: a state object associated with the specified url that is passed in a callback function when the POPState event is triggered. If this object is not needed, null can be used here.
Title: The title of the new page, but all browsers currently ignore this value, so null can be filled 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, we use the pushState method to add a new record to the history object.
var stateObj = { foo: ‘bar’ };
history.pushState(stateObj, ‘page 2’, ‘2.html’);
When you add this new record, 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 latest record in your browsing history. Suppose you go to Google.com and click the back button. The url of the page displays 2.html, but the content is still 1.html. If you click the back button again, the URL will display 1.html, unchanged.
In summary, pushState does not trigger a page refresh, but only causes the history object to change and the address bar to respond.
If the URL argument to pushState sets a new anchor value (that is, a hash), the Hashchange event is not triggered. If a cross-domain URL is set, an error is reported.
/ / an error
history.pushState(null, null, ‘https://twitter.com/hello’);
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 another site.
history.replaceState()
The history.replaceState method takes exactly the same parameters as the pushState method, except that it modifies the current record in the browsing history.
Assume 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 displayed as http://example.com/example.html?page=1
history.back()
/ / url displayed as http://example.com/example.html
history.go(2)
/ / url displayed as http://example.com/example.html?page=3
The history state property
The history.state property returns the state object for the current page.
history.pushState({page: 1}, ‘title 1’, ‘? page=1’);
history.state
// { page: 1 }
Popstate event
The PopState event is triggered every time the browsing history (that is, the history object) of the same document changes.
Note that this event is not triggered by calling the pushState or replaceState methods, but only when the user clicks the browser’s back and forward buttons, or calls the back, forward, or Go methods 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. The argument to this 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).
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));
});
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;
Note that when the page first loads, Chrome and Safari (Webkit core) will fire the PopState event after the Load event, while Firefox and Internet Explorer will not.
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);
URLSearchParams has the following methods to manipulate a parameter.
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”
URLSearchParams also has three methods that iterate over all parameters.
Keys () : Iterate over all parameter names
Values () : traverses all parameter values
Entries () : Traverses key-value pairs for 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
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);
}
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
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(…)
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”
URLSearchParams can also be used in conjunction with the URL interface.
var url = new URL(location);
var foo = url.searchParams.get(‘foo’) || ‘somedefault’;