Add Microsoft Clarity tracking

This commit is contained in:
2569718930@qq.com
2026-06-24 16:25:49 +08:00
parent b8a1950932
commit 004439b736
3 changed files with 59 additions and 0 deletions
+2
View File
@@ -1,6 +1,7 @@
import type { Metadata } from "next";
import { Inter, JetBrains_Mono } from "next/font/google";
import { RegisterSW } from "@/components/dashboard/RegisterSW";
import { MicrosoftClarity } from "@/components/observability/MicrosoftClarity";
import "./globals.css";
const inter = Inter({
@@ -89,6 +90,7 @@ export default function RootLayout({
</a>
<main id="main-content">{children}</main>
<RegisterSW />
<MicrosoftClarity />
</body>
</html>
);
@@ -0,0 +1,23 @@
import Script from "next/script";
const MICROSOFT_CLARITY_PROJECT_ID = "xbydcq2lu2";
const MICROSOFT_CLARITY_SCRIPT = `
(function(c,l,a,r,i,t,y){
c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
})(window, document, "clarity", "script", "${MICROSOFT_CLARITY_PROJECT_ID}");
`;
export function MicrosoftClarity() {
if (process.env.NODE_ENV !== "production") {
return null;
}
return (
<Script id="microsoft-clarity" strategy="afterInteractive">
{MICROSOFT_CLARITY_SCRIPT}
</Script>
);
}
@@ -0,0 +1,34 @@
import fs from "node:fs";
import path from "node:path";
function assert(condition: unknown, message: string) {
if (!condition) throw new Error(message);
}
export function runTests() {
const projectRoot = process.cwd();
const componentPath = path.join(projectRoot, "components", "observability", "MicrosoftClarity.tsx");
const layoutPath = path.join(projectRoot, "app", "layout.tsx");
assert(fs.existsSync(componentPath), "Microsoft Clarity component must exist");
const component = fs.readFileSync(componentPath, "utf8");
const layout = fs.readFileSync(layoutPath, "utf8");
assert(
component.includes('import Script from "next/script"') &&
component.includes('strategy="afterInteractive"'),
"Microsoft Clarity must use next/script and load after hydration",
);
assert(
component.includes("xbydcq2lu2") &&
component.includes("https://www.clarity.ms/tag/") &&
component.includes('window, document, "clarity", "script"'),
"Microsoft Clarity must use the configured PolyWeather project script",
);
assert(
layout.includes("@/components/observability/MicrosoftClarity") &&
layout.includes("<MicrosoftClarity />"),
"root layout must render Microsoft Clarity globally",
);
}