MatomoTracker.tsx 873 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. 'use client';
  2. import { useEffect } from 'react';
  3. // 扩展 Window 接口以支持 Matomo Tag Manager
  4. declare global {
  5. interface Window {
  6. _mtm?: Array<any>;
  7. }
  8. }
  9. interface MatomoTrackerProps {
  10. containerUrl?: string;
  11. }
  12. export default function MatomoTracker({ containerUrl }: MatomoTrackerProps) {
  13. useEffect(() => {
  14. if (!containerUrl) {
  15. console.warn('Matomo 容器 URL 未配置');
  16. return;
  17. }
  18. // 初始化 Matomo Tag Manager
  19. const _mtm = (window._mtm = window._mtm || []);
  20. _mtm.push({ 'mtm.startTime': new Date().getTime(), event: 'mtm.Start' });
  21. const d = document;
  22. const g = d.createElement('script');
  23. const s = d.getElementsByTagName('script')[0];
  24. g.async = true;
  25. g.src = containerUrl;
  26. if (s.parentNode) {
  27. s.parentNode.insertBefore(g, s);
  28. }
  29. }, [containerUrl]);
  30. return null;
  31. }