Looping in window.location

84 Views Asked by At

I am getting lat and lng from sessionStorage and I want to send it to browser with window.location but i get to a infinity loop.

    var lat = sessionStorage.getItem('lat');
    var lng = sessionStorage.getItem('lng');       
    window.location = '?lat='+lat+'&lng='+lng;
   

I saw other questions about this but they did not work. I tryed to use window.location.hash / href etc... but the result is not what I expect

Does someone knows how to build that function to work properly? Thank you very much

2

There are 2 best solutions below

1
alcompilor On BEST ANSWER

Here is a self invoked function to achieve what you want

const redirect = (() => {
  var lat = sessionStorage.getItem("lat");
  var lng = sessionStorage.getItem("lng");
  const params = new URLSearchParams(window.location.search);
  !params.get("lat") ? (window.location.href = `?lat=${lat}&lng=${lng}`) : null;
})();

0
epascarello On

Check before setting the location so you are not stuck in the loop.

const urlParams = new URLSearchParams(window.location.search);
const latQS = urlParams.get('lat');
const lat = sessionStorage.getItem('lat');
cost lng = sessionStorage.getItem('lng');       
if (!latQS && lat && lng) {
  const lat = sessionStorage.getItem('lat');
  cost lng = sessionStorage.getItem('lng');       
  window.location = '?lat='+lat+'&lng='+lng;
}

Other option is setting the history with pushstate

const lat = sessionStorage.getItem('lat');
cost lng = sessionStorage.getItem('lng');
if (lat && lng) { 
  const url = new URL(window.location);
  url.searchParams.set('lat', lat);
  url.searchParams.set('lng', lng);
  window.history.pushState({}, '', url);
}