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;
}
}
});
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)
– Ednardo Menezes
But you want to change ALL the links on the page or just a few?
– Sam