Ardi Vaba
Ardi Vaba

Reputation: 189

Detect external link Click?

How can i detect external link click?

I have a simple question, which may or may not have an simple answer. I need to detect if some of my page's user's have clicked an external link, an ad for example.

My first tought was that i would place an random number of transparent div's over a specific link so an user should click on it until he'll get redirected to a new page but that would be inconvievnant for users and would still be exploitable.

I hope that you guys can help me out and i'll do my best to help you out one day.

Sorry for my english as my native language isn't english.

Upvotes: 4

Views: 4200

Answers (4)

crmpicco
crmpicco

Reputation: 17181

You can track outbound clicks that do not belong to the current site by doing the following:

jQuery(document).ready(function($) {
    $('body').on('click', 'a[href^="http"]:not([href*="//' + location.host + '"])', function(){
        if (typeof(_gaq) !== 'undefined') {
            _gaq.push(['_trackEvent', 'outbound', 'click', this.href.match(/\/\/([^\/]+)/)[1]]);
            _gaq.push(['t2._trackEvent', 'outbound', 'click', this.href.match(/\/\/([^\/]+)/)[1]]);
        }
    });
});

Obviously you can strip out the Google Analytics gaq stuff if you don't need it.

Upvotes: 1

Ailef
Ailef

Reputation: 7906

If you can add an extra class to the links you could do something like that:

<a href="http://www.externalsite.com/" class="external">AD</a>

i.e. add an "external" class to every link, and then use jquery like this:

$('.external').click(function(event) {
    // do something before the user gets redirected
});

You could also use event.preventDefault() to prevent the default action (i.e. redirecting the user) and then do something else.

EDIT If you can't add class="external" directly into the markup, you could add it dinamycally using jQuery using some code like:

$('a').each(function() {
    if($(this).attr('href') is an external link) {
        $(this).addClass('external');
    }
});

I've not tested this second snippet but it should work.

Upvotes: -3

guido
guido

Reputation: 19224

with jquery, select all external links and an handler for click event:

// Creating custom :external selector
$.expr[':'].external = function(obj){
    return !obj.href.match(/^mailto\:/)
            && (obj.hostname != location.hostname);
};

// Manage clicks on external links
$('a:external').click(function() {
    // do your stuff here, ie send the link href to some server-side script
    $.ajax({ type: "POST", url: "some.php", data: "href="+$(this).attr("href") });
});

Upvotes: 6

Neeraj
Neeraj

Reputation: 8532

Hey, you really need to use google analytics. Incase you do not want to do that, check this out. Logging hyperlink clicks on my website

Upvotes: 1

Related Questions