javascriptdjangowindow.location

Looping in window.location


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


Solution

  • 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;
    })();