Recording user data for heatmap with JavaScript

后端 未结 5 1650
孤独总比滥情好
孤独总比滥情好 2020-12-13 00:12

I was wondering how sites such as crazyegg.com store user click data during a session. Obviously there is some underlying script which is storing each clicks data, but how i

5条回答
  •  忘掉有多难
    2020-12-13 00:45

    The fundamental idea used by many tracking systems uses a 1x1px image which is requested with extra GET parameters. The request is added to server log file, then log files are processed to generate some statistics. So a minimalist click tracking function might look like this:

    document.onclick = function(e){
      var trackImg = new Image();
      trackImg.src = 'http://tracking.server/img.gif?x='+e.clientX+'&y='+e.clientY;
    }
    

    AJAX wouldn't be useful because it is subject to same-origin policy (you won't be able to send requests to your tracking server). And you'd have to add AJAX code to your tracking script. If you want to send more data (like cursor movements) you'd store the coordinates in a variable and periodically poll for a new image with updated path in the GET parameter.

    Now there are many many problems:

    • cross-browser compatibility - to make the above function work in all browsers that matter at the moment you'd probably have to add 20 more lines of code
    • getting useful data
      • many pages are fixed-width, centered, so raw X and Y coordinates won't let you create visual overlay of clicks n the page
      • some pages have liquid-width elements, or use a combination of min- and max-height
      • users may use different font sizes
      • dynamic elements that appear on the page in response to user's actions
    • etc. etc.

    When you have the tracking script worked out you only need to create a tool that takes raw server logs and turns them into shiny heatmaps :)

提交回复
热议问题