I'm using Google Tag Manager to fire Facebook pixels among my other analytics scripts. Without getting into too much detail, what I want to do is the following:
My custom html tag code:
<script> var element = {{Click Element}};; var linkclickurl = '{{Click URL}}'; alert('Click URL is ' + linkclickurl + '. Hostname is {{Page Hostname}}'); // Check if hostname is contained in linkclickurl if(linkclickurl.indexOf("{{Page Hostname}}") > -1) { alert('Not outbound link'); } else { // Check if query string already exists if(linkclickurl.indexOf("?") > -1) { window.location.href = linkclickurl + '&fb=1'; alert('Found a query'); } else { window.location.href = linkclickurl + '?fb=1'; alert('Found no query'); } } </script>
So my current problem is that I don't know how to stop the link from propagating after the link click. I'm changing the href after the fact which does nothing as the page will redirect to the original link.
Is there a way to stop the link from propagating if it is outbound and then switch it to the updated version?
Taking @sdhaus advice, I was able to do this with the following script:
function updateLinks(parameter, value) { var links = document.getElementsByTagName('a'); var includeDomains = self.location.host; for (var i=0;i<links.length;i++) { if(links[i].href != "#" && links[i].href != "/" && links[i].href != "" && links[i].href != window.location) //Ignore links with empty src attribute, linking to site root, or anchor tags (#) { var updateLink = true; if(links[i].href.toLowerCase().indexOf(includeDomains.toLowerCase()) != -1) //Domain of current link is included i the includeDomains array. Update Required... { updateLink = false; } if(!updateLink) { //Do nothing - link is internal } else { var queryStringComplete = ""; var paramCount = 0; var linkParts = links[i].href.split("?"); if(linkParts.length > 1) // Has Query String Params { queryStringComplete = "?"; var fullQString = linkParts[1]; var paramArray = fullQString.split("&"); var found = false; for (j=0;j<paramArray.length;j++) { var currentParameter = paramArray[j].split("="); if(paramCount > 0) queryStringComplete = queryStringComplete + "&"; if(currentParameter[0] == parameter) //Parameter exists in url, refresh value { queryStringComplete = queryStringComplete + parameter + "=" + value; found = true; } else { queryStringComplete = queryStringComplete + paramArray[j]; //Not related parameter - re-include in url } paramCount++; } if(!found) //Add new param to end of query string queryStringComplete = queryStringComplete + "&" + parameter + "=" + value; } else { queryStringComplete = "?" + parameter + "=" + value; } links[i].href = links[i].href.split("?")[0] + queryStringComplete; } } else { //Do nothing } } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.