This is the 28th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
The History object
The History object is an object in the browser model, obtained through the window.history property, and represents the browsing History of the current window.
In a browser window, the addresses of all visited pages are saved in the History object.
A change in the anchor value of the URL also creates a browsing record in the History object.
Cannot read browsed specific address through JS
For security reasons, browsers do not allow JS to read specific addresses, but can navigate between addresses. Such as back, forward, go, etc.
length
和 state
attribute
history.length
: Number of urls visited by the current window (including the current page).history.state
: History Indicates the state value at the top of the stack, that is, the current state, usually undefined and not set.
History.back () rewinds to the previous page
History.back () returns to the previous page viewed. This is the most common fallback feature in browsers.
History.forward () advances to the next url
History.forward () moves to the next url, and the current window displays the next page. Forward function.
History.go (num) moves to the url page based on the current location
The history.go() argument is an integer based on the location of the current url. For example, go(1) equals forward(); Go (-1) equals back().
Go (-2) moves to the second url after the current page. If you specify a parameter that exceeds the actual range, it will have no effect.
No parameters are specified, or parameters are specified0
, the current page is refreshed.
History.pushstate () Adds a record to the browsing history.
Window. The history. PushState (state, the title, url) :
state
: a state object associated with the added recordpopstate
Event to pass in a callback function. It is a separate object that can be used when the page is reloaded. If no, set it tonull
Can.title
: The title of the new page, usually does not work (such as FireFox), just fill in the blank string.url
: new url, must be in the same domain as the current page. That is,PushState does not allow adding cross-domain addresses.
History.pushstate () adds a record, which is displayed in the browser address bar, but does not jump to the page, just as a recent record in the browsing history.
That is, pushState() does not trigger a page entry refresh. After this method is executed, the incoming state value can be read out through history.state.
PushState does not allow adding cross-domain urls. This is done to prevent malicious code from making users think they are on another site, since pushState() does not cause a page jump.
History.replacestate () modifies the current record
History.replacestate () is used the same as pushState(), except that replaceState() is used to modify the current record.
For example, the current web address is example.com/example.html. After you perform the following operations, the URL in the address bar is displayed as:
history.pushState({page: 1}, 'title 1'.'? page=1')
/ / URL displayed as http://example.com/example.html?page=1
history.pushState({page: 2}, 'title 2'.'? page=2');
/ / URL displayed as http://example.com/example.html?page=2
history.replaceState({page: 3}, 'title 3'.'? page=3');
/ / URL displayed as http://example.com/example.html?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
Copy the code
Popstate and Hashchange events
popstate
The event
The PopState event is emitted when the browsing history of the same document changes without refreshing into the changed URL.
Note that changes in the browsing history of the same document will not trigger this event if a document is loaded (a different document is loaded or the current document is reloaded). That is,
The PopState event is triggered when the browsing history changes and the page is not loaded. Also, the browser does not fire the PopState event when the page (re) loads and refreshes, including the first load.
window.addEventListener('popstate'.function(e){
console.log('location: ' + document.location);
console.log('state: ' + JSON.stringify(event.state));
})
Copy the code
The state property of the event event object in the callback refers to the state object (the first argument) in the pushState and replaceState methods. This state object can also be obtained through history.state.
When will the PopState event be triggered?
As mentioned above, the PopState event only fires if the browser does not load the page. If you change the HASH of the URL using the history.pushstate ()/ history.replacestate () method, you can change the URL without loading the page.
That is, after the page has loaded, Page forward or backward (or history.back(), history.forward(), history.go())), or modification after calling history.pushState()/ history.replacestate () The POPState event is triggered only when the URL hash.
To simulate the popState event, you can modify the URL address or hash value in the browser record address bar to test the popState event.
hashchange
The event
Hash is what follows the # in the URL (including #). A hashchange event is an event that listens for changes in the hash value of a URL.
A hash can also be called a fragment identifier.
window.addEventListener('hashchange'.function() {
console.log('The hash has changed! ');
if (location.hash === '#cool-feature') {
console.log("You're visiting a cool feature!"); }},false);
Copy the code
The hashchange event object contains the URL before and after the hashchange: oldURL and newURL properties.
window.addEventListener('hashchange'.function(e) {
console.log(e.oldURL);
console.log(e.newURL);
}, false);
Copy the code
Popstate and Hashchange event sequence
Below, test the order in which popState and Hashchange events occur by changing the hash value.
window.location.href+='#cool-feature'
Copy the code
You can also test the forward and back keys in your browser. Here is the output order of these two events:
Location: http://127.0.0.1:5500/code/popstateAndhashchange.html#cool-feature
state: null
The hash has changed!
You're visiting a cool feature!
Copy the code
When a hash is modified, the popState event is triggered first, followed by the Hashchange event.
One advantage of popState events is that you can use the pushState/replaceState methods to pass state objects that can hold and pass some data independently.
Popstate and Hashchange events are also the building blocks for handling front-end routing.
Popstate only listens for history changes and does not prevent the browser from moving forward or backward, but it can prevent the default backward action in event methods by implementing jumps, loading other pages, and so on.
It occurred to me that I should document what hash does. When entering a hash URL or changing the hash value, the page is navigated to (or scrolled to) the element whose ID matches the hash value. Therefore, they are also called anchor points. Simply changing the hash will not cause the page to reload and will not send a GET request. Popular and more useful in single-page applications.
The use of the Hashchange event for mobile page effects
On the mobile terminal, when processing images in a page, there is a very common function: click the small image to display the large image on the current page:
Screenshot from the reference article below
For the mobile terminal, we need to consider, when the large picture is displayed, how to return? In the big picture display state, we usually press the back button at the bottom of the phone to exit the big picture, and then continue browsing in the previous small picture state.
But, however, to the browser, back means back to the previous page, that is, back to the previous URL page, not out of the big picture display.
The URL can then be hashed and the page will not reload, but will be recorded in the browser’s history. This feature, to handle hitting the back key, shows a large image of exit, rather than returning to the previous page.
With the hashchange event, you enter the big picture state, add a specific hash, and exit the big picture state when you hit the back key to trigger hashchange.
Here is the main code to deal with:
// Assume that the hash of the state shown in the larger image is imgSlider
window.addEventListener('hashchange'.function(e) {
var re = /#imgSlider$/;
if( re.test(e.oldURL) && ! re.test(e.newURL) ) {// Assume imgSlider is a large display component objectimgSlider.hide(); }},false);
Copy the code
A popState event is not triggered by clicking the browser back button in Chrome
Chrome does not trigger popState event analysis by clicking the browser back button.
The popState event listening mechanism is introduced. When the page load is loaded, js performs pushState to add a record to the browser history. Then, listen for the popState event; Prompts the user “Are you sure you want to exit?” when the user clicks the back button to trigger the POPState event. . Implement “user retention” operations.
For example, in the following brief processing, the following function is executed on the page onload:
function watchBackBtn() {
window.addEventListener('load'.() = > {
const state = {title: 'init'.url: The '#'};
window.history.pushState(state, 'init'.The '#');
});
window.addEventListener('popstate'.() = > {
alert('back... ');
});
}
Copy the code
There is no problem with this process. In Chrome, the popState event can only be triggered by manually interacting with the page (clicking on an element, swiping the page, etc.) and then clicking the browser’s back button.
Chrome plans to save you from sites that mess with your back button. It is an improvement to prevent rogue sites from blocking users from performing rollback operations and leaving them stuck on the current site. [Did encounter this kind of rogue interface]
In Chrome, popState events are not triggered if the page is entered without any human interaction.
However, in actual tests on the PC version of Chrome, there is no such problem.
Just for the record.
Location object
Location is also a native object provided by the browser to retrieve the URL information of the current page and perform operations. The object can be obtained via the window.location or document.location property.
The location of the property
Location.href
: Indicates the full URL of the current page. Is equivalent tolocation.toString()
Method return value.Location.protocol
: The protocol of the current URL, including the colon (:
).Location.host
: the host. If the port is not the protocol default80
and433
, will also include a colon (:
) and ports.Location.hostname
: Specifies the host name, excluding the port.Location.port
: Port number.Location.pathname
: Path part of the URL, from the root path/
Start.Location.search
: Query string part from question mark?
Start.Location.hash
: fragment string part from#
Start.Location.username
: Indicates the username before the domain name.Location.password
: Password before the domain name.Location.origin
: Protocol, host name, and port of the URL.
// The current url is
// http://user:[email protected]:4097/path/a.html?x=111#part1
document.location.href
// "http://user:[email protected]:4097/path/a.html?x=111#part1"
document.location.protocol
// "http:"
document.location.host
// "www.example.com:4097"
document.location.hostname
// "www.example.com"
document.location.port
/ / "4097"
document.location.pathname
// "/path/a.html"
document.location.search
/ / "? x=111"
document.location.hash
// "#part1"
document.location.username
// "user"
document.location.password
// "passwd"
document.location.origin
// "http://user:[email protected]:4097"
Copy the code
With the exception of the Origin attribute, which is read-only, all other attributes can be modified through assignment to achieve page operations.
For example, assigning a new URl to location.href allows the browser to jump.
// Jump to the new url
window.location.href = 'http://www.example.com';
/ / is equivalent to
window.location = 'http://www.example.com';
Copy the code
Rewriting location directly is the same as changing the href attribute.
For example, jump to the specified hash anchor point by modifying the href or hash implementation.
window.location.href = '#top';
/ / is equivalent to
window.location.hash = '#top';
Copy the code
The location. href attribute allows cross-domain writing
Location. Href is the only property that the browser allows for cross-domain writing, meaning that non-homologous Windows can override the Location. Href property of another window (such as a child window and parent window) to jump.
Location
None of the other properties of the.
methods
Location. assign(url) Jumps to the specified URL
Location. assign(URL) is used to jump to the specified URL. The parameter must be a valid URL string; otherwise, an error will be reported.
// Jump to the new url
document.location.assign('http://www.example.com')
Copy the code
Location.replace (URL) jumps to the new URL and deletes the current url in history
Location.replace (URL) is also used to jump to a new URL, except that it removes the current url from the browser’s browsing History.
That is, the back button cannot go back to the current page. That is, replace the old URL with the new one in the browsing history.
One of the biggest uses of this method is to determine the current device type and jump to the specified version page. For example, determine if it is a mobile device and immediately jump to the mobile version of the web page.
// Jump to the new url
document.location.replace('http://www.example.com')
Copy the code
Location.reload () refreshes the current page
Location.reload () is used to reload the current URL, equivalent to a browser refresh.
Reload takes a Boolean argument, and if true, the browser rerequests the web page from the server, and the page scrolls to the top (that is, scrollTop === 0).
If the parameter is false or null, the browser will reload the page from the local cache, and the page viewport will be the same as before.
The behavior of using the true and false parameters varies from browser to browser, and does not follow exactly this behavior
// Request the current url from the server again
window.location.reload(true);
Copy the code
Method to refresh the current page
Location.reload () is the standard common refresh method
Location.reload () is the most common way to refresh the current page.
Direct callhistory.go()
history.go()
No parameters are specified, or parameters are specified0
, the current page is refreshed.
The use of the document. The location. The assign (window. The location. Href)
Document.location. assign(window.location.href) can also refresh the current page.
Href = window.location.href does not refresh the current page
Window.location. href=window.location.href does not modify the href URL, so it has no effect on the current page refresh.
reference
- The History object
- Location object, URL object, URLSearchParams object
- Window: hashchange event
- Clever use of the Hashchange event