2

I have this line of code here:

if(window.location.search == "?mytoken=abc") {
          window.history.replaceState(null, '', window.location.pathname);
}

What this code does is check if the query parameter mytoken exists and if it does, replace the current page without the query parameter and this works perfectly.

But I did notice I did have 2 history items in my browser history, one with the query parameter and the other without the query parameter. I am looking for away to remove the item with the query parameter from the browser history. Is this possible?

I found this code in my project, if it helps:

history.listen((newLocation, action) => {

      if (action === "PUSH") {
        if (
          newLocation.pathname !== this.currentPathname ||
          newLocation.search !== this.currentSearch
        ) {
          // Save new location
          this.currentPathname = newLocation.pathname;
          this.currentSearch = newLocation.search;

          // Clone location object and push it to history
          history.push({
            pathname: newLocation.pathname,
            search: newLocation.search,
          });
        }
      } else {
        // Send user back if they try to navigate back
        history.go(1);
      }
    });

This is called every time a new page comes up.

user979331
  • 11,039
  • 73
  • 223
  • 418
  • There's no way to delete or modify past browser history states, but you can emulate history with your own custom object that you have full control over. Take a look at [the top answer here](https://stackoverflow.com/questions/28028297/js-window-history-delete-a-state) for an example of this approach – D-Money Oct 16 '21 at 20:22

4 Answers4

3

You can use new URL in javascript See Docs

const url = new URL(YOUR_URL);

You can access all parts of the url

consr origin = url.origin; // domain.com
const pathname = url.pathname; // /path/test
const search = url.search; // ?query=true

window.location.replace = url.origin + url.pathname + url.search;

history.replace({
    pathname: url.pathname,
    search: url.search
});

You can also use useEffect in your App.js

import { useEffect } from 'react';
import { useLocation, useHistory } from 'react-router-dom';

const Component = () => {
    const { pathname, search } = useLocation();
    const hidtory = useHistory();

    useEffect(() => {
        if (search === "..." || pathnamr === "...") {
            history.replace({...});
        }
    }, [pathname, search]);
}
Ali Yaghoubi
  • 1,258
  • 8
  • 15
1

Yes! you can use history.replace instead of history.push

history.replace({
   pathname: newLocation.pathname,
   search: newLocation.search,
});

P.S: Not window.history. npm install --save history

References: https://github.com/remix-run/history/blob/main/docs/api-reference.md#history.replace

Karthik R
  • 5,523
  • 2
  • 18
  • 30
0

I suggest the use of pushState api. This api remove all the entries in the browsing context's session history after the current entry. If the current entry is the last entry in the session history, then no entries are removed. So when you're attempting to replace the url, you can pushState to remove the current URL, and push the new URL.

I'll write a solution a bit later, but above api would be a good hint to start.

TopW3
  • 1,477
  • 1
  • 8
  • 14
0

There is a related technique for removing OAuth fields received in login responses for SPAs from the browser history - see the history.replaceState call in this code of mine and check if it works for you.

private async handleLoginResponse(): Promise<void> {

    // Ask the security library to process the OAuth response    
    const user = await this.userManager.signinRedirectCallback();

    // Return to the app location before the login redirect
    const preRedirectLocation = user.state.hash;

    // Remove OAuth details from back navigation
    history.replaceState({}, document.title, preRedirectLocation);
}

In my case the value removed is an authorization code and I want to remove these security details from the URL:

https://www.example.com?code=7890257802&state=807245780

Be aware that tokens in URLs could also end up in web server logs. Any tokens in URLs should therefore be one time use, as is the case for authorization codes.

Gary Archer
  • 22,534
  • 2
  • 12
  • 24