Search code examples
javascriptclickhrefevent-listenerabsolute-path

Prepend URL to all clicks with absolute paths executed on a page


I have this issue with advertising agencies delivering ads with no parameters for click tracking URLs.

In my example, the click URL will be: http://landing-page.com

My tracking URL will be: http://tracker.com?url=

The desired effect is, that when a user clicks on any link on the creative, he will be sent to:

http://tracker.com?url=http://landing-page.com

The catch is, that the links are defined by using <a> tags or a click eventListeners. Either with onclick or addEventListener('click', func))

I can iterate through all a[href^=http]s.

How do I catch/prepend my URL to the event listeners?

Many thanks in advance

EDIT:

So for the hrefs I am doing something like this:

<script>
  var links = adContainer.querySelectorAll('a[href^=http]');
  window.adclick = 'http://tracker.com?url='
  for (var i = 0; i < links.length; i++) {
    (function(i) {
      links[i].addEventListener('click', function(e) {
        window.open(window.adclick + links[i].href, '_blank');
        e.preventDefault();
      });
    })(i);
  }
</script>

The issue I have, is that I cannot work out, or find out online how to do something similar with an event listener.


Solution

  • After some more trying, I have found a dead easy solution.

    I should still check if the URL starts with http - but you get the gist:

    window._open = window.open;
    
    window.open = function(url, target) {
      window._open('http://tracker.com?url=' + url, target);
    }