kierrapalmer
kierrapalmer

Reputation: 43

Add to browser History without changing current URL

I have a 3 step signup process where each step is shown on the page using javascript without a page refresh. What I am trying to do now is add a back reference to what step the user was on so if they click the browser back button they will not lose all of their progress.

So for example, as the user navigates from Step 2 to Step 3 the URL stays at www.example.com. The user then clicks the browser back button. The URL should now be www.example.com?step-2.

I'm thinking that I will somehow need to use the History API to accomplish this but if I use window.history.pushState(null, null, 'www.example.com?step-2'), the current URL would be changed as well.

How would I accomplish adding to the history without changing the current URL?

Upvotes: 0

Views: 1078

Answers (2)

nickap
nickap

Reputation: 31

Fortunately, there is a simple and straightforward solution to this issue that leverages the pushState method.

We just need to use the often overlooked state parameter of the pushState method.

By doing so, we can insert an entry into the browser's session history without altering the URL (pushing the same URL) while updating the state parameter.

// Retrieve your URL parameters
const urlParams = getParams();

// Retrieve current URL
const currentUrl = window.location.pathname;

// Update the browser's session history
window.history.pushState({ urlParams }, '', currentUrl);

Bear in mind that a popstate event is triggered whenever user navigates front/back. The popstate event has a state attribute that points to the state object of the history entry.

function handlePopState(event) {
    if (event.state?.urlParams) {
        const restoredParams = event.state.urlParams;
        // Now you can use the restoredParams object as needed
        console.log('Restored URL params:', restoredParams);
    }
}

// Add an event listener for the popstate event
window.addEventListener('popstate', handlePopState);

Upvotes: 0

RookieSA
RookieSA

Reputation: 101

If your objective is to not change the URL, but to still allow back and forth history state changes, your best bet would be to utilize the window's hashchange event listener. This would of course utilize hash references within the URL, but the base URL won't change:

function locationHashChanged() {
  if (location.hash === '#step-2') {
    // Do something here
  }
}

window.onhashchange = locationHashChanged;

For further info on this, refer to official documentation: https://developer.mozilla.org/en-US/docs/Web/API/Window/hashchange_event

Upvotes: 2

Related Questions