You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

core.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. var _excluded = ["category", "action", "label", "value", "nonInteraction", "transport"];
  2. function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
  3. function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
  4. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
  5. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
  6. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  7. function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
  8. function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
  9. function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
  10. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  11. function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
  12. function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
  13. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  14. /**
  15. * React Google Analytics Module
  16. *
  17. * @package react-ga
  18. * @author Adam Lofting <adam@mozillafoundation.org>
  19. * Atul Varma <atul@mozillafoundation.org>
  20. */
  21. /**
  22. * Utilities
  23. */
  24. import format from './utils/format';
  25. import removeLeadingSlash from './utils/removeLeadingSlash';
  26. import trim from './utils/trim';
  27. import loadGA from './utils/loadGA';
  28. import warn from './utils/console/warn';
  29. import log from './utils/console/log';
  30. import TestModeAPI from './utils/testModeAPI';
  31. var _isNotBrowser = typeof window === 'undefined' || typeof document === 'undefined';
  32. var _debug = false;
  33. var _titleCase = true;
  34. var _testMode = false;
  35. var _alwaysSendToDefaultTracker = true;
  36. var _redactEmail = true;
  37. var internalGa = function internalGa() {
  38. var _window;
  39. if (_testMode) return TestModeAPI.ga.apply(TestModeAPI, arguments);
  40. if (_isNotBrowser) return false;
  41. if (!window.ga) return warn('ReactGA.initialize must be called first or GoogleAnalytics should be loaded manually');
  42. return (_window = window).ga.apply(_window, arguments);
  43. };
  44. function _format(s) {
  45. return format(s, _titleCase, _redactEmail);
  46. }
  47. function _gaCommand(trackerNames) {
  48. for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  49. args[_key - 1] = arguments[_key];
  50. }
  51. var command = args[0];
  52. if (typeof internalGa === 'function') {
  53. if (typeof command !== 'string') {
  54. warn('ga command must be a string');
  55. return;
  56. }
  57. if (_alwaysSendToDefaultTracker || !Array.isArray(trackerNames)) internalGa.apply(void 0, args);
  58. if (Array.isArray(trackerNames)) {
  59. trackerNames.forEach(function (name) {
  60. internalGa.apply(void 0, _toConsumableArray(["".concat(name, ".").concat(command)].concat(args.slice(1))));
  61. });
  62. }
  63. }
  64. }
  65. function _initialize(gaTrackingID, options) {
  66. if (!gaTrackingID) {
  67. warn('gaTrackingID is required in initialize()');
  68. return;
  69. }
  70. if (options) {
  71. if (options.debug && options.debug === true) {
  72. _debug = true;
  73. }
  74. if (options.titleCase === false) {
  75. _titleCase = false;
  76. }
  77. if (options.redactEmail === false) {
  78. _redactEmail = false;
  79. }
  80. if (options.useExistingGa) {
  81. return;
  82. }
  83. }
  84. if (options && options.gaOptions) {
  85. internalGa('create', gaTrackingID, options.gaOptions);
  86. } else {
  87. internalGa('create', gaTrackingID, 'auto');
  88. }
  89. }
  90. export function addTrackers(configsOrTrackingId, options) {
  91. if (Array.isArray(configsOrTrackingId)) {
  92. configsOrTrackingId.forEach(function (config) {
  93. if (_typeof(config) !== 'object') {
  94. warn('All configs must be an object');
  95. return;
  96. }
  97. _initialize(config.trackingId, config);
  98. });
  99. } else {
  100. _initialize(configsOrTrackingId, options);
  101. }
  102. return true;
  103. }
  104. export function initialize(configsOrTrackingId, options) {
  105. if (options && options.testMode === true) {
  106. _testMode = true;
  107. } else {
  108. if (_isNotBrowser) {
  109. return;
  110. }
  111. if (!options || options.standardImplementation !== true) loadGA(options);
  112. }
  113. _alwaysSendToDefaultTracker = options && typeof options.alwaysSendToDefaultTracker === 'boolean' ? options.alwaysSendToDefaultTracker : true;
  114. addTrackers(configsOrTrackingId, options);
  115. }
  116. /**
  117. * ga:
  118. * Returns the original GA object.
  119. */
  120. export function ga() {
  121. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  122. args[_key2] = arguments[_key2];
  123. }
  124. if (args.length > 0) {
  125. internalGa.apply(void 0, args);
  126. if (_debug) {
  127. log("called ga('arguments');");
  128. log("with arguments: ".concat(JSON.stringify(args)));
  129. }
  130. }
  131. return window.ga;
  132. }
  133. /**
  134. * set:
  135. * GA tracker set method
  136. * @param {Object} fieldsObject - a field/value pair or a group of field/value pairs on the tracker
  137. * @param {Array} trackerNames - (optional) a list of extra trackers to run the command on
  138. */
  139. export function set(fieldsObject, trackerNames) {
  140. if (!fieldsObject) {
  141. warn('`fieldsObject` is required in .set()');
  142. return;
  143. }
  144. if (_typeof(fieldsObject) !== 'object') {
  145. warn('Expected `fieldsObject` arg to be an Object');
  146. return;
  147. }
  148. if (Object.keys(fieldsObject).length === 0) {
  149. warn('empty `fieldsObject` given to .set()');
  150. }
  151. _gaCommand(trackerNames, 'set', fieldsObject);
  152. if (_debug) {
  153. log("called ga('set', fieldsObject);");
  154. log("with fieldsObject: ".concat(JSON.stringify(fieldsObject)));
  155. }
  156. }
  157. /**
  158. * send:
  159. * Clone of the low level `ga.send` method
  160. * WARNING: No validations will be applied to this
  161. * @param {Object} fieldObject - field object for tracking different analytics
  162. * @param {Array} trackerNames - trackers to send the command to
  163. * @param {Array} trackerNames - (optional) a list of extra trackers to run the command on
  164. */
  165. export function send(fieldObject, trackerNames) {
  166. _gaCommand(trackerNames, 'send', fieldObject);
  167. if (_debug) {
  168. log("called ga('send', fieldObject);");
  169. log("with fieldObject: ".concat(JSON.stringify(fieldObject)));
  170. log("with trackers: ".concat(JSON.stringify(trackerNames)));
  171. }
  172. }
  173. /**
  174. * pageview:
  175. * Basic GA pageview tracking
  176. * @param {String} path - the current page page e.g. '/about'
  177. * @param {Array} trackerNames - (optional) a list of extra trackers to run the command on
  178. * @param {String} title - (optional) the page title e. g. 'My Website'
  179. */
  180. export function pageview(rawPath, trackerNames, title) {
  181. if (!rawPath) {
  182. warn('path is required in .pageview()');
  183. return;
  184. }
  185. var path = trim(rawPath);
  186. if (path === '') {
  187. warn('path cannot be an empty string in .pageview()');
  188. return;
  189. }
  190. var extraFields = {};
  191. if (title) {
  192. extraFields.title = title;
  193. }
  194. if (typeof ga === 'function') {
  195. _gaCommand(trackerNames, 'send', _objectSpread({
  196. hitType: 'pageview',
  197. page: path
  198. }, extraFields));
  199. if (_debug) {
  200. log("called ga('send', 'pageview', path);");
  201. var extraLog = '';
  202. if (title) {
  203. extraLog = " and title: ".concat(title);
  204. }
  205. log("with path: ".concat(path).concat(extraLog));
  206. }
  207. }
  208. }
  209. /**
  210. * modalview:
  211. * a proxy to basic GA pageview tracking to consistently track
  212. * modal views that are an equivalent UX to a traditional pageview
  213. * @param {String} modalName e.g. 'add-or-edit-club'
  214. * @param {Array} trackerNames - (optional) a list of extra trackers to run the command on
  215. */
  216. export function modalview(rawModalName, trackerNames) {
  217. if (!rawModalName) {
  218. warn('modalName is required in .modalview(modalName)');
  219. return;
  220. }
  221. var modalName = removeLeadingSlash(trim(rawModalName));
  222. if (modalName === '') {
  223. warn('modalName cannot be an empty string or a single / in .modalview()');
  224. return;
  225. }
  226. if (typeof ga === 'function') {
  227. var path = "/modal/".concat(modalName);
  228. _gaCommand(trackerNames, 'send', 'pageview', path);
  229. if (_debug) {
  230. log("called ga('send', 'pageview', path);");
  231. log("with path: ".concat(path));
  232. }
  233. }
  234. }
  235. /**
  236. * timing:
  237. * GA timing
  238. * @param args.category {String} required
  239. * @param args.variable {String} required
  240. * @param args.value {Int} required
  241. * @param args.label {String} required
  242. * @param {Array} trackerNames - (optional) a list of extra trackers to run the command on
  243. */
  244. export function timing() {
  245. var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
  246. category = _ref.category,
  247. variable = _ref.variable,
  248. value = _ref.value,
  249. label = _ref.label;
  250. var trackerNames = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
  251. if (typeof ga === 'function') {
  252. if (!category || !variable || typeof value !== 'number') {
  253. warn('args.category, args.variable ' + 'AND args.value are required in timing() ' + 'AND args.value has to be a number');
  254. return;
  255. } // Required Fields
  256. var fieldObject = {
  257. hitType: 'timing',
  258. timingCategory: _format(category),
  259. timingVar: _format(variable),
  260. timingValue: value
  261. };
  262. if (label) {
  263. fieldObject.timingLabel = _format(label);
  264. }
  265. send(fieldObject, trackerNames);
  266. }
  267. }
  268. /**
  269. * event:
  270. * GA event tracking
  271. * @param args.category {String} required
  272. * @param args.action {String} required
  273. * @param args.label {String} optional
  274. * @param args.value {Int} optional
  275. * @param args.nonInteraction {boolean} optional
  276. * @param args.transport {string} optional
  277. * @param {{action: string, category: string}} trackerNames - (optional) a list of extra trackers to run the command on
  278. */
  279. export function event() {
  280. var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
  281. category = _ref2.category,
  282. action = _ref2.action,
  283. label = _ref2.label,
  284. value = _ref2.value,
  285. nonInteraction = _ref2.nonInteraction,
  286. transport = _ref2.transport,
  287. args = _objectWithoutProperties(_ref2, _excluded);
  288. var trackerNames = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
  289. if (typeof ga === 'function') {
  290. // Simple Validation
  291. if (!category || !action) {
  292. warn('args.category AND args.action are required in event()');
  293. return;
  294. } // Required Fields
  295. var fieldObject = {
  296. hitType: 'event',
  297. eventCategory: _format(category),
  298. eventAction: _format(action)
  299. }; // Optional Fields
  300. if (label) {
  301. fieldObject.eventLabel = _format(label);
  302. }
  303. if (typeof value !== 'undefined') {
  304. if (typeof value !== 'number') {
  305. warn('Expected `args.value` arg to be a Number.');
  306. } else {
  307. fieldObject.eventValue = value;
  308. }
  309. }
  310. if (typeof nonInteraction !== 'undefined') {
  311. if (typeof nonInteraction !== 'boolean') {
  312. warn('`args.nonInteraction` must be a boolean.');
  313. } else {
  314. fieldObject.nonInteraction = nonInteraction;
  315. }
  316. }
  317. if (typeof transport !== 'undefined') {
  318. if (typeof transport !== 'string') {
  319. warn('`args.transport` must be a string.');
  320. } else {
  321. if (['beacon', 'xhr', 'image'].indexOf(transport) === -1) {
  322. warn('`args.transport` must be either one of these values: `beacon`, `xhr` or `image`');
  323. }
  324. fieldObject.transport = transport;
  325. }
  326. }
  327. Object.keys(args).filter(function (key) {
  328. return key.substr(0, 'dimension'.length) === 'dimension';
  329. }).forEach(function (key) {
  330. fieldObject[key] = args[key];
  331. });
  332. Object.keys(args).filter(function (key) {
  333. return key.substr(0, 'metric'.length) === 'metric';
  334. }).forEach(function (key) {
  335. fieldObject[key] = args[key];
  336. }); // Send to GA
  337. send(fieldObject, trackerNames);
  338. }
  339. }
  340. /**
  341. * exception:
  342. * GA exception tracking
  343. * @param args.description {String} optional
  344. * @param args.fatal {boolean} optional
  345. * @param {Array} trackerNames - (optional) a list of extra trackers to run the command on
  346. */
  347. export function exception(_ref3, trackerNames) {
  348. var description = _ref3.description,
  349. fatal = _ref3.fatal;
  350. if (typeof ga === 'function') {
  351. // Required Fields
  352. var fieldObject = {
  353. hitType: 'exception'
  354. }; // Optional Fields
  355. if (description) {
  356. fieldObject.exDescription = _format(description);
  357. }
  358. if (typeof fatal !== 'undefined') {
  359. if (typeof fatal !== 'boolean') {
  360. warn('`args.fatal` must be a boolean.');
  361. } else {
  362. fieldObject.exFatal = fatal;
  363. }
  364. } // Send to GA
  365. send(fieldObject, trackerNames);
  366. }
  367. }
  368. export var plugin = {
  369. /**
  370. * require:
  371. * GA requires a plugin
  372. * @param name {String} e.g. 'ecommerce' or 'myplugin'
  373. * @param options {Object} optional e.g {path: '/log', debug: true}
  374. * @param trackerName {String} optional e.g 'trackerName'
  375. */
  376. require: function require(rawName, options, trackerName) {
  377. if (typeof ga === 'function') {
  378. // Required Fields
  379. if (!rawName) {
  380. warn('`name` is required in .require()');
  381. return;
  382. }
  383. var name = trim(rawName);
  384. if (name === '') {
  385. warn('`name` cannot be an empty string in .require()');
  386. return;
  387. }
  388. var requireString = trackerName ? "".concat(trackerName, ".require") : 'require'; // Optional Fields
  389. if (options) {
  390. if (_typeof(options) !== 'object') {
  391. warn('Expected `options` arg to be an Object');
  392. return;
  393. }
  394. if (Object.keys(options).length === 0) {
  395. warn('Empty `options` given to .require()');
  396. }
  397. ga(requireString, name, options);
  398. if (_debug) {
  399. log("called ga('require', '".concat(name, "', ").concat(JSON.stringify(options)));
  400. }
  401. } else {
  402. ga(requireString, name);
  403. if (_debug) {
  404. log("called ga('require', '".concat(name, "');"));
  405. }
  406. }
  407. }
  408. },
  409. /**
  410. * execute:
  411. * GA execute action for plugin
  412. * Takes variable number of arguments
  413. * @param pluginName {String} e.g. 'ecommerce' or 'myplugin'
  414. * @param action {String} e.g. 'addItem' or 'myCustomAction'
  415. * @param actionType {String} optional e.g. 'detail'
  416. * @param payload {Object} optional e.g { id: '1x5e', name : 'My product to track' }
  417. */
  418. execute: function execute(pluginName, action) {
  419. var payload;
  420. var actionType;
  421. for (var _len3 = arguments.length, args = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
  422. args[_key3 - 2] = arguments[_key3];
  423. }
  424. if (args.length === 1) {
  425. payload = args[0];
  426. } else {
  427. actionType = args[0];
  428. payload = args[1];
  429. }
  430. if (typeof ga === 'function') {
  431. if (typeof pluginName !== 'string') {
  432. warn('Expected `pluginName` arg to be a String.');
  433. } else if (typeof action !== 'string') {
  434. warn('Expected `action` arg to be a String.');
  435. } else {
  436. var command = "".concat(pluginName, ":").concat(action);
  437. payload = payload || null;
  438. if (actionType && payload) {
  439. ga(command, actionType, payload);
  440. if (_debug) {
  441. log("called ga('".concat(command, "');"));
  442. log("actionType: \"".concat(actionType, "\" with payload: ").concat(JSON.stringify(payload)));
  443. }
  444. } else if (payload) {
  445. ga(command, payload);
  446. if (_debug) {
  447. log("called ga('".concat(command, "');"));
  448. log("with payload: ".concat(JSON.stringify(payload)));
  449. }
  450. } else {
  451. ga(command);
  452. if (_debug) {
  453. log("called ga('".concat(command, "');"));
  454. }
  455. }
  456. }
  457. }
  458. }
  459. };
  460. /**
  461. * outboundLink:
  462. * GA outboundLink tracking
  463. * @param args.label {String} e.g. url, or 'Create an Account'
  464. * @param {function} hitCallback - Called after processing a hit.
  465. */
  466. export function outboundLink(args, hitCallback, trackerNames) {
  467. if (typeof hitCallback !== 'function') {
  468. warn('hitCallback function is required');
  469. return;
  470. }
  471. if (typeof ga === 'function') {
  472. // Simple Validation
  473. if (!args || !args.label) {
  474. warn('args.label is required in outboundLink()');
  475. return;
  476. } // Required Fields
  477. var fieldObject = {
  478. hitType: 'event',
  479. eventCategory: 'Outbound',
  480. eventAction: 'Click',
  481. eventLabel: _format(args.label)
  482. };
  483. var safetyCallbackCalled = false;
  484. var safetyCallback = function safetyCallback() {
  485. // This prevents a delayed response from GA
  486. // causing hitCallback from being fired twice
  487. safetyCallbackCalled = true;
  488. hitCallback();
  489. }; // Using a timeout to ensure the execution of critical application code
  490. // in the case when the GA server might be down
  491. // or an ad blocker prevents sending the data
  492. // register safety net timeout:
  493. var t = setTimeout(safetyCallback, 250);
  494. var clearableCallbackForGA = function clearableCallbackForGA() {
  495. clearTimeout(t);
  496. if (!safetyCallbackCalled) {
  497. hitCallback();
  498. }
  499. };
  500. fieldObject.hitCallback = clearableCallbackForGA; // Send to GA
  501. send(fieldObject, trackerNames);
  502. } else {
  503. // if ga is not defined, return the callback so the application
  504. // continues to work as expected
  505. setTimeout(hitCallback, 0);
  506. }
  507. }
  508. export var testModeAPI = TestModeAPI;
  509. export default {
  510. initialize: initialize,
  511. ga: ga,
  512. set: set,
  513. send: send,
  514. pageview: pageview,
  515. modalview: modalview,
  516. timing: timing,
  517. event: event,
  518. exception: exception,
  519. plugin: plugin,
  520. outboundLink: outboundLink,
  521. testModeAPI: TestModeAPI
  522. };