All files / src/utils ga.ts

61.9% Statements 26/42
40% Branches 20/50
83.33% Functions 5/6
61.53% Lines 24/39

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 1244x 4x   4x   4x                 106x   106x 105x   1x                                                   1x                                     4x 252x         4x       105x                 105x 105x 105x                               105x                 3x 3x 1x 1x 1x 1x             4x  
import { log } from "../api/client"
import { AutocompleteConfig, defaultGaConfig } from "../config"
 
const localStorageKey = "nostoAutocomplete:gaEvent"
 
export function trackGaPageView(options?: {
    delay?: boolean
    title?: string
    location?: string
}) {
    const {
        delay = false,
        title = document.title,
        location = window.location.href,
    } = options || {}
 
    if (delay) {
        saveToLocalStorage(title, location)
    } else {
        Iif ("gtag" in window && typeof window.gtag === "function") {
            const accounts =
                "google_tag_manager" in window &&
                typeof window.google_tag_manager === "object"
                    ? Object.keys(window.google_tag_manager || []).filter(
                          e => {
                              return e.substring(0, 2) == "G-"
                          }
                      )
                    : []
 
            if (accounts.length > 1) {
                for (let i = 0; i < accounts.length; i++) {
                    window.gtag("event", "page_view", {
                        page_title: title,
                        page_location: location,
                        send_to: accounts[i],
                    })
                }
            } else {
                window.gtag("event", "page_view", {
                    page_title: title,
                    page_location: location,
                })
            }
        }
        Iif (
            "ga" in window &&
            typeof window.ga === "function" &&
            "getAll" in window.ga &&
            typeof window.ga.getAll === "function"
        ) {
            try {
                const url = new URL(location)
                const trackers = window.ga!.getAll()
                Iif (trackers?.length > 0) {
                    trackers[0]?.send("pageview", url.pathname + url.search)
                }
            } catch (error) {
                log("Could not send pageview to GA", error, "warn")
            }
        }
    }
}
 
export const isGaEnabled = <State>(config: AutocompleteConfig<State>) =>
    typeof config.googleAnalytics === "boolean"
        ? config.googleAnalytics
        : typeof config.googleAnalytics === "object" &&
          config.googleAnalytics.enabled
 
export const getGaTrackUrl = <State>(
    value: string | undefined,
    config: AutocompleteConfig<State>
) => {
    const gaConfig = isGaEnabled(config)
        ? typeof config.googleAnalytics === "boolean"
            ? defaultGaConfig
            : {
                  ...defaultGaConfig,
                  ...config.googleAnalytics,
              }
        : undefined
 
    if (value && gaConfig) {
        try {
            return new URL(
                `${
                    gaConfig?.serpPath || location.pathname
                }?${`${encodeURIComponent(
                    gaConfig.queryParamName
                )}=${encodeURIComponent(value).replace(/%20/g, "+")}`}`,
                window.location.origin
            ).toString()
        } catch (error) {
            log("Could not create track url", error, "warn")
            return undefined
        }
    }
}
 
function saveToLocalStorage(title: string, location: string): void {
    localStorage.setItem(localStorageKey, JSON.stringify({ title, location }))
}
 
interface Event {
    title: string
    location: string
}
 
function consumeLocalStorageEvent(): void {
    const eventString = localStorage.getItem(localStorageKey)
    if (typeof eventString === "string") {
        localStorage.removeItem(localStorageKey)
        try {
            const event: Event = JSON.parse(eventString)
            trackGaPageView(event)
        } catch (e) {
            log("Could not consume pageView", e, "warn")
        }
    }
}
 
setTimeout(consumeLocalStorageEvent, 1000)