Submitting url parameters

0

I'm a bit lazy on the subject, but I'm putting together a sales page for a product and I'm having a hard time. I want to pass on the% of users who come via url , to some link contained on the page, dynamically.

url looks like this: utms

I would like to pass this https://meusite.com?utm_source=teste&utm_campaign=teste&utm_content=teste on to the link on the page.

    
asked by anonymous 20.07.2018 / 00:47

1 answer

0

To change ALL links on the page, you can get the parameters coming from the URL with location.href and extract only the string from ? using the .substring() method:

var url_ = location.href;
// url_ = https://meusite.com?utm_source=teste&utm_campaign=teste&utm_content=teste
var params = url_.substring(url_.indexOf("?"));
// params = ?utm_source=teste&utm_campaign=teste&utm_content=teste

Then just looping for all <a> elements and concatenate the variable params to the href attribute of each:

// verifica se no params tem a string "?utm", caso contrário, não faz nada
if(~params.indexOf("?utm")){
   var as = document.querySelectorAll("a");
   for(var x=0; x<as.length; x++){
      as[x].href = as[x].href+params;
   }  
}

Full Code:

// aguarda o DOM ser carregado
document.addEventListener("DOMContentLoaded", function(){
   var url_ = location.href;
   var params = url_.substring(url_.indexOf("?"));

   if(~params.indexOf("?utm")){
      var as = document.querySelectorAll("a");
      for(var x=0; x<as.length; x++){
         as[x].href = as[x].href+params;
      }  
   }
});

Or, if you want only a few links to change, you need to identify them in some way. You can put class , for example, class="alt" :

<a class="alt" href="link">Link 1</a>
<br>
<a href="link">Link 2</a>

The code below will only change the links with the class .alt , that is, the href of the link 1 will be changed, but the link 2 will not:

document.addEventListener("DOMContentLoaded", function(){
   var url_ = location.href;
   var params = url_.substring(url_.indexOf("?"));

   if(~params.indexOf("?utm")){
      var as = document.querySelectorAll("a.alt");
      for(var x=0; x<as.length; x++){
         as[x].href = as[x].href+params;
      }  
   }
});
    
20.07.2018 / 01:42