@mopinion/survey
Version:
Collect customer feedback with the Mopinion survey library
336 lines (335 loc) • 14.7 kB
JavaScript
;
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
exports.getAnalyticsIdFromPage = getAnalyticsIdFromPage;
var _utils = require("../../../utils");
var _request2 = _interopRequireDefault(require("../../../api/request"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function isAnalyticsId() {
var id = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
return /^UA-/i.test(id);
}
function isGa4Id() {
var id = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
return /^G-/i.test(id);
}
function isAnalyticsOrGtagId() {
var str = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
return isGa4Id(str) || isAnalyticsId(str);
}
function getFromGoogleTagManager() {
for (var _i = 0, _Object$keys = Object.keys((_window$google_tag_ma = window.google_tag_manager) !== null && _window$google_tag_ma !== void 0 ? _window$google_tag_ma : {}); _i < _Object$keys.length; _i++) {
var _window$google_tag_ma;
var item = _Object$keys[_i];
if (isAnalyticsOrGtagId(item)) {
return item;
}
}
}
function getFromDataLayer() {
if ((0, _utils.isArray)(window.dataLayer)) {
var _iterator = _createForOfIteratorHelper(window.dataLayer),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var item = _step.value;
if (item[0] === 'config' && isAnalyticsOrGtagId(item[1])) {
return item[1];
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
}
function getLegacyAnalyticsId() {
return window.ga.getAll()[0].get('trackingId');
}
function getAnalyticsIdFromPage() {
var getters = [getFromGoogleTagManager, getFromDataLayer, getLegacyAnalyticsId];
for (var _i2 = 0, _getters = getters; _i2 < _getters.length; _i2++) {
var get = _getters[_i2];
try {
if (get()) {
return get();
}
} catch (e) {}
}
return null;
}
function sendGa4WhenReady(fn) {
if (ga4IsActive()) {
fn();
return;
}
var count = 0;
var interval = setInterval(function () {
if (ga4IsActive()) {
fn();
clearInterval(interval);
}
if (count > 10) {
clearInterval(interval);
}
count++;
}, 100);
}
function sendLegacyGaWhenReady() {
var fn = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {};
if (window.ga) {
return fn();
}
var count = 0;
var interval = setInterval(function () {
if (window.ga) {
fn();
clearInterval(interval);
}
if (count > 10) {
clearInterval(interval);
}
count++;
}, 100);
}
function handleGa4Post() {
if (window.gtag) {
window.gtag(arguments);
}
if ((0, _utils.isArray)(window.dataLayer)) {
window.dataLayer.push(arguments);
}
}
function ga4IsActive() {
return window.gtag || (0, _utils.isArray)(window.dataLayer);
}
var gtagConfig = {
send_page_view: false,
cookie_prefix: 'mop',
cookie_expires: 60 * 60 * 24 * 365,
allow_google_signals: false
};
var legacyGaConfig = {
name: 'mopinion',
cookieExpires: 60 * 60 * 24 * 365,
cookieName: 'mop_ga'
};
function loadGa4(id) {
(0, _utils.appendScript)("https://www.googletagmanager.com/gtag/js?id=".concat(id), {
onLoad: function onLoad() {
window.dataLayer = window.dataLayer || [];
window.gtag = function () {
window.dataLayer.push(arguments);
};
window.gtag('js', new Date());
window.gtag('config', id, gtagConfig);
}
});
}
var Track = exports["default"] = _createClass(function Track() {
var _this = this,
_advanced$analytics_i;
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
advanced = _ref.advanced,
disablePost = _ref.disablePost,
formKey = _ref.formKey,
_formName = _ref.formName,
metricsDomain = _ref.metricsDomain;
_classCallCheck(this, Track);
_defineProperty(this, "setEventProps", function (props) {
_this.eventProps = props;
return _this;
});
_defineProperty(this, "setFeedback", function (props) {
_this.feedback = props;
return _this;
});
_defineProperty(this, "send", function (event) {
if (_this.disablePost) {
(0, _utils.log)('Tracking disabled', event, _this.eventProps);
return;
}
if (_this.metrics) {
_this.sendMetrics(event, _this.eventProps);
}
if (_this.gaId) {
_this.sendGa({
action: event
}, _this.eventProps);
}
});
_defineProperty(this, "sendFeedback", function () {
if (_this.gaId && _this.gaSendFeedback) {
_this.sendFeedbackGa(_this.feedback);
}
});
_defineProperty(this, "sendMetrics", function (event, eventProps) {
if (!(0, _utils.getCookie)('SQsession')) {
(0, _utils.setCookie)('SQsession', (0, _utils.createId)(5), 0.5 / 24);
}
setTimeout(function () {
var data = {
project_token: _this.surveyKey,
datetime: new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString(),
session: (0, _utils.getCookie)('SQsession'),
url: window.location.href,
url_title: document.title,
url_referrer: document.referrer,
host: window.location.hostname,
user_agent: navigator.userAgent,
browser_language: navigator.language || navigator.userLanguage,
viewport: "".concat(window.innerWidth, "x").concat(window.innerHeight),
Dextra: {
eventName: event,
eventProps: _objectSpread({}, eventProps)
}
};
(0, _utils.log)('Send Metrics', data);
var _request = (0, _request2["default"])("https://".concat(_this.metricsDomain, "/datapoints"), {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}),
promise = _request.promise;
promise.then(function (r) {
return (0, _utils.log)(r);
})["catch"](function (e) {
return (0, _utils.log)(e);
});
}, 300);
});
_defineProperty(this, "getGaTracker", function () {
var event = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
return _this.customGaTracker ? "".concat(_this.customGaTracker, ".").concat(event) : event;
});
_defineProperty(this, "initGa", function () {
if (!ga4IsActive() && isGa4Id(_this.gaId)) {
loadGa4(_this.gaId);
} else if (ga4IsActive() && _this.gaId !== getAnalyticsIdFromPage()) {
handleGa4Post('config', _this.gaId, gtagConfig);
} else if (window.ga && isAnalyticsId(_this.gaId) && _this.gaId !== getAnalyticsIdFromPage()) {
_this.customGaTracker = legacyGaConfig.name;
window.ga('create', _this.gaId, legacyGaConfig);
window.ga(_this.getGaTracker('set'), 'allowAdFeatures', false);
} else if (!window.ga && isAnalyticsId(_this.gaId)) {
_this.customGaTracker = legacyGaConfig.name;
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments);
}, i[r].l = 1 * new Date();
a = s.createElement(o), m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m);
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
window.ga('create', _this.gaId, legacyGaConfig);
window.ga(_this.getGaTracker('set'), 'allowAdFeatures', false);
}
});
_defineProperty(this, "isNonInteractionEvent", function (action) {
var eventProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var trigger_method = eventProps.trigger_method;
var nonInteractionActions = ['form shown'];
var nonInteractionTriggerMethods = ['proactive'];
if (nonInteractionActions.indexOf(action.toLowerCase()) > -1 && nonInteractionTriggerMethods.indexOf(trigger_method) > -1) {
return true;
}
return false;
});
_defineProperty(this, "sendGa", function (_ref2) {
var action = _ref2.action,
label = _ref2.label,
categoryExtra = _ref2.categoryExtra,
feedbackQuestion = _ref2.feedbackQuestion,
feedbackValue = _ref2.feedbackValue;
var eventProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var formName = "Mopinion Form - ".concat(_this.surveyName);
(0, _utils.log)('Send Analytics', action);
if (ga4IsActive() || isGa4Id(_this.gaId)) {
sendGa4WhenReady(function () {
handleGa4Post('event', action, _objectSpread(_objectSpread({
mop_form_name: formName,
send_to: _this.gaId
}, feedbackQuestion && feedbackValue && {
mop_feedback_question: feedbackQuestion,
mop_feedback_value: feedbackValue
}), _this.isNonInteractionEvent(action, eventProps) && {
non_interaction: true
}));
});
} else {
var category = "Mopinion Form - ".concat(_this.surveyName).concat(categoryExtra ? categoryExtra : '');
sendLegacyGaWhenReady(function () {
window.ga(_this.getGaTracker('send'), _objectSpread(_objectSpread({
hitType: 'event',
eventCategory: category,
eventAction: action
}, label && {
eventLabel: label
}), _this.isNonInteractionEvent(action, eventProps) && {
nonInteraction: true
}));
});
}
});
_defineProperty(this, "sendFeedbackGa", function () {
var feedback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
feedback.forEach(function (feedbackItem, i) {
if (feedbackItem.title) {
if (ga4IsActive() || isGa4Id(_this.gaId)) {
_this.sendGa({
action: 'Feedback data',
feedbackQuestion: "Q".concat(i + 1, " - ").concat(feedbackItem.title),
feedbackValue: feedbackItem.value
});
} else {
_this.sendGa({
action: "Q".concat(i + 1, " - ").concat(feedbackItem.title),
label: feedbackItem.value,
categoryExtra: ' - Feedback'
});
}
}
});
});
this.disablePost = disablePost;
this.surveyKey = formKey;
this.surveyName = _formName;
this.metricsDomain = metricsDomain;
this.customGaTracker = '';
this.eventProps = {};
this.feedback = [];
if (advanced !== null && advanced !== void 0 && advanced.logMetrics) {
this.metrics = true;
}
if (advanced !== null && advanced !== void 0 && (_advanced$analytics_i = advanced.analytics_integration) !== null && _advanced$analytics_i !== void 0 && _advanced$analytics_i.load_analytics) {
this.gaId = advanced.analytics_integration.GA_TRACKING_ID;
if (!this.gaId) {
this.gaId = getAnalyticsIdFromPage();
}
this.gaSendFeedback = Boolean(advanced.analytics_integration.sendFeedback);
if (this.gaId) {
(0, _utils.log)("Tracking Analytics ".concat(this.gaId));
this.initGa();
}
}
});
//# sourceMappingURL=Track.js.map