The History API Module #35 Flashcards
What are the 3 methods used to engage with the History API? How is go( ) different from the rest?
- back( )–Goes to the previous entry in session history
- forward( )–Goes to the next entry in session history
- go( )–Allows navigation backward or forward through multiple levels
How can you determine how many levels there are in the session history?
history.length
How would you put together a function that returns the user to a previous history state?
First hook into the dom element such as a button with something like querySelector. Then attach an event listener to the button, that listens for a “click” event. Finally fire the history( ) method on the event. Example:
document.querySelector(‘.back’).addEventListener(‘click’, ( ) => {
history.back( )
} )
How would you go back or forward through multiple history states?
Use the go method. For example:
history. go(-1) //equivalent to history.back( )
history. go(-2) //equivalent to calling history.back( ) twice
history. go(1) //equivalent to history.forward( )
history. go(3) //equivalent to calling history.forward( ) 3 times
How is an extra entry added to the history state?
Using pushState( )
const state = { color: 'red' } history.pushState(state, ' ', '/anotherPage')
What are the 3 params you pass when using the push state method
- an object which can contain anything OR be empty
- Second param is currently unusable by browsers so make it an empty string (“”)
- The third is a URL associated with the new state. BUT the url must belong to the same domain of the current URL.
What technique is used to manipulate the current history state?
replaceState( )
This accepts the same params see below:
history.replaceState(state, ‘ ‘, ‘/post/second’)
AGAIN:
1. The first is an object which can contain anything (there is a size limit however, and the object needs to be serializable).
- The second parameter is currently unused by major browsers, so you generally pass an empty string.
- The third parameter is a URL associated to the new state. Note that the URL needs to belong to the same origin domain of the current URL.
What on Earth is ‘popstate’ used for?
This event is called on window every time the active history state changes with the current state as the callback parameter.
EXAMPLE:
window.onpopstate = event => {
console.log(event.state)
}
.state refers to the current state!
Write a function using popstate as an event listener.
Hint: Start with window.addEventListener
window.addEventListener(‘popstate’, event => {
console.log(event.state)
} )