Files
web/app/[lang]/Tracking.tsx
Arvid Norlin 5ccb6166c3 WIP: tracking
2024-02-14 10:57:37 +01:00

81 lines
2.5 KiB
TypeScript

"use client"
import "client-only"
import { useParams, usePathname, useSearchParams } from "next/navigation"
import { useEffect } from "react"
type WindowWithDataLayer = Window & {
datalayer: { [key: string]: any }
}
declare const window: WindowWithDataLayer
function createPageObject(pathName: string, queryString?: string) {
const [lang, ...segments] = pathName.split("/").filter((v: string) => v)
// Better to get lang from useParams() instead?? ⬆️
function getSiteSections(segments: string[]) {
const sitesections: { [key: string]: string } = {}
// Adobe expects the properties sitesection1 - sitessection6, hence the for-loop below
for (let i = 0; i < 6; i++) {
const key = "value" + (i + 1)
sitesections[key] = segments.slice(0, i + 1).join("|")
if (i > 0 && !segments[i]) {
sitesections[key] = sitesections[key].concat(
"|".repeat(i + 1 - segments.length)
)
}
}
return sitesections
}
const sitesections = getSiteSections(segments)
const { host: domain, href: pageurl } = window.location
const page_obj = {
pagename: "<a unique name of the page>", // CMS
pagetype: "<the type of page or content group>", // CMS
pageurl, // is window.location.href viable?
...sitesections,
createDate: "< the date when page is created>", // CMS
publishDate: "< the date when page is published>", // CMS
domain, // is window.location.host viable?
errorcode: null, // handle
querystring: queryString || "",
pageid: "<unique id of the page>", // CMS
sessionid: "<unique identifier of session>", // base on what?
domainlanguage: lang,
hotelbrand: "scandic", // "<scandic or scandicgo)>", what is this based on?
siteversion: "new-web", // good enough?
}
return page_obj
}
export default function Tracking() {
const pathName = usePathname()
const queryString = useSearchParams().toString()
useEffect(() => {
if (!window.datalayer) {
console.log("creating datalayer 🧑‍🔧")
window.datalayer = {}
} else {
const pageObject = createPageObject(pathName, queryString)
window.datalayer.page = pageObject
// NOTE: Is this irrelevant för drop 1?
// var user_obj = {
// loginstatus: "<if the user is logged in or not>",
// memberid: "<unique meeting package membership id for the user>",
// memberlevel: "<member level of user>",
// }
// datalayer.user = user_obj;
console.log("🤖 datalayer: ", window.datalayer)
}
}, [pathName, queryString])
return null
}