ReasonJun

javascript : Web API (history) 본문

Frontend/Javasciprt

javascript : Web API (history)

ReasonJun 2023. 6. 9. 00:19
728x90

In web development, the history object in JavaScript provides access to the browser's history stack. It allows you to programmatically manipulate the browser's history, navigate between pages, and control the browsing session.

Here are the key aspects of the history object:

  1. Accessing the History Object: The history object is accessible through the window.history property.
  2. Navigating History: The history object provides several methods to navigate the browser's history stack. These methods include:
    • go(n): Moves the browser's history forward or backward by n steps. n can be a positive or negative integer. For example, history.go(-1) moves back one page, while history.go(2) moves forward two pages.
    • back(): Equivalent to history.go(-1), it moves the browser back by one page.
    • forward(): Equivalent to history.go(1), it moves the browser forward by one page.
    • pushState(state, title, url): Adds a new entry to the browser's history stack with the specified state object, title, and url. This method allows you to change the URL without triggering a page refresh.
    • replaceState(state, title, url): Replaces the current entry in the history stack with a new one, similar to pushState() but without adding a new entry. This method is useful for updating the URL without creating a new history entry.
  3. History Length: The length property of the history object returns the number of entries in the history stack.
console.log(history.length); // Output: Number of entries in the history stack
  1. Listening to History Changes: The popstate event is fired whenever the active history entry changes. You can listen for this event using the window.addEventListener() method.
window.addEventListener('popstate', (event) => {
  // Handle history change
});
  1. This event is triggered when the user navigates using the browser's back or forward buttons or when the history.go(), history.back(), or history.forward() methods are called.

The history object is particularly useful when building single-page applications (SPAs) or implementing navigation within an application. It allows you to modify the URL and manage the browser's history stack without triggering full page reloads. This enables smoother and more interactive user experiences.

 

However, note that manipulating the browser's history can have implications for usability and accessibility. It's important to use the history object judiciously and consider how it affects navigation and user expectations within your web application.

 

// .scrollRestoration :Check and specify whether or not to restore the scroll position when navigating the history
history.scrollRestoration = 'manual';
// Scroll to the top on refresh.
history.scrollRestoration = 'auto';
// Scrolling is maintained on refresh.

 

728x90
Comments