Cover Image for Javascript history.pushState() Method
145 views

Javascript history.pushState() Method

The history.pushState() method is a JavaScript function that allows you to modify the browser’s history and change the URL of the current page without triggering a full page reload. It is part of the History API, which provides methods for interacting with the browser’s session history.

The pushState() method takes three parameters:

history.pushState(state, title, url);
  • state (optional): An object representing the state associated with the new history entry. This state can be accessed later using the state property of the popstate event.
  • title (optional): The title of the new history entry. Most browsers currently ignore this parameter, so it can be an empty string.
  • url (optional): The new URL that should be displayed in the browser’s address bar. This URL can be relative or absolute.

Here’s an example that demonstrates the usage of the pushState() method:

JavaScript
var stateObj = { data: 'example' };
var title = 'Page Title';
var url = '/new-url';

history.pushState(stateObj, title, url);

In the example above, we call the pushState() method to push a new state into the browser’s history. We provide an object stateObj to represent the state associated with the new history entry. We also specify a title (which may be ignored by most browsers) and a url that should be displayed in the address bar.

When the pushState() method is called, the URL in the address bar will be updated to the specified url, but the page will not be reloaded. This allows you to create dynamic web applications that can change the URL without causing a full page refresh.

It’s important to note that using pushState() does not automatically load a new page or update the content on the page. It simply changes the URL and adds a new entry to the browser’s history. To handle the change in the URL and update the page content accordingly, you’ll typically need to listen for the popstate event and update the page based on the new URL or state.

To summarize, the pushState() method is a powerful tool for manipulating the browser’s history and changing the URL dynamically. It is commonly used in single-page applications (SPAs) and other cases where you want to update the URL without triggering a full page reload.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS