Pass url parameters

Asked

Viewed 145 times

0

I’m a little layman on the subject, but I’m putting together a sales page for a product and I’m having a hard time. I want to go over the utms who come via url, for some link contained on the page, dynamically.

To url comes like this: https://meusite.com?utm_source=teste&utm_campaign=teste&utm_content=teste

I’d like to go over this one utm who comes in the url to others link that are on the page.

  • So I use these parameters coming from traffic sources like Facebook and Google, so [link] (http://meusite.com?src=teste) and in the source code of the page has a check out link that accurate takes the information from the url [link] (http://monetizze.com/dasdsd?src=utm-da-url)

  • But you want to change ALL the links on the page or just a few?

1 answer

0

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

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 make a loop searching all the elements <a> and concatenate the variable params to the attribute href 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;
   }  
}

Complete 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 be changed, you need to identify them in some way. You can put a 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, i.e., the href of link 1 shall be amended, but link 2 nay:

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;
      }  
   }
});

Browser other questions tagged

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