Web development and Tech news Blog site. WEBISFREE.com

HOME > js

JavaScript history object allows page transition without page refreshing and pushstate

Last Modified : 06 Mar, 2023 / Created : 06 Mar, 2023
677
View Count

We will learn how to change the current page to a different address using JavaScript without refreshing or updating it.



# Changing the URL in the current page using JavaScript


If you want to change the URL in the address bar of the current page to something else while keeping the page intact, you can do so by using the pushstate() method of the history object.

history.pushstate(state, title, url)


pushstate() allows the URL of the current page to be changed while maintaining the same page, preventing it from being refreshed or changed. This also enables the URL in the address bar to change at the same time.


! When will you need it?

This is often used on pages with a search page or pagination. In other words, when search conditions or page transitions are made using asynchronous AJAX, the page address is also changed to reflect these changes. By changing the page address, even if the page is reloaded or refreshed, the changed address or query string information can still be obtained.


The advantage of pushstate() is not just changing the page address, but it also allows for passing data (state) and changing the page title at the same time.

To access the passed data, you can use history.state. This method can be found at the bottom.


! How to change the URL using pushstate() and examples.


First, let's learn how to change the URL address. You can simply change the address as follows if there is no data (state) or title.
const url = '/test';
history.pushstate('', '', url);

When you run the code, you can confirm that the current page has changed to /test in the address bar of the browser.


! Let's learn how to pass data through state


We are going to enter the following into the state to pass data and try changing the page.
const state = { sitename: 'webisfree' };
history.pushState(state, '', '/test');

You can retrieve the concurrently passed state by changing the address to '/test'.
history.state;

// Result
{sitename: 'webisfree'}


We have learned how to use the pushState() method of the history object in JavaScript to change the URL of a page without refreshing or reloading it up to this point.

Perhaps you're looking for the following text as well?

    Previous

    Adding text and elements to JavaScript cursor position and selection area

    Previous

    JavaScript date and time library - momentjs information and examples