UNPKG

utm-synapse

Version:

Track and report UTM parameters along a browser session

158 lines (151 loc) 7.18 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('memorystorage')) : typeof define === 'function' && define.amd ? define(['exports', 'memorystorage'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.UtmSynapse = {}, global.MemoryStorage)); })(this, (function (exports, MemoryStorage) { 'use strict'; function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var MemoryStorage__default = /*#__PURE__*/_interopDefaultLegacy(MemoryStorage); exports.UtmParamEnum = void 0; (function (UtmParamEnum) { UtmParamEnum["Source"] = "utm_source"; UtmParamEnum["Medium"] = "utm_medium"; UtmParamEnum["Campaign"] = "utm_campaign"; UtmParamEnum["Content"] = "utm_content"; UtmParamEnum["Name"] = "utm_name"; UtmParamEnum["Term"] = "utm_term"; UtmParamEnum["InitialSource"] = "initial_utm_source"; UtmParamEnum["InitialMedium"] = "initial_utm_medium"; UtmParamEnum["InitialCampaign"] = "initial_utm_campaign"; UtmParamEnum["InitialContent"] = "initial_utm_content"; UtmParamEnum["InitialName"] = "initial_utm_name"; UtmParamEnum["InitialTerm"] = "initial_utm_term"; UtmParamEnum["Gclid"] = "gclid"; })(exports.UtmParamEnum || (exports.UtmParamEnum = {})); /** Its instance allows you to deal with UTM parameters */ class UtmSynapse { constructor() { // In the future we could allow customizing the `sessionStorage` key... // In case the storage is missing, log this plugin won't work normally if (typeof Storage === 'undefined') { console.warn("Using the UTM package without having a storage won't work properly"); this.storage = new MemoryStorage__default["default"](); } else { this.storage = sessionStorage; } } /** Extract UTM parameters from a URL or by default `window.location.href` */ parse(url) { const parsedUrl = new URL(url || window.location.href); const urlParams = parsedUrl.searchParams; const utmParams = {}; Object.values(exports.UtmParamEnum).forEach(utmKey => { const value = urlParams.get(utmKey); if (value) { utmParams[utmKey] = value; } }); if (!Object.keys(utmParams).length) { return null; } return utmParams; } /** Save UTM parameters for later usage */ save(params) { if (!this.storage) { return; } // Load the existing params if any and patch with the input ones const previousParamsString = this.storage.getItem(UtmSynapse.StorageKey); const paramsToSave = JSON.parse(JSON.stringify(params)); if (previousParamsString) { const previousParams = JSON.parse(previousParamsString); // If any "initial" in the input params, we ignored keeping the previous saved ones const mapInitialKeys = { [exports.UtmParamEnum.Source]: exports.UtmParamEnum.InitialSource, [exports.UtmParamEnum.Medium]: exports.UtmParamEnum.InitialMedium, [exports.UtmParamEnum.Campaign]: exports.UtmParamEnum.InitialCampaign, [exports.UtmParamEnum.Content]: exports.UtmParamEnum.InitialContent, [exports.UtmParamEnum.Name]: exports.UtmParamEnum.InitialName, [exports.UtmParamEnum.Term]: exports.UtmParamEnum.InitialTerm, }; const intersectionArray = Object.values(mapInitialKeys).filter(value => Object.keys(params).includes(value)); if (!intersectionArray.length) { const paramsToLookFor = Object.keys(mapInitialKeys); for (const [key, value] of Object.entries(previousParams)) { if (paramsToLookFor.includes(key)) { const convertedKey = mapInitialKeys[key]; paramsToSave[convertedKey] = value; } } } } this.storage.setItem(UtmSynapse.StorageKey, JSON.stringify(paramsToSave)); } /** Load any UTM parameter in the storage */ load() { if (!this.storage) { return null; } const utmParams = this.storage.getItem(UtmSynapse.StorageKey); return utmParams ? JSON.parse(utmParams) : null; } /** Clear the storage of any UTM parameter */ clear() { if (!this.storage) { return; } this.storage.removeItem(UtmSynapse.StorageKey); } /** Remove UTM parameters from an URL */ trimUrl(url) { const parsedUrl = new URL(url); const urlParams = parsedUrl.searchParams; if (!urlParams) { return url; } for (const paramKey of Object.values(exports.UtmParamEnum)) { urlParams.delete(paramKey); } return parsedUrl.toString(); } /** * Will ask the browser to remove UTM parameters without reloading the page. * Can be useful to avoid users doing copy/paste with UTM parameters * * Tip: you should save parameters before doing this (because they would be lost otherwise) * Note: if the history browser feature is not accessible it won't work */ cleanDisplayedUrl() { if (!window || !history) { return; } const trimmedUrl = this.trimUrl(window.location.href); const previousState = history.state; history.replaceState(previousState, '', trimmedUrl); } /** * Will add provided parameters to the URL * * Note: in case the URL already contains one of those parameters already, we remove all the original ones before patching (to not mix different analytics sessions) */ setIntoUrl(url, params) { const cleanUrlToPatch = this.trimUrl(url); const parsedUrl = new URL(cleanUrlToPatch); const urlParams = parsedUrl.searchParams; for (const [key, value] of Object.entries(params)) { if (value) { urlParams.append(key, value); } } return parsedUrl.toString(); } } UtmSynapse.StorageKey = 'utmParams'; /** Default global instance for the ease of use */ const utmSynapse = new UtmSynapse(); exports.UtmSynapse = UtmSynapse; exports.utmSynapse = utmSynapse; Object.defineProperty(exports, '__esModule', { value: true }); })); //# sourceMappingURL=index.js.map