开发者

Detect external link Click?

How can i detect external link cli开发者_如何学Pythonck?

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.


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") });
});


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜