Different behavior inside and outside the function

Asked

Viewed 160 times

4

Good afternoon!

For example, I made a script to redirect all people from my site to the home of the site, because, we will change system and with this, sales have to stop so we can do this.

I made a mini function just for testing and to be more organized. (I had no need to create function)

However, when I tested it, it redirects the person to the home of the site, which is the root in the case (/) but it at the root is also redirecting and forms an infinite loop, since it is in the url that is actually to be redirected, (only with the function)

let newRedirect = function(){
    if(window.location.href != "https://www.meusite.com.br/"){
        window.location.href = "https://www.meusite.com.br/";
    }
}
newRedirect();

Now, if I use like this (no function):

if(window.location.href != "https://www.meusite.com.br/"){
    window.location.href = "https://www.meusite.com.br/";
}

Works normally and redirects only once.

In short, why with function, even at the root, is redirecting and without function, no?

  • The location.pathname returns only the path, so you can validate with a != "/".

  • 2

    This shouldn’t happen. Put a alert(window.location.href) at the beginning of the function and see what shows.

  • You can also try using a.log console (window.location.href) so it’s easier to track and understand what’s going on, what the value is window.location.href...

  • Are you using Node.js? And the http-server module?

  • Suddenly it’s a problem with Hoisting?

  • may be that your Location.href is returning h ttps://meusite.com.br/ without www

Show 1 more comment

2 answers

-1

Some window settings have a delay, so it only works with the function that is called after reading the script, try to use after Document.Domcontentloaded.

-3

Paulaodev’s answer may already clarify something. But in case you’re still in trouble, what I recommend is doing what Sam and Raphael Godoi indicated. Comment on the line window.location.href = "https://www.meusite.com.br/"; and put in place a console.log(windows.location.href) for more information than is happening.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.