How to redirect to a url using url parameters

2

I would like to get a url that is just after red= and redirect to it, if it is blank do not redirect. I've used window.location.replace("") just to test the code.
Example where I want to get: red=http://www.google.com/ The code has the function of replacing content within an element, and redirect the page in a few seconds.

window.onload = function substituir() {

   var url = new URL(window.location);
   var sub = url.searchParams.get("sub");
   var red = url.searchParams.get("red");
   setTimeout(redirecionar, 5000);

   if(sub == 1) {
       document.getElementById("subst").innerHTML = "<p>Alguma coisa</p>"
   }

   function redirecionar() {

      if(red == 1) {
         window.location.replace("https://www.google.com");
      }
   }
}
    
asked by anonymous 27.07.2018 / 03:55

2 answers

2

Just check if the variable has value with if(variável) and redirect with window.location.href .

The value in sub will also be sent to the element if it is not undefined and not null .

window.onload = function substituir() {

   var url = new URL(window.location);
   var sub = url.searchParams.get("sub");
   var red = url.searchParams.get("red");
   setTimeout(redirecionar, 5000);

   if(sub) {
       document.getElementById("subst").innerHTML = "<p>"+sub+"</p>"
   }

   function redirecionar() {

      if(red) {
         window.location.href = red;
      }
   }
}

If http:// is missing you can check using a regex with .test() and concatenate to red :

if(red) {
   if(!/^http:\/\//.test(red)){
      red = "http://"+red;
   }
   window.location.href = red;
}

The regex /^http:\/\// checks if at the beginning of the string has http:// .

    
27.07.2018 / 04:27
1

Code

 $().ready(function () {

    var url = new URL(window.location);
    var sub = url.searchParams.get("sub");
    var red = url.searchParams.get("red");
    setTimeout(redirecionar, 5000);

    if(sub == 1) {
       document.getElementById("subst").innerHTML = "<p>Alguma coisa</p>"
    }

    function redirecionar() {
      if (red.length > 0)
        window.location.replace(red);
    }

  })

Explanation

The difference for your code is that I've changed the condition for page redirection. In the new condition it is checked whether the size of the string caught by the red parameter is greater than 0 .

    
27.07.2018 / 04:10