UNPKG

@nuxt/scripts

Version:

Load third-party scripts with better performance, privacy and DX in Nuxt Apps.

41 lines (40 loc) 1.38 kB
import { withQuery } from "ufo"; import { useRegistryScript } from "#nuxt-scripts/utils"; import { object, string, optional } from "#nuxt-scripts-validator"; export const GoogleAnalyticsOptions = object({ id: optional(string()), // The GA4 measurement ID (format: G-XXXXXXXX) l: optional(string()) // Optional global name for dataLayer (defaults to 'dataLayer') }); export function useScriptGoogleAnalytics(_options) { return useRegistryScript(_options?.key || "googleAnalytics", (options) => { const dataLayerName = options?.l ?? "dataLayer"; const w = import.meta.client ? window : {}; return { scriptInput: { src: withQuery("https://www.googletagmanager.com/gtag/js", { id: options?.id, l: options?.l }) }, schema: import.meta.dev ? GoogleAnalyticsOptions : void 0, scriptOptions: { use: () => { return { dataLayer: w[dataLayerName], gtag: w.gtag }; } }, clientInit: import.meta.server ? void 0 : () => { w[dataLayerName] = w[dataLayerName] || []; w.gtag = function() { w[dataLayerName].push(arguments); }; _options?.onBeforeGtagStart?.(w.gtag); w.gtag("js", /* @__PURE__ */ new Date()); if (options?.id) { w.gtag("config", options?.id); } } }; }, _options); }