UNPKG

@mobileaction/ui-modules

Version:

Mobile Action common modules for Vue projects

83 lines (71 loc) 2.48 kB
import Cookies from 'js-cookie'; import { injectPlugin, validateVueInstall } from '../PluginUtils.js'; // do not store this so on changes it can adjust its behavior class MaGA { constructor(Vue, { isProduction = false }) { this.Vue = Vue; this.pUserId = false; this.imp = null; if (typeof isProduction == 'boolean') { this.isProduction = () => isProduction; } else { this.isProduction = isProduction; } } cantSend() { return !this.isProduction() || Cookies.get('MA') === '1' || !window.dataLayer; } initialize(user, imp = null) { this.imp = imp; this.pUserId = user && user.userId; if (this.cantSend()) { return; } window.dataLayer.push({ userId: this.pUserId }); } eventSend(category, action, label = false, btnIdentifier = false, value = false) { const _label = label === false ? location.pathname : label; if (this.cantSend()) { // using ...arguments does not reflect default behaviour of label === false MaGA.$log.warn('Mocked GA event:', category, action, _label, this.pUserId, value, btnIdentifier); return; } const eventData = { event: 'customEvent', gaEventCategory: category, gaEventAction: action, gaEventLabel: _label, }; if (this.pUserId) { eventData.dimension2 = `${ this.pUserId }`; // since it can be integer turn to string for safety } if (btnIdentifier) { eventData.dimension3 = btnIdentifier; } if (value !== false) { eventData.gaEventValue = value; } window.dataLayer.push(eventData); } transactionAdd(id, affiliation, revenue, userID, products) { if (this.cantSend()) { MaGA.$log.warn('Mocked GA transaction event:', ...arguments); return; } window.dataLayer.push({ event: 'transactionEvent', transactionId: id, transactionAffiliation: affiliation, transactionTotal: revenue, dimension2: userID, transactionProducts: products, }); } } export function MaGa(app, options = {}) { if (!validateVueInstall(app, MaGA, 'MaGA')) { return; } injectPlugin(app, new MaGA(app, options || {}), '$ga'); } export default MaGA;