Redirect using url parameters

Asked

Viewed 44 times

2

This one is a redirect code, I used it without url parameters, but now I need it to work according to the parameters and I could not, I am very new in javascript, could someone explain to me what I am doing wrong in my code?
If ver is equal to 1, do nothing, otherwise run window.location.replace("https://www.google.com");

var url = new URL(window.location);
var ver = url.searchParams.get("ver");

document.onload = function() {

   if(ver == 1) {
      return false;
   }

   else {
      window.location.replace("https://www.google.com");
   }
}

1 answer

1


The event onload shall not apply to document, but to the object window.

Change to:

window.onload = function() {...

Now, wouldn’t it be more interesting to check whether ver is different from 1, since the else will consider any value other than 1?

if(ver != 1) {
  window.location.replace("https://www.google.com");
}
  • can explain to me the function of exclamation?

  • 1

    Yes: != means "different" and == means "equal"

  • 1

    thank you very much, this will help me simplify a lot of things

  • Also has !== which means different in value and type, and === equal in value and type. More information about operators you think at this link

Browser other questions tagged

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