Prevent Adding To History API Array

512 Views Asked by At

Is it possible to prevent adding the current Page URL to the History if user is on specific/same page and only location.search parameters change? The page reloads with new search params but I'm not able to prevent the URL to get stored to History array if pathname does not change.

I need to have only one Product Page in the History when I click the back button instead of having "number" depending on how many times location.search is changed. I'm trying this but it's not working, what am I doing wrong?

// Note: Page Reloads when changing the search parameters ( window.location.search params can change but the URL should not be added to History API)
    if(document.querySelector('.prod-page')) { // check if user is on Prod Page
      console.log("user is on PDP PAGE");
    
      const prodPage = window.location.pathname; // get Prod Page Location Pathname 
    
      window.addEventListener('popstate', (e) => {  // on browser "Back" click
        e.preventDefault();
    
        if(prodPage) { // if user is still on Product Page 
          window.history.pushState(null, null, null); // Prevent adding current URL (another product page url) to History API
        }
    
      });
    
    }
1

There are 1 best solutions below

0
Tyler Dill On

I believe what is happening is that when the event listener is called prodPage is out of scope. You can try passing prodPage to the callback so it has access to it, like this:

      window.addEventListener('popstate', (e, prodPage) => {  // on browser "Back" click
        e.preventDefault();
    
        if(prodPage) { // if user is still on Product Page 
          window.history.pushState(null, null, null); // Prevent adding current URL (another product page url) to History API
        }
    
      });