diff --git a/.gitignore b/.gitignore index 76add87..3c3629e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1 @@ node_modules -dist \ No newline at end of file diff --git a/dist/format.js b/dist/format.js new file mode 100644 index 0000000..ff86c3b --- /dev/null +++ b/dist/format.js @@ -0,0 +1,46 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = format; +var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i; +function toTitleCase(string) { + return string.toString().trim().replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g, function (match, index, title) { + if (index > 0 && index + match.length !== title.length && match.search(smallWords) > -1 && title.charAt(index - 2) !== ":" && (title.charAt(index + match.length) !== "-" || title.charAt(index - 1) === "-") && title.charAt(index - 1).search(/[^\s-]/) < 0) { + return match.toLowerCase(); + } + if (match.substr(1).search(/[A-Z]|\../) > -1) { + return match; + } + return match.charAt(0).toUpperCase() + match.substr(1); + }); +} + +// See if s could be an email address. We don't want to send personal data like email. +// https://support.google.com/analytics/answer/2795983?hl=en +function mightBeEmail(s) { + // There's no point trying to validate rfc822 fully, just look for ...@... + return typeof s === "string" && s.indexOf("@") !== -1; +} +var redacted = "REDACTED (Potential Email Address)"; +function redactEmail(string) { + if (mightBeEmail(string)) { + console.warn("This arg looks like an email address, redacting."); + return redacted; + } + return string; +} +function format() { + var s = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ""; + var titleCase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; + var redactingEmail = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; + var _str = s || ""; + if (titleCase) { + _str = toTitleCase(s); + } + if (redactingEmail) { + _str = redactEmail(_str); + } + return _str; +} \ No newline at end of file diff --git a/dist/ga4.js b/dist/ga4.js new file mode 100644 index 0000000..a3bb941 --- /dev/null +++ b/dist/ga4.js @@ -0,0 +1,438 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = exports.GA4 = void 0; +var _gtag = _interopRequireDefault(require("./gtag")); +var _format = _interopRequireDefault(require("./format")); +var _excluded = ["eventCategory", "eventAction", "eventLabel", "eventValue", "hitType"], + _excluded2 = ["title", "location"], + _excluded3 = ["page", "hitType"]; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +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; } +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; } +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); } +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } +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."); } +function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } +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; } +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; } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +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); } +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; } +function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +/* +Links +https://developers.google.com/gtagjs/reference/api +https://developers.google.com/tag-platform/gtagjs/reference +*/ +/** + * @typedef GaOptions + * @type {Object} + * @property {boolean} [cookieUpdate=true] + * @property {number} [cookieExpires=63072000] Default two years + * @property {string} [cookieDomain="auto"] + * @property {string} [cookieFlags] + * @property {string} [userId] + * @property {string} [clientId] + * @property {boolean} [anonymizeIp] + * @property {string} [contentGroup1] + * @property {string} [contentGroup2] + * @property {string} [contentGroup3] + * @property {string} [contentGroup4] + * @property {string} [contentGroup5] + * @property {boolean} [allowAdFeatures=true] + * @property {boolean} [allowAdPersonalizationSignals] + * @property {boolean} [nonInteraction] + * @property {string} [page] + */ +/** + * @typedef UaEventOptions + * @type {Object} + * @property {string} action + * @property {string} category + * @property {string} [label] + * @property {number} [value] + * @property {boolean} [nonInteraction] + * @property {('beacon'|'xhr'|'image')} [transport] + */ +/** + * @typedef InitOptions + * @type {Object} + * @property {string} trackingId + * @property {GaOptions|any} [gaOptions] + * @property {Object} [gtagOptions] New parameter + */ +var GA4 = /*#__PURE__*/function () { + function GA4() { + var _this = this; + _classCallCheck(this, GA4); + _defineProperty(this, "reset", function () { + _this.isInitialized = false; + _this._testMode = false; + _this._currentMeasurementId; + _this._hasLoadedGA = false; + _this._isQueuing = false; + _this._queueGtag = []; + _this._dataLayerName = "dataLayer"; + }); + _defineProperty(this, "_gtag", function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + if (!_this._testMode) { + if (_this._isQueuing) { + _this._queueGtag.push(args); + } else { + _gtag["default"].apply(void 0, [_this._dataLayerName].concat(args)); + } + } else { + _this._queueGtag.push(args); + } + }); + _defineProperty(this, "_loadGA", function (GA_MEASUREMENT_ID, nonce) { + var gtagUrl = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "https://www.googletagmanager.com/gtag/js"; + var dataLayerName = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "dataLayer"; + if (typeof window === "undefined" || typeof document === "undefined") { + return; + } + if (!_this._hasLoadedGA) { + // Global Site Tag (gtag.js) - Google Analytics + var script = document.createElement("script"); + script.async = true; + script.src = "".concat(gtagUrl, "?id=").concat(GA_MEASUREMENT_ID, "&l=").concat(dataLayerName); + if (nonce) { + script.setAttribute("nonce", nonce); + } + document.body.appendChild(script); + window[dataLayerName] = window[dataLayerName] || []; + window.gtag = function gtag() { + window[dataLayerName].push(arguments); + }; + _this._dataLayerName = dataLayerName; + _this._hasLoadedGA = true; + } + }); + _defineProperty(this, "_toGtagOptions", function (gaOptions) { + if (!gaOptions) { + return; + } + var mapFields = { + // Old https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#cookieUpdate + // New https://developers.google.com/analytics/devguides/collection/gtagjs/cookies-user-id#cookie_update + cookieUpdate: "cookie_update", + cookieExpires: "cookie_expires", + cookieDomain: "cookie_domain", + cookieFlags: "cookie_flags", + // must be in set method? + userId: "user_id", + clientId: "client_id", + anonymizeIp: "anonymize_ip", + // https://support.google.com/analytics/answer/2853546?hl=en#zippy=%2Cin-this-article + contentGroup1: "content_group1", + contentGroup2: "content_group2", + contentGroup3: "content_group3", + contentGroup4: "content_group4", + contentGroup5: "content_group5", + // https://support.google.com/analytics/answer/9050852?hl=en + allowAdFeatures: "allow_google_signals", + allowAdPersonalizationSignals: "allow_ad_personalization_signals", + nonInteraction: "non_interaction", + page: "page_path", + hitCallback: "event_callback" + }; + var gtagOptions = Object.entries(gaOptions).reduce(function (prev, _ref) { + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; + if (mapFields[key]) { + prev[mapFields[key]] = value; + } else { + prev[key] = value; + } + return prev; + }, {}); + return gtagOptions; + }); + _defineProperty(this, "initialize", function (GA_MEASUREMENT_ID) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (!GA_MEASUREMENT_ID) { + throw new Error("Require GA_MEASUREMENT_ID"); + } + var initConfigs = typeof GA_MEASUREMENT_ID === "string" ? [{ + trackingId: GA_MEASUREMENT_ID + }] : GA_MEASUREMENT_ID; + _this._currentMeasurementId = initConfigs[0].trackingId; + var gaOptions = options.gaOptions, + gtagOptions = options.gtagOptions, + nonce = options.nonce, + _options$testMode = options.testMode, + testMode = _options$testMode === void 0 ? false : _options$testMode, + gtagUrl = options.gtagUrl, + dataLayerName = options.dataLayerName; + _this._testMode = testMode; + if (!testMode) { + _this._loadGA(_this._currentMeasurementId, nonce, gtagUrl, dataLayerName); + } + if (!_this.isInitialized) { + _this._gtag("js", new Date()); + initConfigs.forEach(function (config) { + var mergedGtagOptions = _objectSpread(_objectSpread(_objectSpread({}, _this._toGtagOptions(_objectSpread(_objectSpread({}, gaOptions), config.gaOptions))), gtagOptions), config.gtagOptions); + if (Object.keys(mergedGtagOptions).length) { + _this._gtag("config", config.trackingId, mergedGtagOptions); + } else { + _this._gtag("config", config.trackingId); + } + }); + } + _this.isInitialized = true; + if (!testMode) { + var queues = _toConsumableArray(_this._queueGtag); + _this._queueGtag = []; + _this._isQueuing = false; + while (queues.length) { + var queue = queues.shift(); + _this._gtag.apply(_this, _toConsumableArray(queue)); + if (queue[0] === "get") { + _this._isQueuing = true; + } + } + } + }); + _defineProperty(this, "set", function (fieldsObject) { + if (!fieldsObject) { + console.warn("`fieldsObject` is required in .set()"); + return; + } + if (_typeof(fieldsObject) !== "object") { + console.warn("Expected `fieldsObject` arg to be an Object"); + return; + } + if (Object.keys(fieldsObject).length === 0) { + console.warn("empty `fieldsObject` given to .set()"); + } + _this._gaCommand("set", fieldsObject); + }); + _defineProperty(this, "_gaCommandSendEvent", function (eventCategory, eventAction, eventLabel, eventValue, fieldsObject) { + _this._gtag("event", eventAction, _objectSpread(_objectSpread({ + event_category: eventCategory, + event_label: eventLabel, + value: eventValue + }, fieldsObject && { + non_interaction: fieldsObject.nonInteraction + }), _this._toGtagOptions(fieldsObject))); + }); + _defineProperty(this, "_gaCommandSendEventParameters", function () { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + if (typeof args[0] === "string") { + _this._gaCommandSendEvent.apply(_this, _toConsumableArray(args.slice(1))); + } else { + var _args$ = args[0], + eventCategory = _args$.eventCategory, + eventAction = _args$.eventAction, + eventLabel = _args$.eventLabel, + eventValue = _args$.eventValue, + hitType = _args$.hitType, + rest = _objectWithoutProperties(_args$, _excluded); + _this._gaCommandSendEvent(eventCategory, eventAction, eventLabel, eventValue, rest); + } + }); + _defineProperty(this, "_gaCommandSendTiming", function (timingCategory, timingVar, timingValue, timingLabel) { + _this._gtag("event", "timing_complete", { + name: timingVar, + value: timingValue, + event_category: timingCategory, + event_label: timingLabel + }); + }); + _defineProperty(this, "_gaCommandSendPageview", function (page, fieldsObject) { + if (fieldsObject && Object.keys(fieldsObject).length) { + var _this$_toGtagOptions = _this._toGtagOptions(fieldsObject), + title = _this$_toGtagOptions.title, + location = _this$_toGtagOptions.location, + rest = _objectWithoutProperties(_this$_toGtagOptions, _excluded2); + _this._gtag("event", "page_view", _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, page && { + page_path: page + }), title && { + page_title: title + }), location && { + page_location: location + }), rest)); + } else if (page) { + _this._gtag("event", "page_view", { + page_path: page + }); + } else { + _this._gtag("event", "page_view"); + } + }); + _defineProperty(this, "_gaCommandSendPageviewParameters", function () { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + if (typeof args[0] === "string") { + _this._gaCommandSendPageview.apply(_this, _toConsumableArray(args.slice(1))); + } else { + var _args$2 = args[0], + page = _args$2.page, + hitType = _args$2.hitType, + rest = _objectWithoutProperties(_args$2, _excluded3); + _this._gaCommandSendPageview(page, rest); + } + }); + _defineProperty(this, "_gaCommandSend", function () { + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + var hitType = typeof args[0] === "string" ? args[0] : args[0].hitType; + switch (hitType) { + case "event": + _this._gaCommandSendEventParameters.apply(_this, args); + break; + case "pageview": + _this._gaCommandSendPageviewParameters.apply(_this, args); + break; + case "timing": + _this._gaCommandSendTiming.apply(_this, _toConsumableArray(args.slice(1))); + break; + case "screenview": + case "transaction": + case "item": + case "social": + case "exception": + console.warn("Unsupported send command: ".concat(hitType)); + break; + default: + console.warn("Send command doesn't exist: ".concat(hitType)); + } + }); + _defineProperty(this, "_gaCommandSet", function () { + for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + args[_key5] = arguments[_key5]; + } + if (typeof args[0] === "string") { + args[0] = _defineProperty({}, args[0], args[1]); + } + _this._gtag("set", _this._toGtagOptions(args[0])); + }); + _defineProperty(this, "_gaCommand", function (command) { + for (var _len6 = arguments.length, args = new Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) { + args[_key6 - 1] = arguments[_key6]; + } + switch (command) { + case "send": + _this._gaCommandSend.apply(_this, args); + break; + case "set": + _this._gaCommandSet.apply(_this, args); + break; + default: + console.warn("Command doesn't exist: ".concat(command)); + } + }); + _defineProperty(this, "ga", function () { + for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { + args[_key7] = arguments[_key7]; + } + if (typeof args[0] === "string") { + _this._gaCommand.apply(_this, args); + } else { + var readyCallback = args[0]; + _this._gtag("get", _this._currentMeasurementId, "client_id", function (clientId) { + _this._isQueuing = false; + var queues = _this._queueGtag; + readyCallback({ + get: function get(property) { + return property === "clientId" ? clientId : property === "trackingId" ? _this._currentMeasurementId : property === "apiVersion" ? "1" : undefined; + } + }); + while (queues.length) { + var queue = queues.shift(); + _this._gtag.apply(_this, _toConsumableArray(queue)); + } + }); + _this._isQueuing = true; + } + return _this.ga; + }); + _defineProperty(this, "event", function (optionsOrName, params) { + if (typeof optionsOrName === "string") { + _this._gtag("event", optionsOrName, _this._toGtagOptions(params)); + } else { + var action = optionsOrName.action, + category = optionsOrName.category, + label = optionsOrName.label, + value = optionsOrName.value, + nonInteraction = optionsOrName.nonInteraction, + transport = optionsOrName.transport; + if (!category || !action) { + console.warn("args.category AND args.action are required in event()"); + return; + } + + // Required Fields + var fieldObject = { + hitType: "event", + eventCategory: (0, _format["default"])(category), + eventAction: (0, _format["default"])(action) + }; + + // Optional Fields + if (label) { + fieldObject.eventLabel = (0, _format["default"])(label); + } + if (typeof value !== "undefined") { + if (typeof value !== "number") { + console.warn("Expected `args.value` arg to be a Number."); + } else { + fieldObject.eventValue = value; + } + } + if (typeof nonInteraction !== "undefined") { + if (typeof nonInteraction !== "boolean") { + console.warn("`args.nonInteraction` must be a boolean."); + } else { + fieldObject.nonInteraction = nonInteraction; + } + } + if (typeof transport !== "undefined") { + if (typeof transport !== "string") { + console.warn("`args.transport` must be a string."); + } else { + if (["beacon", "xhr", "image"].indexOf(transport) === -1) { + console.warn("`args.transport` must be either one of these values: `beacon`, `xhr` or `image`"); + } + fieldObject.transport = transport; + } + } + _this._gaCommand("send", fieldObject); + } + }); + _defineProperty(this, "send", function (fieldObject) { + _this._gaCommand("send", fieldObject); + }); + this.reset(); + } + _createClass(GA4, [{ + key: "gtag", + value: function gtag() { + this._gtag.apply(this, arguments); + } + }]); + return GA4; +}(); +exports.GA4 = GA4; +var _default = new GA4(); +exports["default"] = _default; \ No newline at end of file diff --git a/dist/ga4.test.js b/dist/ga4.test.js new file mode 100644 index 0000000..70cc486 --- /dev/null +++ b/dist/ga4.test.js @@ -0,0 +1,379 @@ +"use strict"; + +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); } +var _gtag = _interopRequireDefault(require("./gtag")); +var _ga = _interopRequireDefault(require("./ga4")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +var newDate = new Date("2020-01-01"); +jest.mock("./gtag"); +jest.useFakeTimers("modern").setSystemTime(newDate.getTime()); +describe("GA4", function () { + // Given + var GA_MEASUREMENT_ID = "GA_MEASUREMENT_ID"; + beforeEach(function () { + _gtag["default"].mockReset(); + _ga["default"].reset(); + }); + describe("GA4.initialize()", function () { + it("initialize() default", function () { + // When + _ga["default"].initialize(GA_MEASUREMENT_ID); + + // Then + expect(_gtag["default"]).toHaveBeenNthCalledWith(1, "js", newDate); + expect(_gtag["default"]).toHaveBeenNthCalledWith(2, "config", GA_MEASUREMENT_ID); + expect(_gtag["default"]).toHaveBeenCalledTimes(2); + }); + it("initialize() with options", function () { + // Given + var options = { + gaOptions: { + cookieUpdate: false + } + }; + + // When + _ga["default"].initialize(GA_MEASUREMENT_ID, options); + + // Then + expect(_gtag["default"]).toHaveBeenNthCalledWith(1, "js", newDate); + expect(_gtag["default"]).toHaveBeenNthCalledWith(2, "config", GA_MEASUREMENT_ID, { + cookie_update: false + }); + expect(_gtag["default"]).toHaveBeenCalledTimes(2); + }); + it("initialize() in test mode", function () { + // Given + var options = { + testMode: true + }; + var command = "send"; + var object = { + hitType: "pageview" + }; + + // When + _ga["default"].initialize(GA_MEASUREMENT_ID, options); + _ga["default"].ga(command, object); + + // Then + expect(_gtag["default"]).toHaveBeenCalledTimes(0); + }); + it("initialize() multiple products", function () { + // Given + var GA_MEASUREMENT_ID2 = "GA_MEASUREMENT_ID2"; + var config = [{ + trackingId: GA_MEASUREMENT_ID + }, { + trackingId: GA_MEASUREMENT_ID2 + }]; + + // When + _ga["default"].initialize(config); + + // Then + expect(_gtag["default"]).toHaveBeenNthCalledWith(1, "js", newDate); + expect(_gtag["default"]).toHaveBeenNthCalledWith(2, "config", GA_MEASUREMENT_ID); + expect(_gtag["default"]).toHaveBeenNthCalledWith(3, "config", GA_MEASUREMENT_ID2); + expect(_gtag["default"]).toHaveBeenCalledTimes(3); + }); + }); + describe("GA4.ga()", function () { + it("ga() send pageview", function () { + // Given + var command = "send"; + var object = { + hitType: "pageview" + }; + + // When + _ga["default"].ga(command, object); + + // Then + expect(_gtag["default"]).toHaveBeenNthCalledWith(1, "event", "page_view"); + }); + it("ga() send timing", function () { + // Given + var command = "send"; + var hitType = "timing"; + var timingCategory = "DOM"; + var timingVar = "first-contentful-paint"; + var timingValue = 120; + + // When + _ga["default"].ga(command, hitType, timingCategory, timingVar, timingValue); + + // Then + expect(_gtag["default"]).toHaveBeenNthCalledWith(1, "event", "timing_complete", { + event_category: timingCategory, + name: timingVar, + value: timingValue + }); + }); + it("ga() callback", function (done) { + // Given + var clientId = "clientId value"; + _gtag["default"].mockImplementationOnce(function (command, target, field_name, cb) { + return cb(clientId); + }); + var callback = jest.fn(function (tracker) { + var trackerClientId = tracker.get("clientId"); + var trackerTrackingId = tracker.get("trackingId"); + var trackerApiVersion = tracker.get("apiVersion"); + expect(trackerClientId).toEqual(clientId); + expect(trackerTrackingId).toEqual(GA_MEASUREMENT_ID); + expect(trackerApiVersion).toEqual("1"); + done(); + }); + + // When + _ga["default"].ga(callback); + + // Then + expect(_gtag["default"]).toHaveBeenNthCalledWith(1, "get", GA_MEASUREMENT_ID, "client_id", expect.any(Function)); + }); + it("ga() async callback", function (done) { + // Given + var clientId = "clientId value"; + _gtag["default"].mockImplementationOnce(function (command, target, field_name, cb) { + return cb(clientId); + }); + var callback = jest.fn( /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(tracker) { + var trackerClientId; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + trackerClientId = tracker.get("clientId"); + expect(trackerClientId).toEqual(clientId); + done(); + case 3: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x) { + return _ref.apply(this, arguments); + }; + }()); + + // When + _ga["default"].ga(callback); + + // Then + expect(_gtag["default"]).toHaveBeenNthCalledWith(1, "get", GA_MEASUREMENT_ID, "client_id", expect.any(Function)); + }); + it("ga() callback queue", function (done) { + // Given + var clientId = "clientId value"; + _gtag["default"].mockImplementationOnce(function (command, target, field_name, cb) { + setImmediate(function () { + return cb(clientId); + }); + }); + var callback = jest.fn(function () { + _ga["default"].ga("send", { + hitType: "pageview" + }); + expect(_gtag["default"]).toHaveBeenNthCalledWith(2, "event", "page_view"); + done(); + }); + + // When + _ga["default"].ga(callback); + _ga["default"].ga("send", "event", "category value"); + + // Then + expect(_gtag["default"]).toHaveBeenNthCalledWith(1, "get", GA_MEASUREMENT_ID, "client_id", expect.any(Function)); + expect(_gtag["default"]).toHaveBeenCalledTimes(1); + expect(_ga["default"]._isQueuing).toBeTruthy(); + expect(_ga["default"]._queueGtag).toHaveLength(1); + jest.runAllTimers(); + expect(_ga["default"]._isQueuing).toBeFalsy(); + expect(_ga["default"]._queueGtag).toHaveLength(0); + expect(_gtag["default"]).toHaveBeenNthCalledWith(3, "event", undefined, { + event_category: "category value" + }); + }); + }); + describe("GA4.send()", function () { + it("send() pageview", function () { + // Given + var object = { + hitType: "pageview" + }; + + // When + _ga["default"].send(object); + + // Then + expect(_gtag["default"]).toHaveBeenNthCalledWith(1, "event", "page_view"); + }); + }); + describe("GA4.event()", function () { + it("event() custom events", function () { + // Given + var eventName = "screen_view"; + var eventParams = { + app_name: "myAppName", + screen_name: "Home" + }; + + // When + _ga["default"].event(eventName, eventParams); + + // Then + expect(_gtag["default"]).toHaveBeenNthCalledWith(1, "event", eventName, eventParams); + }); + it("event() simple", function () { + // Given + var object = { + category: "category value", + action: "action value", + label: "label value", + nonInteraction: true + }; + + // When + _ga["default"].event(object); + + // Then + expect(_gtag["default"]).toHaveBeenNthCalledWith(1, "event", "Action Value", { + event_category: "Category Value", + event_label: "Label Value", + non_interaction: true + }); + }); + }); + describe("GA4.set()", function () { + it("set()", function () { + // Given + var object = { + anonymizeIp: true, + referrer: "/signup", + allowAdFeatures: "allowAdFeatures value", + allowAdPersonalizationSignals: "allowAdPersonalizationSignals value", + page: "/home" + }; + + // When + _ga["default"].set(object); + + // Then + expect(_gtag["default"]).toHaveBeenNthCalledWith(1, "set", { + anonymize_ip: true, + referrer: "/signup", + allow_google_signals: "allowAdFeatures value", + allow_ad_personalization_signals: "allowAdPersonalizationSignals value", + page_path: "/home" + }); + }); + }); + describe("Reference", function () { + it("pageview", function () { + // Old https://developers.google.com/analytics/devguides/collection/analyticsjs/pages + // New https://developers.google.com/gtagjs/reference/event#page_view + + // Given + var hitType = "pageview"; + var path = "/location-pathname"; + var title = "title value"; + + // When / Then + + // Without parameters + _ga["default"].send(hitType); + expect(_gtag["default"]).toHaveBeenNthCalledWith(1, "event", "page_view"); + _ga["default"].send({ + hitType: hitType + }); + expect(_gtag["default"]).toHaveBeenNthCalledWith(2, "event", "page_view"); + _ga["default"].ga("send", hitType); + expect(_gtag["default"]).toHaveBeenNthCalledWith(3, "event", "page_view"); + + // With path parameter + _ga["default"].send({ + hitType: hitType, + page: path + }); + expect(_gtag["default"]).toHaveBeenNthCalledWith(4, "event", "page_view", { + page_path: path + }); + _ga["default"].ga("send", hitType, path); + expect(_gtag["default"]).toHaveBeenNthCalledWith(5, "event", "page_view", { + page_path: path + }); + + // With path and title parameter + _ga["default"].send({ + hitType: hitType, + page: path, + title: title + }); + expect(_gtag["default"]).toHaveBeenNthCalledWith(6, "event", "page_view", { + page_path: path, + page_title: title + }); + _ga["default"].ga("send", hitType, path, { + title: title + }); + expect(_gtag["default"]).toHaveBeenNthCalledWith(7, "event", "page_view", { + page_path: path, + page_title: title + }); + }); + }); + describe("Web vitals", function () { + it("Web vitals", function () { + // https://github.com/GoogleChrome/web-vitals/blob/main/README.md + function sendToGoogleAnalytics(_ref2) { + var name = _ref2.name, + delta = _ref2.delta, + value = _ref2.value, + id = _ref2.id; + _ga["default"].send({ + hitType: "event", + eventCategory: "Web Vitals", + eventAction: name, + eventLabel: id, + nonInteraction: true, + // Built-in params: + value: Math.round(name === "CLS" ? delta * 1000 : delta), + // Use `delta` so the value can be summed. + // Custom params: + metric_id: id, + // Needed to aggregate events. + metric_value: value, + // Optional. + metric_delta: delta // Optional. + + // OPTIONAL: any additional params or debug info here. + // See: https://web.dev/debug-web-vitals-in-the-field/ + // metric_rating: 'good' | 'ni' | 'poor', + // debug_info: '...', + // ... + }); + } + + sendToGoogleAnalytics({ + name: "CLS", + delta: 12.34, + value: 1, + id: "v2-1632380328370-6426221164013" + }); + expect(_gtag["default"]).toHaveBeenNthCalledWith(1, "event", "CLS", { + event_category: "Web Vitals", + event_label: "v2-1632380328370-6426221164013", + metric_delta: 12.34, + metric_id: "v2-1632380328370-6426221164013", + metric_value: 1, + non_interaction: true, + value: 12340 + }); + }); + }); +}); \ No newline at end of file diff --git a/dist/gtag.js b/dist/gtag.js new file mode 100644 index 0000000..e7625de --- /dev/null +++ b/dist/gtag.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var gtag = function gtag(dataLayerName) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + if (typeof window !== "undefined") { + var _window; + if (typeof window.gtag === "undefined") { + window[dataLayerName] = window[dataLayerName] || []; + window.gtag = function gtag() { + window[dataLayerName].push(arguments); + }; + } + (_window = window).gtag.apply(_window, args); + } +}; +var _default = gtag; +exports["default"] = _default; \ No newline at end of file diff --git a/dist/index.js b/dist/index.js new file mode 100644 index 0000000..9824aeb --- /dev/null +++ b/dist/index.js @@ -0,0 +1,14 @@ +"use strict"; + +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); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = exports.ReactGAImplementation = void 0; +var _ga = _interopRequireWildcard(require("./ga4")); +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } +var ReactGAImplementation = _ga.GA4; +exports.ReactGAImplementation = ReactGAImplementation; +var _default = _ga["default"]; +exports["default"] = _default; \ No newline at end of file diff --git a/src/ga4.js b/src/ga4.js index cf6a597..e3b53e4 100644 --- a/src/ga4.js +++ b/src/ga4.js @@ -60,6 +60,7 @@ export class GA4 { this._hasLoadedGA = false; this._isQueuing = false; this._queueGtag = []; + this._dataLayerName = "dataLayer"; }; _gtag = (...args) => { @@ -67,7 +68,7 @@ export class GA4 { if (this._isQueuing) { this._queueGtag.push(args); } else { - gtag(...args); + gtag(this._dataLayerName, ...args); } } else { this._queueGtag.push(args); @@ -81,7 +82,8 @@ export class GA4 { _loadGA = ( GA_MEASUREMENT_ID, nonce, - gtagUrl = "https://www.googletagmanager.com/gtag/js" + gtagUrl = "https://www.googletagmanager.com/gtag/js", + dataLayerName = "dataLayer" ) => { if (typeof window === "undefined" || typeof document === "undefined") { return; @@ -91,17 +93,18 @@ export class GA4 { // Global Site Tag (gtag.js) - Google Analytics const script = document.createElement("script"); script.async = true; - script.src = `${gtagUrl}?id=${GA_MEASUREMENT_ID}`; + script.src = `${gtagUrl}?id=${GA_MEASUREMENT_ID}&l=${dataLayerName}`; if (nonce) { script.setAttribute("nonce", nonce); } document.body.appendChild(script); - window.dataLayer = window.dataLayer || []; + window[dataLayerName] = window[dataLayerName] || []; window.gtag = function gtag() { - window.dataLayer.push(arguments); + window[dataLayerName].push(arguments); }; + this._dataLayerName = dataLayerName; this._hasLoadedGA = true; } }; @@ -158,6 +161,7 @@ export class GA4 { * @param {string} [options.nonce] * @param {boolean} [options.testMode=false] * @param {string} [options.gtagUrl=https://www.googletagmanager.com/gtag/js] + * @param {string} [options.dataLayerName=dataLayer] * @param {GaOptions|any} [options.gaOptions] * @param {Object} [options.gtagOptions] New parameter */ @@ -178,11 +182,12 @@ export class GA4 { nonce, testMode = false, gtagUrl, + dataLayerName, } = options; this._testMode = testMode; if (!testMode) { - this._loadGA(this._currentMeasurementId, nonce, gtagUrl); + this._loadGA(this._currentMeasurementId, nonce, gtagUrl, dataLayerName); } if (!this.isInitialized) { this._gtag("js", new Date()); diff --git a/src/gtag.js b/src/gtag.js index 676b039..f1e5c6d 100644 --- a/src/gtag.js +++ b/src/gtag.js @@ -1,9 +1,9 @@ -const gtag = (...args) => { +const gtag = (dataLayerName, ...args) => { if (typeof window !== "undefined") { if (typeof window.gtag === "undefined") { - window.dataLayer = window.dataLayer || []; + window[dataLayerName] = window[dataLayerName] || []; window.gtag = function gtag() { - window.dataLayer.push(arguments); + window[dataLayerName].push(arguments); }; } diff --git a/types/ga4.d.ts b/types/ga4.d.ts index 07eca88..a0bcba4 100644 --- a/types/ga4.d.ts +++ b/types/ga4.d.ts @@ -42,9 +42,10 @@ export class GA4 { _hasLoadedGA: boolean; _isQueuing: boolean; _queueGtag: any[]; + _dataLayerName: string; _gtag: (...args: any[]) => void; gtag(...args: any[]): void; - _loadGA: (GA_MEASUREMENT_ID: any, nonce: any, gtagUrl?: string) => void; + _loadGA: (GA_MEASUREMENT_ID: any, nonce: any, gtagUrl?: string, dataLayerName?: string) => void; _toGtagOptions: (gaOptions: any) => {}; /** * @@ -53,6 +54,7 @@ export class GA4 { * @param {string} [options.nonce] * @param {boolean} [options.testMode=false] * @param {string} [options.gtagUrl=https://www.googletagmanager.com/gtag/js] + * @param {string} [options.dataLayerName=dataLayer] * @param {GaOptions|any} [options.gaOptions] * @param {Object} [options.gtagOptions] New parameter */ @@ -60,6 +62,7 @@ export class GA4 { nonce?: string; testMode?: boolean; gtagUrl?: string; + dataLayerName?: string; gaOptions?: GaOptions | any; gtagOptions?: any; }) => void; diff --git a/types/gtag.d.ts b/types/gtag.d.ts index 97d4610..5eeb29a 100644 --- a/types/gtag.d.ts +++ b/types/gtag.d.ts @@ -1,2 +1,2 @@ export default gtag; -declare function gtag(...args: any[]): void; +declare function gtag(dataLayerName: any, ...args: any[]): void;