Click Logging with JavaScript

后端 未结 5 593
挽巷
挽巷 2021-01-03 01:55

I want to log all clicks on a link.

I\'ve written a little logger, which can be called by an url (returns an empty page). This url is called with a jquery-ajax-metho

5条回答
  •  心在旅途
    2021-01-03 03:01

    This example will fire off an ajax post before the link click is processed. I found I had to call ajax synchronously or the POST will not be executed. In this example my ajax post is to a PHP page which appends a log file. This example is efficient since it only attaches a click event to the window. It also will not interfere with a user clicking a link.

    //attach click event to window
    attachClickEvent = function() {
        $(document).on('click', function(e) { //document for IE8 compatibility
            var element = $(e.target);
            var tag = element.prop('tagName');
    
            if (tag === 'A') {
                var data = {'title':document.title, 'URL':element.attr('href'), 'origin':location.href};
                logData(data);
            }
        });
    }
    
    logData = function(data) {
        $.ajax({
            async: false,
            cache: false,
            type: "POST",
            data: data,
            url: 'logger.php',
            success: function(msg) { 
                //debugging
            },
            error: function() {
                //debugging
            }
        });
    }
    

提交回复
热议问题