Listening to all clicks on a webpage

I recently thought of an interesting experiment. If I wanted to find out where users were clicking on a website, how would I go about it? It's trivial if it is a static webpage and the only clickable objects were new pages. You can just look at the server access logs. This quickly gets obsolete as soon as you are doing anything with JavaScript.

The way I found most usable was to listen to a click event on document.body. This doesn't interfere with any existing code. To find out which element they click on, I found that the name, attributes, and its CSSpath to the root were enough information to uniquely identify a node.

const fullDomPath = function(element) {  
  let path = [element.tagName.toLowerCase()];
  element = element.parentElement;
  while (element) {
    path.unshift(element.tagName.toLowerCase());
    element = element.parentElement;
  }
  return path.join(' > ');
};

const simplify = function(element) {  
  return {
    name: element.tagName.toLowerCase(),
    attributes: Array.from(element.attributes).map((i) => ({[i.nodeName]: i.nodeValue})),
    path: fullDomPath(element)
  };
};

document.body.addEventListener("click", function(event) {  
  let info = {
    event: {
      clientX: event.clientX,
      clientY: event.clientY
    },
    element: simplify(event.target)
  };
  console.log(JSON.stringify(info));
}, false);

Try it out with a sample webpage at JSFiddle.

Bret Lowrey

Code is like a war - the best code is one never written.

Florida, USA