UNPKG

mr-gtag

Version:

Easy, strong typed, and a modern way to use google analytics gtag lib.

51 lines (46 loc) 1.9 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.gtag = {})); }(this, (function (exports) { 'use strict'; const anyWindow = window; const defaultGtagConfigurationOptions = { send_page_view: true, }; /** * Only injects the google analytics gtag lib without calling config. * @param trackingId The ga tracking id. */ function onlyInstallGtag(trackingId) { const { head } = document; const script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = `https://www.googletagmanager.com/gtag/js?id=${trackingId}`; head.insertBefore(script, head.firstChild); anyWindow.dataLayer = anyWindow.dataLayer || []; gtagRaw('js', new Date()); } /** * Injects the google analytics gtag lib. * @param trackingId The ga tracking id. * @param options The options to configure. */ function installGtag(trackingId, options) { onlyInstallGtag(trackingId); options = Object.assign(Object.assign({}, defaultGtagConfigurationOptions), options); gtag('config', trackingId, options); } function gtagRaw(...params) { anyWindow.dataLayer.push(arguments); } // tslint:enable: unified-signatures, max-line-length function gtag(arg1, arg2, arg3) { anyWindow.dataLayer.push(arguments); } exports.gtag = gtag; exports.gtagRaw = gtagRaw; exports.installGtag = installGtag; exports.onlyInstallGtag = onlyInstallGtag; Object.defineProperty(exports, '__esModule', { value: true }); })));