UNPKG

mr-gtag

Version:

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

38 lines (36 loc) 1.25 kB
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); } export { gtag, gtagRaw, installGtag, onlyInstallGtag };