1

I have two domains as: project1.com and project2.com. The latter contains a subdomain as login.project2.com. I need to redirect a user to this place, i.e. login.project2.com from the former based on his input. (Don't ask about the logic, or as to why I do this, it is simply because I have been asked to do).

I have tried the following:

function redirectToPage() {
    if (someVar == someValue) {
        document.location = 'http://www.login.project2.com'; // does not work
        document.location = 'www.login.project2.com'; // does not work
        document.location = 'http://login.project2.com'; // does not work
        document.location = 'login.project2.com'; // inval

        //only of the above is left uncommented at a time
    }
}

But, when I type the fourth one directly in the address bar, it leads me to the desired page. Where am I wrong?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
user2053912
  • 173
  • 1
  • 3
  • 11

1 Answers1

2
  1. document.location is deprecated and could be read-only
  2. if you have another domain, you need the protocol too. this is added by the browser if you leave it out on the location bar, but not in a script.
  3. it is good practice to wrap a statement in brackets so I added them for you

Here is how to redirect using JavaScript - I use replace so the old address is replaced in the history so the back button is not broken

function redirectToPage() {
  if (someVar == someValue) {
    window.location.replace('http://login.project2.com'); 
  }
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236