/src/js/snowplow.js

https://github.com/gergelyke/snowplow-javascript-tracker · JavaScript · 250 lines · 96 code · 29 blank · 125 comment · 16 complexity · 3bb320a8d2bc9dc51800b4b0bbb5cc14 MD5 · raw file

  1. /*
  2. * JavaScript tracker for Snowplow: snowplow.js
  3. *
  4. * Significant portions copyright 2010 Anthon Pang. Remainder copyright
  5. * 2012-2014 Snowplow Analytics Ltd. All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are
  9. * met:
  10. *
  11. * * Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. *
  14. * * Redistributions in binary form must reproduce the above copyright
  15. * notice, this list of conditions and the following disclaimer in the
  16. * documentation and/or other materials provided with the distribution.
  17. *
  18. * * Neither the name of Anthon Pang nor Snowplow Analytics Ltd nor the
  19. * names of their contributors may be used to endorse or promote products
  20. * derived from this software without specific prior written permission.
  21. *
  22. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  25. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  26. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  27. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  28. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  29. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  30. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  31. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  32. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  33. */
  34. /*jslint browser:true, plusplus:true, vars:true, nomen:true, evil:true */
  35. /*global window */
  36. /*global unescape */
  37. /*global ActiveXObject */
  38. /*global _snaq:true */
  39. /*members encodeURIComponent, decodeURIComponent, getElementsByTagName,
  40. shift, unshift,
  41. addEventListener, attachEvent, removeEventListener, detachEvent,
  42. cookie, domain, readyState, documentElement, doScroll, title, text,
  43. location, top, document, referrer, parent, links, href, protocol, GearsFactory,
  44. event, which, button, srcElement, type, target,
  45. parentNode, tagName, hostname, className,
  46. userAgent, cookieEnabled, platform, mimeTypes, enabledPlugin, javaEnabled,
  47. XDomainRequest, XMLHttpRequest, ActiveXObject, open, setRequestHeader, onreadystatechange, setRequestHeader, send, readyState, status,
  48. getTime, getTimeAlias, setTime, toGMTString, getHours, getMinutes, getSeconds,
  49. toLowerCase, charAt, indexOf, lastIndexOf, split, slice, toUpperCase,
  50. onload, src,
  51. round, random,
  52. exec,
  53. res, width, height,
  54. pdf, qt, realp, wma, dir, fla, java, gears, ag,
  55. hook, getHook,
  56. setCollectorCf, setCollectorUrl, setAppId,
  57. setDownloadExtensions, addDownloadExtensions,
  58. setDomains, setIgnoreClasses, setRequestMethod,
  59. setReferrerUrl, setCustomUrl, setDocumentTitle,
  60. setDownloadClasses, setLinkClasses,
  61. discardHashTag,
  62. setCookieNamePrefix, setCookieDomain, setCookiePath, setVisitorIdCookie,
  63. setVisitorCookieTimeout, setSessionCookieTimeout, setReferralCookieTimeout,
  64. doNotTrack, respectDoNotTrack, msDoNotTrack, getTimestamp, getCookieValue,
  65. detectTimezone, detectViewport,
  66. addListener, enableLinkTracking, enableActivityTracking, setLinkTrackingTimer,
  67. enableDarkSocialTracking,
  68. killFrame, redirectFile, setCountPreRendered,
  69. trackLink, trackPageView, trackImpression,
  70. addPlugin, getAsyncTracker
  71. */
  72. ;(function() {
  73. // Load all our modules (at least until we fully modularize & remove grunt-concat)
  74. var
  75. tracker = require('./tracker'),
  76. helpers = require('./lib/helpers'),
  77. queue = require('./queue'),
  78. config = require('./config.json'),
  79. namespace = config.namespace,
  80. object = typeof exports !== 'undefined' ? exports : this; // For eventual node.js environment support
  81. object.Snowplow = function() {
  82. var
  83. documentAlias = document,
  84. windowAlias = window,
  85. /* Tracker identifier with version */
  86. version = 'js-1.0.0', // Update banner.js too
  87. /* Contains three variables that are shared with tracker.js and must be passed by reference */
  88. mutSnowplowState = {
  89. expireDateTime: null,
  90. /* DOM Ready */
  91. hasLoaded: false,
  92. registeredOnLoadHandlers: []
  93. },
  94. /* Asynchronous tracker */
  95. asyncTracker = null;
  96. /************************************************************
  97. * Private methods
  98. ************************************************************/
  99. /*
  100. * Handle beforeunload event
  101. *
  102. * Subject to Safari's "Runaway JavaScript Timer" and
  103. * Chrome V8 extension that terminates JS that exhibits
  104. * "slow unload", i.e., calling getTime() > 1000 times
  105. */
  106. function beforeUnloadHandler() {
  107. var now;
  108. /*
  109. * Delay/pause (blocks UI)
  110. */
  111. if (mutSnowplowState.expireDateTime) {
  112. // the things we do for backwards compatibility...
  113. // in ECMA-262 5th ed., we could simply use:
  114. // while (Date.now() < mutSnowplowState.expireDateTime) { }
  115. do {
  116. now = new Date();
  117. } while (now.getTime() < mutSnowplowState.expireDateTime);
  118. }
  119. }
  120. /*
  121. * Handler for onload event
  122. */
  123. function loadHandler() {
  124. var i;
  125. if (!mutSnowplowState.hasLoaded) {
  126. mutSnowplowState.hasLoaded = true;
  127. for (i = 0; i < mutSnowplowState.registeredOnLoadHandlers.length; i++) {
  128. mutSnowplowState.registeredOnLoadHandlers[i]();
  129. }
  130. }
  131. return true;
  132. }
  133. /*
  134. * Add onload or DOM ready handler
  135. */
  136. function addReadyListener() {
  137. var _timer;
  138. if (documentAlias.addEventListener) {
  139. helpers.addEventListener(documentAlias, 'DOMContentLoaded', function ready() {
  140. documentAlias.removeEventListener('DOMContentLoaded', ready, false);
  141. loadHandler();
  142. });
  143. } else if (documentAlias.attachEvent) {
  144. documentAlias.attachEvent('onreadystatechange', function ready() {
  145. if (documentAlias.readyState === 'complete') {
  146. documentAlias.detachEvent('onreadystatechange', ready);
  147. loadHandler();
  148. }
  149. });
  150. if (documentAlias.documentElement.doScroll && windowAlias === windowAlias.top) {
  151. (function ready() {
  152. if (!mutSnowplowState.hasLoaded) {
  153. try {
  154. documentAlias.documentElement.doScroll('left');
  155. } catch (error) {
  156. setTimeout(ready, 0);
  157. return;
  158. }
  159. loadHandler();
  160. }
  161. }());
  162. }
  163. }
  164. // sniff for older WebKit versions
  165. if ((new RegExp('WebKit')).test(navigator.userAgent)) {
  166. _timer = setInterval(function () {
  167. if (mutSnowplowState.hasLoaded || /loaded|complete/.test(documentAlias.readyState)) {
  168. clearInterval(_timer);
  169. loadHandler();
  170. }
  171. }, 10);
  172. }
  173. // fallback
  174. helpers.addEventListener(windowAlias, 'load', loadHandler, false);
  175. }
  176. /************************************************************
  177. * Constructor
  178. ************************************************************/
  179. // initialize the Snowplow singleton
  180. helpers.addEventListener(windowAlias, 'beforeunload', beforeUnloadHandler, false);
  181. addReadyListener();
  182. asyncTracker = new tracker.Tracker(version, mutSnowplowState); // No argmap
  183. // Now replace initialization array with proxy object
  184. if (namespace) {
  185. windowAlias[namespace]._snaq = new queue.AsyncQueueProxy(asyncTracker, windowAlias[namespace]._snaq);
  186. } else {
  187. windowAlias._snaq = new queue.AsyncQueueProxy(asyncTracker, windowAlias._snaq);
  188. }
  189. /************************************************************
  190. * Public data and methods
  191. ************************************************************/
  192. return {
  193. /**
  194. * Returns a Tracker object, configured with a
  195. * CloudFront collector.
  196. *
  197. * @param string distSubdomain The subdomain on your CloudFront collector's distribution
  198. */
  199. getTrackerCf: function (distSubdomain) {
  200. return new tracker.Tracker(version, mutSnowplowState, {cf: distSubdomain});
  201. },
  202. /**
  203. * Returns a Tracker object, configured with the
  204. * URL to the collector to use.
  205. *
  206. * @param string rawUrl The collector URL minus protocol and /i
  207. */
  208. getTrackerUrl: function (rawUrl) {
  209. return new tracker.Tracker(version, mutSnowplowState, {url: rawUrl});
  210. },
  211. /**
  212. * Get internal asynchronous tracker object
  213. *
  214. * @return Tracker
  215. */
  216. getAsyncTracker: function () {
  217. return asyncTracker;
  218. }
  219. }
  220. }
  221. }());