Search code examples
javascriptgoogle-analyticsanalytics

Real-time basic web analytics with Javascript


I need to develop an in-house real-time analytics solution (similar to GA or mixpanel for example) that collects:

  • Information from the website itself ­­(URL)
  • Information from the user’s browser ­­(lang, device, OS etc..)
  • Information from the referring source etc..

.. and sends this data to the server with a single-pixel image request. Similar to how GA and other solutions work:

Google Analytics works by the inclusion of a block of JavaScript code on pages in your website. When users to your website view a page, this JavaScript code references a JavaScript file which then executes the tracking operation for Analytics. The tracking operation retrieves data about the page request through various means and sends this information to the Analytics server via a list of parameters attached to a single-pixel image request.

I wonder if there's any open source project available that does this part which I could use as base to build further. There's Piwik but its too feature-packed and too heavy for my requirement.

Edited to add: I'm doing something specific with the data, otherwise I'd just use the existing solutions.


Solution

  • Try

    var img = new Image;
    img.width = img.height = "1px";
    var res = window.navigator;
    var data = {};
    var _plugins = {};
    Array.prototype.slice.call(navigator.plugins).forEach(function(v, k) {
      _plugins[v.name.toLowerCase().replace(/\s/, "-")] = {
        "name": v.name,
        "description": v.description,
        "filename": v.filename
      }
    });
    delete res.plugins && delete res.mimeTypes;
    data.url = window.location.href;
    data.ref = document.referrer;
    data.nav = res;
    data._plugins = _plugins;
    // set `img` `dataset` with `data` ,
    // send `img` to server , decode `img` `dataset` at server
    img.dataset.stats = JSON.stringify(data);
    

    var img = new Image;
    img.width = img.height = "1px";
    var res = window.navigator;
    var data = {};
    var _plugins = {};
    Array.prototype.slice.call(navigator.plugins).forEach(function(v, k) {
      _plugins[v.name.toLowerCase().replace(/\s/, "-")] = {
        "name": v.name,
        "description": v.description,
        "filename": v.filename
      }
    });
    delete res.plugins && delete res.mimeTypes;
    data.url = window.location.href;
    data.ref = document.referrer;
    data.nav = res;
    data._plugins = _plugins;
    img.dataset.stats = JSON.stringify(data);
    document.write(
      img.dataset.stats       
    );