0

I want to replace a URL with another while loading. I have written the code below.

<script type="text/javascript">
    var executed = false;
     if (!executed) {
        executed = true;
        window.location.href = window.location.pathname + '?'+'bc';
            }
</script>

But it's not working correctly. It's loading again and again. It doesn't stop.

2
  • 2
    Changing the URL will cause the browser to direct the user to that location, hence causing an infinite loop. You should use window.history states instead: spoiledmilk.com/blog/… Commented Dec 23, 2013 at 10:11
  • well it would load again and again since the variable is reset on page load.Try to keep executed in some cookie Commented Dec 23, 2013 at 10:11

2 Answers 2

3

The executed variable is not kept when going to the new page. Even if it were, var executed = false just sets it to false again :p

Try this instead:

if( !window.location.search.match(/\?bc$/)) {
    window.location.href = window.location.pathname+"?bc";
}
Sign up to request clarification or add additional context in comments.

Comments

1

Just you variables resets after page reload. Try to check GET params like this:

if (window.location.search.indexOf('?bc') === -1) {
  window.location.href = window.location.pathname + '?bc';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.