基于nuxtJs的matomo统计部署以及自定义维度的统计

最近在导流 新站没有备案添加不了统计代码 干脆自己部署了一套matomo来自己统计 除了不能看关键词来路 其他都还可以

从网站A导流到网站B 链接后加参数 如domain.com/?source=xxx 用于统计 顺便利用sessionStorage来记录用户的一些信息 这样就可以实现每次点击带来的访客还贡献了多少PV

由于使用sessionStorage 所以当关闭浏览器后失效 下次访问就看用户是直接访问 还是继续从A站点的导流入口进入B站点了

代码如下:

declare global {
  interface Window {
    _paq?: any[]
  }
}

export default defineNuxtPlugin(() => {
  if (import.meta.server) return

  window._paq = window._paq || []
  const matomoUrl = 'https://tongji.dooqiu.com/'
  const siteId = '1'
  const CUSTOM_DIMENSION_ID = 1

  // 获取并保存 source 参数
  const getSource = (querySource?: any): string | null => {
    const source = (Array.isArray(querySource) ? querySource[0] : querySource) || sessionStorage.getItem('matomo_source')
    if (source) sessionStorage.setItem('matomo_source', source)
    return source as string | null
  }

  // 构建包含 pk_campaign 参数的 URL(Matomo 默认识别 pk_campaign 作为广告活动)
  const buildUrlWithCampaign = (path: string, source?: string | null): string => {
    if (!source) return path
    const url = new URL(path.startsWith('/') ? path : '/' + path, window.location.origin)
    if (!url.searchParams.has('pk_campaign')) url.searchParams.set('pk_campaign', source)
    if (!url.searchParams.has('source')) url.searchParams.set('source', source)
    return url.pathname + url.search
  }

  // 跟踪页面(统一处理初始页面和路由变化)
  const trackPage = (path: string, source?: string | null) => {
    if (source) {
      try {
        window._paq!.push(['setCustomDimension', CUSTOM_DIMENSION_ID, source])
      } catch (e) {
        console.warn('Matomo source 参数跟踪失败:', e)
      }
    }
    window._paq!.push(['setCustomUrl', buildUrlWithCampaign(path, source)])
    window._paq!.push(['trackPageView'])
  }

  // 配置 Matomo
  window._paq!.push(['setTrackerUrl', matomoUrl + 'matomo.php'])
  window._paq!.push(['setSiteId', siteId])
  window._paq!.push(['enableLinkTracking'])

  // 初始页面跟踪
  const router = useRouter()
  const route = useRoute()
  trackPage(route.fullPath, getSource(route.query.source))

  // 加载 Matomo 脚本
  const script = document.createElement('script')
  script.async = true
  script.src = matomoUrl + 'matomo.js'
  document.head.appendChild(script)

  // 监听路由变化
  router.afterEach((to) => {
    trackPage(to.fullPath, getSource(to.query.source))
  })
})

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注