javascripthttp-redirectparameters

JS redirect from [example.com/home] to [example.com/home?loc=USA] causes infinite loop


I'm trying to redirect from example.com/home to example.com/home?loc=USA. But it causes infinite loop. How do I stop it? Thanks.

My code:

<script>
    window.location = "example.com/home?loc=USA";
</script>

Solution

  • Currently you're redirecting the user unconditionally, every time the page loads. You can wrap that logic in a condition which checks if the query string parameter you're looking for exists or not. For example:

    const params = new URLSearchParams(window.location.search);
    const loc = params.get('loc');
    if (!loc) {
      window.location = "example.com/home?loc=USA";
    }