We do have some Campaigns (Google, facebook,...) When the user arrives the landingpage (abo.mysite.com) he does have the utm parameter utm_source=theCampaignSource. When the user clicks an CTA the CTA gives an new UTM utm_source=abo and he goes to shop.mysite.com.
We are not able to remove the UTM from abo.mysite.com.
Is there a way to check if a user have already an UTM, and when he does have one to kepp them until shop.mysite.com? So we know that the user is comming from Google (...)?
We know that how this Thing is set up is a very bad practice, and we are working on it.
Ive found a code snippet which is manipulating the links on a site:
links.forEach(function(link){
link.setAttribute("href","abo.mysite.com")
})
but i couldn get it work - cause i do have a lack of experience.
Update
To my specific needs a made it that way:
1) Remove existing UTM from Links on the Site
<script>
var link = document.getElementsByTagName("a");
for (var i = 0; i < link.length; i++) {
link[i].href = link[i].href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
}
</script>
2) Hash the UTM in the URL
<script>
if(!window.jQuery) {
document.write('<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">\x3C/script>');
}
</script>
<script type="text/javascript">
$(document).ready(function() {
function getUrlVars() {
var vars = [],
hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var parameters = getUrlVars();
var utm_source = decodeURIComponent(parameters['utm_source']);
var utm_campaign = decodeURIComponent(parameters['utm_campaign']);
var utm_medium = decodeURIComponent(parameters['utm_medium']);
</script>
3)rewrite every URL on the Site with the hashed UTMs
<script>
$('a').each(function(){
$(this).attr('href', $(this).attr('href') + '?utm_source=' + utm_source + '&utm_campaign' + utm_campaign + '&utm_medium' + utm_medium);
});
});
Edit
Thanks to Michele Pisani
this works well - BUT, if a user does not have an UTM, and he clicks the button, the UTM will be set to undefined
Is there a way to set the UTM Parameter from the URL when the User already has one, or to use the existing UTM (which are hardcoded in the button) when he does not have an UTM in the URL.
Edit 2 & update
Finally - with the help of you guys - i found a solution:
<script>
var link = document.querySelectorAll('a:not([href*="#"])');
for (var i = 0; i < link.length; i++) {
//link[i].href = link[i].href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
}
</script>
<script type="text/javascript">
$(document).ready(function() {
function getUrlVars() {
var vars = [],
hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
//var parameters = getUrlVars();
//var utm_source = decodeURIComponent(parameters['utm_source']);
//var utm_campaign = decodeURIComponent(parameters['utm_campaign']);
//var utm_medium = decodeURIComponent(parameters['utm_medium']);
var url_string = window.location.href; //window.location.href
var url = new URL(url_string);
//var c = url.searchParams.get("c");
var utm_source = url.searchParams.get("utm_source");
var utm_campaign = url.searchParams.get("utm_campaign");
var utm_medium = url.searchParams.get("utm_medium");
$('a:not([href^="#"])').each(function() {
if(utm_source != "" && utm_source != null){
var href = $(this).attr("href");
href = href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
$(this).attr("href",href);
$(this).attr('href', $(this).attr('href') + '?utm_source=' + utm_source + '&utm_campaign=' + utm_campaign + '&utm_medium=' + utm_medium);
}
});
});
</script>
With JavaScript, to remove UTM parameters from links in page you can try this function with regex:
var link = document.getElementsByTagName("a");
for (var i = 0; i < link.length; i++) {
link[i].href = link[i].href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
}
If you are using Google Tag Manager you can add it in a custom HTML tag and fires it on DOM Ready.
If you want to keep the fragment in the URL you can modify the function in this way:
var link = document.getElementsByTagName("a");
for (var i = 0; i < link.length; i++) {
arr_link = (link[i].href).split("#");
var fragment = "";
if (arr_link[1]) { fragment = "#" + arr_link[1]; }
var my_new_url = arr_link[0].replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
link[i].href = my_new_url + fragment;
}
const ourUTMs = new URL(location.href).searchParams;
document.body.onclick = (e) => {
if (!isParamsContainsUTM(ourUTMs) || e.target.tagName !== "A") {
return;
}
try {
// Is valid url?, else we go to catch =)
const url = new URL(e.target.href);
e.preventDefault();
// Remove all utm params from link;
Array.from(url.searchParams).forEach(([k]) => {
if (k.startsWith("utm_")) {
url.searchParams.delete(k);
}
});
// Add our utm_ params to link
Array.from(ourUTMs).forEach(([k, v]) => {
url.searchParams.append(k, v);
});
// Open URL
window.open(url.toString());
} catch (e) {}
};
const isParamsContainsUTM = (arr = new URLSearchParams()) =>
Array.from(arr).some(([key]) => key.startsWith("utm_"));
Related
I am using a javascript on my site, which always inherits the UTM parameters to the links on the site.
However, this is not working, when the links are anchor links to a section of the site and the link the visitor used to visit the page contains the "gclid" parameter from google.
For example:
A visitor uses this link to visit a site:
domain.com?utm_source=test&utm_medium=test&utm_campaign=test&gclid=12345
The button link on the site with the anchor link will look like the following:
domain.com&gclid=12345?utm_source=test&utm_medium=test&utm_campaign=test#anchor
For some reason the "&gclid" part changes its position.
I've tested it with a link without an anchor and in this case the "gclid" parameter doesn't get inherited and the link works.
Of course, the second domain isn't working anymore and leads to a 404 error.
Does someone have an idea what could be the cause for this?
This is the javascript I am using to inherit the UTMs:
(function() {
var utmInheritingDomain = "grundl-institut.de"
utmRegExp = /(\&|\?)utm_[A-Za-z]+=[A-Za-z0-9]+/gi,
links = document.getElementsByTagName("a"),
utms = [
"utm_medium={{URL - utm_medium}}",
"utm_source={{URL - utm_source}}",
"utm_campaign={{URL - utm_campaign}}"
];
for (var index = 0; index < links.length; index += 1) {
var tempLink = links[index].href,
tempParts;
if (tempLink.indexOf(utmInheritingDomain) > 0) {
tempLink = tempLink.replace(utmRegExp, "");
tempParts = tempLink.split("#");
if (tempParts[0].indexOf("?") < 0) {
tempParts[0] += "?" + utms.join("&");
} else {
tempParts[0] += "&" + utms.join("&");
}
tempLink = tempParts.join("#");
}
links[index].href = tempLink;
}
}());
EDIT: It seems like the following script don`t causes this problem:
<script>
(function() {
var domainsToDecorate = [
'domain.com',
],
queryParams = [
'utm_medium',
'utm_source',
'utm_campaign',
]
var links = document.querySelectorAll('a');
for (var linkIndex = 0; linkIndex < links.length; linkIndex++) {
for (var domainIndex = 0; domainIndex < domainsToDecorate.length; domainIndex++) {
if (links[linkIndex].href.indexOf(domainsToDecorate[domainIndex]) > -1 && links[linkIndex].href.indexOf("#") === -1) {
links[linkIndex].href = decorateUrl(links[linkIndex].href);
}
}
}
function decorateUrl(urlToDecorate) {
urlToDecorate = (urlToDecorate.indexOf('?') === -1) ? urlToDecorate + '?' : urlToDecorate + '&';
var collectedQueryParams = [];
for (var queryIndex = 0; queryIndex < queryParams.length; queryIndex++) {
if (getQueryParam(queryParams[queryIndex])) {
collectedQueryParams.push(queryParams[queryIndex] + '=' + getQueryParam(queryParams[queryIndex]))
}
}
return urlToDecorate + collectedQueryParams.join('&');
}
// borrowed from https://stackoverflow.com/questions/831030/
// a function that retrieves the value of a query parameter
function getQueryParam(name) {
if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(window.location.search))
return decodeURIComponent(name[1]);
}
})();
</script>
You really should not change URLs with regexp and string manipulation.
Here is the recommended way
const url = new URL(location.href); // change to tempLink
utms = [
"utm_medium=med",
"utm_source=src",
"utm_campaign=camp"
];
utms.forEach(utm => url.searchParams.set(...utm.split("=")))
console.log(url.toString())
I am building a page that needs to be able to get a all the file links on a webpage and add them to a dropdown list. Original it was the script was supposed to be on the same page as the files but now it needs to search an external. This is what I used before the change
<script>
$(document).ready(function() {
var arr = [];
var filenames = [];
var alt_var;
var baseURL = "www.fakeurl.com"
$('.ms-vb-icon').find('a').each(function(){
var temp = $(this).attr('href')
$(this).find('img').each(function(){
alt_var = $(this).attr('alt');
});
if(temp.indexOf('.csv') != -1){arr.push(temp); filenames.push(alt_var);}
});
for(i = 0; i < arr.length; ++i)
{
var x = document.createElement('li');
var a = document.createElement('a');
var t = document.createTextNode(" " + filenames[i]);
var fullURL = baseURL + arr[i];
a.setAttribute('href',"#");
a.setAttribute('class', "glyphicon glyphicon-file");
a.setAttribute('id', baseURL + arr[i]);
a.setAttribute('onclick', "drawChart(this.id)");
a.appendChild(t);
x.appendChild(a);
document.getElementById("dropdownfiles").appendChild(x);
}
});
</script>
How can I change this to search an external url. (PS new to Javascript)
Not sure if this is the cleanest way but you could add a hidden iframe on the page and then search in there.
css:
.externalSearcher iframe {
display: none;
}
html:
<div class="externalSearcher"></div>
js:
$('.externalSearcher').append('<iframe src="' + externalLink + '"></iframe>');
$('.externalSearcher').find('a').each(function () {
//do what you want with the link
});
I have an email link that uses javascript to protect the email address but I want to replace the link text with an image. How would I do this?
This is an example what I have on my website with the words "email me" as the clickable email link which I would like to replace with an image instead:
<script>mail2("name","fake-email",1,"?subject=Referral from website" "Email Me")</script>
And this is the code from the js file:
// Email.js version 5
var tld_ = new Array()
tld_[0] = "com";
tld_[1] = "com.au";
tld_[2] = "net";
tld_[3] = "ws";
tld_[4] = "info";
tld_[10] = "co.uk";
tld_[11] = "org.uk";
tld_[12] = "gov.uk";
tld_[13] = "ac.uk";
var topDom_ = 13;
var m_ = "mailto:";
var a_ = "#";
var d_ = ".";
function mail(name, dom, tl, params)
{
var s = e(name,dom,tl);
document.write(''+s+'');
}
function mail2(name, dom, tl, params, display)
{
document.write(''+display+'');
}
function e(name, dom, tl)
{
var s = name+a_;
if (tl!=-2)
{
s+= dom;
if (tl>=0)
s+= d_+tld_[tl];
}
else
s+= swapper(dom);
return s;
}
function swapper(d)
{
var s = "";
for (var i=0; i<d.length; i+=2)
if (i+1==d.length)
s+= d.charAt(i)
else
s+= d.charAt(i+1)+d.charAt(i);
return s.replace(/\?/g,'.');
}
What you want to do is send your image as the display variable like the following...
<script>mail2("name","fake-email",1,"?subject=Referral from website",'<img src="src/to/image.jpg" />')</script>
I'm trying to change the url's and words using greasemonkey
Example :
www.rapid*share.com
www.*Forbidden*
*Forbidden*
i want change word's
rapid*share to rapidshare
*forbidden * to mediafire.com
*forbidden * to narutopedia
userscript:
var words = {
"rapid*share":"rapidshare",
"*Forbidden*":"www.mediafire.com",
"*Forbidden*":"narutopedia",
"":""};
// read
String.prototype.prepareRegex = function() {
return this.replace(/([\[\]\^\&\$\.\(\)\?\/\\\+\{\}\|])/g, "\\$1");
};
// tag
function isOkTag(tag) {
return (new RegExp("(," + tag + ",) | (," + tag + "$)", "g").test(",pre,blockquote,code,input,button,textarea")) == false;
}
// convert word
var regexs=new Array(),
replacements=new Array();
for(var word in words) {
if(word != "") {
regexs.push(new RegExp(word.prepareRegex().replace(/(\\)?\*/g, function(e) {return ((e !== "\\*") ? "[^ ]*" : "*");}), "gi"));
replacements.push(words[word]);
}
}
//
var texts = document.evaluate(".//text()[normalize-space(.)!='']",document.body,null,6,null), text="", len=regexs.length;
for(var i=0,l=texts.snapshotLength; (this_text=texts.snapshotItem(i)); i++) {
if(isOkTag(this_text.parentNode.tagName) && (text=this_text.textContent)) {
for(var x=0; x<len; x++) text = this_text.textContent = text.replace(regexs[x], replacements[x]);
}
}
//replace url or link
var links = document.links;
var link;
for(var i=links.length-1; i >=0; i--){
link = links[i];
link.href = link.href.replace("http://www.rapid*share.com", 'http://www.rapidshare.com');
link.href = link.href.replace("http://www.zid*du.com", 'http://www.ziddu.com');
}
output, change only word but not url, and forbidden all change to narutopedia.
www.rapidshare.com
narutopedia
<!-- text -->
narutopedia
jsfiddle here
any solution?
thanks
Solution For Change Url
var url1,url2;
url1 = ['www.youtube.com','youtube.com', 'www.video.google.com', 'video.google.com', 'adbanner', 'advertisement', 'adserver', 'doubleclick'];
url2 = ['208.65.153.242','208.65.153.242', 'video.l.google.com', 'video.l.google.com', ' ', ' ',' ',' ' ];
var a, links;
var tmp="a";
var p,q;
links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
a = links[i];
for(var j=0;j<url1.length; j++)
{
tmp = a.href+"" ;
if(tmp.indexOf(url1[j]) != -1)
{
p=tmp.indexOf(url1[j]) ;
q="http://";
q = q + url2[j] + tmp.substring(p+url1[j].length,tmp.length);
a.href=q ;
}
}
}
Change the lines
link.href = link.href.replace("http://www.rapid*share.com", 'http://www.rapidshare.com');
link.href = link.href.replace("http://www.zid*du.com", 'http://www.ziddu.com');
to
link.href = link.href.replace("http://www.rapid%2Ashare.com", 'http://www.rapidshare.com');
link.href = link.href.replace("http://www.zid%2Adu.com", 'http://www.ziddu.com');
My problem is the following:
I have a page with many links
Some of them have a specific pattern :
http://www.example.com/.../?parameter1=...¶meter2=PARAMETER2
What i want to do is to change these links' href to the value of the parameter2 using JavaScript.
For example if i have a link like :
text here
what i want to do after the script runs is to have a link like this:
text here
Any suggestion would be truly appreciated!!!
Thank you all in advance!!!
If you are using jquery
then use the following code
$(function() {
$("a[href^='www.example.com']").each(function(){
var ele = $(this);
var href = ele.attr("href");console.log(href);
var index = href.lastIndexOf("parameter2");
var param_2 = href.substring((index + 11));
ele.attr("href", param_2);
});
});
http://jsfiddle.net/LVNeC/
function getUrlVars(_url)
{
var vars = [], hash;
var hashes = _url.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var myLINK = document.getElementById("mylink");
var url = myLINK.href;
myLINK.href = getUrlVars(url )["parameter2"];