UNPKG

vue-gtag

Version:

Global Site Tag (gtag.js) plugin for Vue

35 lines (34 loc) 6.76 kB
import{computed as e}from"vue";function t(){return typeof window>`u`||typeof document>`u`}async function n(e,n){return new Promise((r,i)=>{if(t())return r();let a=document.head,o=document.createElement(`script`);if(o.async=!0,o.src=e,o.type=n?.type??`text/javascript`,n?.defer&&(o.defer=!0),n?.nonce&&o.setAttribute(`nonce`,n.nonce),n?.preconnect){let t=document.createElement(`link`),n=new URL(e);t.href=n.origin,t.rel=`preconnect`,a.appendChild(t)}a.appendChild(o),o.onload=()=>r(),o.onerror=e=>i(e)})}function r(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function i(e,t){let n={...e};for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a)){let o=t[a],s=e[a];r(o)&&r(s)?n[a]=i(s,o):n[a]=o}return n}function a(e){if(t())return;let n=new URL(window.location.href);n.search=``;for(let[t,r]of Object.entries(e))n.searchParams.set(t,r);window.history.replaceState({},``,n.toString())}const o=`utm_`;function s(e){let t=new URL(e),n={},r=[],i={};t.searchParams.forEach((e,t)=>{t.includes(o)?(n[t.replace(o,``).replace(`campaign`,`id`)]=e,r.push(t)):i[t]=e});for(let e of r)t.searchParams.delete(e);return{utmParams:n,cleanQueryParams:i,cleanUrl:t.toString()}}function c(e){let t=RegExp(`[?&]${o}`);return!!e.match(t)}function l(e,t){let n=t.endsWith(`/`)?t:`${t}/`,r=e.startsWith(`/`)?e.substring(1):e;return`${n}${r}`}const u=`expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;async function d(e){for(let t of document.cookie.split(`;`)){let n=t.split(`=`)[0].trim();n.startsWith(e)&&(document.cookie=`${n}=; ${u}`)}}const f={resource:{url:`https://www.googletagmanager.com/gtag/js`,inject:!0},dataLayerName:`dataLayer`,gtagName:`gtag`,groupName:`default`,initMode:`auto`};let p={...f};function m(){return p}function h(e){p=i(p,e)}function g(...e){let{dataLayerName:n,gtagName:r}=m();t()||(window[n]=window[n]||[],window[r]=function(){window[n].push(arguments)},window[r](...e))}function _(e){let{tagId:t,additionalAccounts:n}=m();if(t&&(g(`config`,t,e),n))for(let t of n)g(`config`,t.tagId,e)}function v(e,t){g(`consent`,e,t)}function y(e=`default`){v(e,{ad_user_data:`granted`,ad_personalization:`granted`,ad_storage:`granted`,analytics_storage:`granted`})}function b(e=`default`){v(e,{ad_user_data:`denied`,ad_personalization:`denied`,ad_storage:`denied`,analytics_storage:`denied`})}function x(e){_({custom_map:e})}function S(e,t={}){let{groupName:n,additionalAccounts:r}=m();t.send_to===void 0&&r?.length&&(t.send_to=n),g(`event`,e,t)}function C(e,t={}){S(e,t)}function w(e){S(`exception`,e)}function T(e){g(`set`,`linker`,e)}function E(e,t){t?window[e]=t:delete window[e]}function D(e,n){let{tagId:r,additionalAccounts:i}=m();if(!t()&&(E(`ga-disable-${e??r}`,n),!(!i?.length||e)))for(let e of i)E(`ga-disable-${e.tagId}`,n)} /** * Disable tracking * By default uses the provided tagId and all additional accounts in the plugin configuration. * If a tagId is provided, it will only disable that account. */ function O(e){D(e,!0)} /** * Enable tracking * * By default uses the provided tagId and all additional accounts in the plugin configuration. * If a tagId is provided, it will only enable that account. */ function k(e){D(e,void 0)}function A(...e){g(`set`,...e)}function j(e){let{pageTracker:t}=m(),n;if(typeof e==`string`)n={page_path:e};else if(`path`in e){let r=t?.router.options.history.base??``,i=t?.useRouteFullPath?e.fullPath:e.path;n={...e.name?{page_title:e.name.toString()}:{},page_path:t?.useRouterBasePath?l(i,r):i}}else n=e;if(n.page_location===void 0&&(n.page_location=window.location.href),n.send_page_view===void 0&&(n.send_page_view=t?.sendPageView??!0),n.page_path!==`/`&&n.page_path?.endsWith(`/`)&&(n.page_path=n.page_path.slice(0,-1)),c(n.page_location)){let{utmParams:e,cleanUrl:t,cleanQueryParams:r}=s(n.page_location);n.page_location=t,a(r),A(`campaign`,e)}g(`event`,`page_view`,n)}function M(e){let{appName:t}=m(),n={};typeof e==`string`?n.screen_name=e:`path`in e?n.screen_name=e.name??e.path:n=e,t&&n?.app_name===void 0&&(n.app_name=t),g(`event`,`screen_view`,n)}function N(e){S(`timing_complete`,e)}function P(e={}){return{send_page_view:!1,anonymize_ip:!0,...e}}function F(){let{tagId:e,config:t,groupName:n,linker:r,additionalAccounts:i,hooks:a,consentMode:o}=m();if(e){if(a?.[`config:init:before`]?.(),o===`granted`?y():o===`denied`&&b(),r&&T(r),g(`js`,new Date),g(`config`,e,P(t)),i)for(let e of i)g(`config`,e.tagId,P({groups:n,...e.config}));a?.[`config:init:after`]?.()}}function I(e){let{pageTracker:t}=m();return t?.exclude?typeof t.exclude==`function`?t.exclude(e):t.exclude?.some(({name:t,path:n}={})=>t&&t===e.name||n&&n===e.path):!1}function L(e){let{pageTracker:t,hooks:n}=m();if(I(e))return;n?.[`router:track:before`]?.(e);let r;if(t?.template&&(r=typeof t.template==`function`?t.template(e):t.template),t?.useScreenview){let t=r&&`screen_name`in r?r:e;M(t)}else{let t=r&&`page_path`in r?r:e;j(t)}n?.[`router:track:after`]?.(e)}async function R(){let{pageTracker:e}=m();if(!e?.router)return;let{router:t}=e;await t.isReady(),L(t.currentRoute.value),t.afterEach((e,t)=>{e.path!==t.path&&L(e)})} /** * Adds the Google Analytics gtag script to the application and initializes router * auto-tracking when enabled. */ async function z(){let{resource:e,dataLayerName:t,tagId:r,pageTracker:i,hooks:a}=m();if(r&&(F(),i?.router&&R(),e.inject))try{await n(`${e.url}?id=${r}&l=${t}`,{preconnect:e.preconnect,defer:e.defer,nonce:e.nonce}),a?.[`script:loaded`]?.()}catch(e){a?.[`script:error`]?.(e)}}const B=`_ga`; /** * Provides functionality to manage user consent. * @remark Make sure to set `initMode` to `manual` */ function V(){let n=e(()=>t()?!1:document.cookie.includes(B)),r=async()=>{await z(),y(`update`),window.location.reload()},i=async()=>{b(`update`),await d(B),window.location.reload()},a=async e=>{await z(),v(`update`,e),window.location.reload()};return n.value&&z(),{hasConsent:n,acceptAll:r,rejectAll:i,acceptCustom:a}}function H(){let{initMode:e}=m();e!==`manual`&&z()} /** * Configures Google Analytics gtag instance * @param settings - Configuration settings for the gtag plugin */ function U(e){h(e),H()}const W={config:_,consent:v,consentDeniedAll:b,consentGrantedAll:y,customMap:x,ecommerce:C,event:S,exception:w,linker:T,optIn:k,optOut:O,pageview:j,screenview:M,set:A,time:N,query:g}; /** * Creates and configures Google Analytics gtag instance for Vue application * @param settings - Configuration settings for the gtag plugin */ function G(e){return U(e),e=>{e.config.globalProperties.$gtag=W}}export{z as addGtag,_ as config,U as configure,v as consent,b as consentDeniedAll,y as consentGrantedAll,G as createGtag,x as customMap,C as ecommerce,S as event,w as exception,T as linker,k as optIn,O as optOut,j as pageview,g as query,M as screenview,A as set,N as time,V as useConsent};