0

I'm looking for a way of tracking all outbound clicks from a web page using Javascript/ JQuery without modifying any of the existing page code. The solution must work with frames, iframes, content from different domains, AJAX etc.

Perhaps, Javascript is the wrong technology for a universal solution. If so, please let me know what would be better.

jnthnclrk
  • 469
  • 6
  • 29

2 Answers2

3

It's easy enough to capture all clicks on external links.

$(document).ready(function() {
    $("a[@href^=http]").each(function(){
        if(this.href.indexOf(location.hostname) == -1) {
            // Handle click here
        }
    });
});

Getting this to work for iframes is a little trickier. The iframe should reside from the same domain due to the Same origin policy. If so you should be able to change the css selector above to something like $("#iframe_id").contents().find("[@href^=http]")

Cory House
  • 14,235
  • 13
  • 70
  • 87
ChrisR
  • 14,370
  • 16
  • 70
  • 107
  • Need a solution that works for content originating from different domains. – jnthnclrk Feb 23 '11 at 22:17
  • Would this work if I used a PHP function like file_get_contents to get all the content onto the same domain? – jnthnclrk Feb 24 '11 at 11:07
  • You are talking serverside now ... i don't know what you are aiming for but no, the code i posted is pure clientside and can't capture serverside requests. That would require you to capture the requests serverside. – ChrisR Feb 24 '11 at 12:16
0

There is an easy solution:

get all a elements
    check href to see if it begins with http or https
        if so and the domain is external to your site, add a click handler
Finbarr
  • 31,350
  • 13
  • 63
  • 94