UNPKG

@nuxt/scripts

Version:

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

72 lines (71 loc) 3.04 kB
import { withBase, withHttps, withoutProtocol, withoutTrailingSlash } from "ufo"; import { useRegistryScript } from "../utils.js"; import { useScriptEventPage } from "../composables/useScriptEventPage.js"; import { boolean, object, optional, string, number, union } from "#nuxt-scripts-validator"; import { logger } from "../logger.js"; export const MatomoAnalyticsOptions = object({ matomoUrl: optional(string()), siteId: optional(union([string(), number()])), cloudId: optional(string()), trackerUrl: optional(string()), trackPageView: optional(boolean()), enableLinkTracking: optional(boolean()), disableCookies: optional(boolean()), watch: optional(boolean()) }); export function useScriptMatomoAnalytics(_options) { return useRegistryScript("matomoAnalytics", (options) => { const normalizedCloudId = options?.cloudId ? withoutTrailingSlash(withoutProtocol(options.cloudId)) : void 0; const origin = options?.matomoUrl ? options.matomoUrl : `https://cdn.matomo.cloud/${normalizedCloudId}/`; const _paq = import.meta.client ? window._paq = window._paq || [] : []; return { scriptInput: { src: withBase(`/matomo.js`, origin), crossorigin: false }, schema: import.meta.dev ? MatomoAnalyticsOptions : void 0, scriptOptions: { use() { const _paqProxy = { push: (...args) => { if (window._paq && typeof window._paq.push === "function") { return window._paq.push(...args); } window._paq = window._paq || []; return window._paq.push(...args); } }; return { _paq: _paqProxy }; } }, clientInit: import.meta.server ? void 0 : () => { if (options?.enableLinkTracking) { _paq.push(["enableLinkTracking"]); } if (options?.disableCookies) { _paq.push(["disableCookies"]); } if (options?.trackerUrl || options?.matomoUrl) { _paq.push(["setTrackerUrl", options?.trackerUrl ? withHttps(options.trackerUrl) : withBase(`/matomo.php`, withHttps(options?.matomoUrl || ""))]); } else if (normalizedCloudId) { _paq.push(["setTrackerUrl", withBase(`/matomo.php`, withHttps(normalizedCloudId))]); } _paq.push(["setSiteId", String(options?.siteId) || "1"]); if (options?.trackPageView !== void 0) { if (import.meta.dev) { logger.warn("The `trackPageView` option is deprecated. Use `watch: true` (default) for automatic page view tracking, or remove this option entirely."); } if (options.trackPageView) { _paq.push(["trackPageView"]); } } else if (options?.watch !== false) { useScriptEventPage((payload) => { window._paq.push(["setDocumentTitle", payload.title]); window._paq.push(["setCustomUrl", payload.path]); window._paq.push(["trackPageView"]); }); } } }; }, _options); }