Skip to content

Instantly share code, notes, and snippets.

@entendu
Last active March 16, 2016 18:10
Show Gist options
  • Select an option

  • Save entendu/6c79814d289380734cbe to your computer and use it in GitHub Desktop.

Select an option

Save entendu/6c79814d289380734cbe to your computer and use it in GitHub Desktop.
Track when people print a page on your Drupal site thru Google Analytics events.
/**
* Track a Google Analytics event when people print.
*
* Inserts print-only CSS that's an image link to the GA collector, so it's only
* fired when someone tries to print.
*
* Inspired by https://sites.google.com/site/thedigitalinspiration/how-to-guides/use-google-analytics-to-track-when-people-print-your-web-pages
* and updated with a better tracking method for analytics.js.
*
* @author Domenic Santangelo <dsantangelo@magento.com>
*/
(function ($) {
Drupal.behaviors.track_print = {
attach : function() {
// A unique visitor identifier is required. Normally stored in the _ga
// cookie, but it's possible that cookie won't exist (adblockers, etc)
// so account fo that too. This logic requires jquery-cookie
// (https://github.com/carhartl/jquery-cookie) but you can swap in
// whatever method of retrieving the cookie you want.
var gaCid = "123456789.123456789";
try {
var gaCookieSplit = $.cookie('_ga').split('.');
gaCid = gaCookieSplit[2] + '.' + gaCookieSplit[3];
} catch(e) {}
// Prepare the GA account and DOM element:
var gaId = "UA-XXXXXXXX-Y"; // <--- insert your tracking code here
var css = document.createElement('style');
// See https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters
var gimg = "https://www.google-analytics.com/collect?v=1"
+ "&tid=" + gaId
+ "&cid=" + gaCid
+ "&t=event"
+ "&ec=Print"
+ "&ea=Printed"
// These values become URL-encoded and so are not an XSS risk.
+ "&el=" + window.location.pathname
+ "&dh=" + location.hostname
+ "&dp=" + window.location.pathname
;
// Generate a CSS rule inside a print media query and append it to <head>.
var cstr = "@media print {body:after";
cstr += "{content:url(" + gimg + ")}}";
var node = document.createTextNode(cstr);
if (css.styleSheet) {
css.styleSheet.cssText = node.nodeValue;
}
else {
css.appendChild(node);
}
var head = document.getElementsByTagName('head')[0];
if (head) {
head.appendChild(css);
}
}
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment